cf272e5635a1eb66e72ec90810b864b10eff9f27
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / playerstats.qc
1 #include "playerstats.qh"
2 #if defined(CSQC)
3 #elif defined(MENUQC)
4 #elif defined(SVQC)
5     #include "constants.qh"
6     #include "util.qh"
7     #include <common/weapons/_all.qh>
8     #include "../server/anticheat.qh"
9     #include "../server/defs.qh"
10     #include "../server/scores.qh"
11     #include "../server/weapons/accuracy.qh"
12 #endif
13
14 #ifdef SVQC
15 void PlayerStats_Prematch()
16 {
17         //foobar
18 }
19
20 void PlayerStats_GameReport_AddPlayer(entity e)
21 {
22         if((PS_GR_OUT_DB < 0) || (e.playerstats_id)) { return; }
23
24         // set up player identification
25         string s = "";
26
27         if((e.crypto_idfp != "") && (CS(e).cvar_cl_allow_uidtracking == 1))
28                 { s = e.crypto_idfp; }
29         else if(IS_BOT_CLIENT(e))
30                 { s = sprintf("bot#%g#%s", skill, e.cleanname); }
31
32         if((s == "") || find(NULL, playerstats_id, s)) // already have one of the ID - next one can't be tracked then!
33         {
34                 if(IS_BOT_CLIENT(e))
35                         { s = sprintf("bot#%d", e.playerid); }
36                 else
37                         { s = sprintf("player#%d", e.playerid); }
38         }
39
40         e.playerstats_id = strzone(s);
41
42         // now add the player to the database
43         string key = sprintf("%s:*", e.playerstats_id);
44         string p = db_get(PS_GR_OUT_DB, key);
45
46         if(p == "")
47         {
48                 if(PS_GR_OUT_PL)
49                 {
50                         db_put(PS_GR_OUT_DB, key, PS_GR_OUT_PL);
51                         strunzone(PS_GR_OUT_PL);
52                 }
53                 else { db_put(PS_GR_OUT_DB, key, "#"); }
54                 PS_GR_OUT_PL = strzone(e.playerstats_id);
55         }
56 }
57
58 void PlayerStats_GameReport_AddTeam(int t)
59 {
60         if(PS_GR_OUT_DB < 0) { return; }
61
62         string key = sprintf("%d", t);
63         string p = db_get(PS_GR_OUT_DB, key);
64
65         if(p == "")
66         {
67                 if(PS_GR_OUT_TL)
68                 {
69                         db_put(PS_GR_OUT_DB, key, PS_GR_OUT_TL);
70                         strunzone(PS_GR_OUT_TL);
71                 }
72                 else { db_put(PS_GR_OUT_DB, key, "#"); }
73                 PS_GR_OUT_TL = strzone(key);
74         }
75 }
76
77 void PlayerStats_GameReport_AddEvent(string event_id)
78 {
79         if(PS_GR_OUT_DB < 0) { return; }
80
81         string key = sprintf("*:%s", event_id);
82         string p = db_get(PS_GR_OUT_DB, key);
83
84         if(p == "")
85         {
86                 if(PS_GR_OUT_EVL)
87                 {
88                         db_put(PS_GR_OUT_DB, key, PS_GR_OUT_EVL);
89                         strunzone(PS_GR_OUT_EVL);
90                 }
91                 else { db_put(PS_GR_OUT_DB, key, "#"); }
92                 PS_GR_OUT_EVL = strzone(event_id);
93         }
94 }
95
96 float PlayerStats_GameReport_Event(string prefix, string event_id, float value)
97 {
98         if((prefix == "") || PS_GR_OUT_DB < 0) { return 0; }
99
100         string key = sprintf("%s:%s", prefix, event_id);
101         float val = stof(db_get(PS_GR_OUT_DB, key));
102         val += value;
103         db_put(PS_GR_OUT_DB, key, ftos(val));
104         return val;
105 }
106
107 void PlayerStats_GameReport_Accuracy(entity p)
108 {
109         #define ACCMAC(suffix, field) \
110                 PlayerStats_GameReport_Event_Player(p, \
111                         sprintf("acc-%s-%s", it.netname, suffix), CS(p).accuracy.(field[i-1]));
112         FOREACH(Weapons, it != WEP_Null, {
113                 ACCMAC("hit", accuracy_hit)
114                 ACCMAC("fired", accuracy_fired)
115                 ACCMAC("cnt-hit", accuracy_cnt_hit)
116                 ACCMAC("cnt-fired", accuracy_cnt_fired)
117                 ACCMAC("frags", accuracy_frags)
118         });
119         #undef ACCMAC
120 }
121
122 void PlayerStats_GameReport_FinalizePlayer(entity p)
123 {
124         if((p.playerstats_id == "") || PS_GR_OUT_DB < 0) { return; }
125
126         // add global info!
127         if(p.alivetime)
128         {
129                 PlayerStats_GameReport_Event_Player(p, PLAYERSTATS_ALIVETIME, time - p.alivetime);
130                 p.alivetime = 0;
131         }
132
133         db_put(PS_GR_OUT_DB, sprintf("%s:_playerid", p.playerstats_id), ftos(p.playerid));
134
135         if(CS(p).cvar_cl_allow_uid2name == 1 || IS_BOT_CLIENT(p))
136                 db_put(PS_GR_OUT_DB, sprintf("%s:_netname", p.playerstats_id), playername(p, false));
137
138         if(teamplay)
139                 db_put(PS_GR_OUT_DB, sprintf("%s:_team", p.playerstats_id), ftos(p.team));
140
141         if(stof(db_get(PS_GR_OUT_DB, sprintf("%s:%s", p.playerstats_id, PLAYERSTATS_ALIVETIME))) > 0)
142                 PlayerStats_GameReport_Event_Player(p, PLAYERSTATS_JOINS, 1);
143
144         PlayerStats_GameReport_Accuracy(p);
145         anticheat_report_to_playerstats(p);
146
147         if(IS_REAL_CLIENT(p))
148         {
149                 if(CS(p).latency_cnt)
150                 {
151                         float latency = (CS(p).latency_sum / CS(p).latency_cnt);
152                         if(latency)
153                                 PlayerStats_GameReport_Event_Player(p, PLAYERSTATS_AVGLATENCY, latency);
154                 }
155
156                 db_put(PS_GR_OUT_DB, sprintf("%s:_ranked", p.playerstats_id), ftos(CS(p).cvar_cl_allow_uidranking));
157         }
158
159         strfree(p.playerstats_id);
160 }
161
162 void PlayerStats_GameReport(bool finished)
163 {
164         if(PS_GR_OUT_DB < 0) { return; }
165
166         PlayerScore_Sort(score_dummyfield, 0, 0, 0);
167         PlayerScore_Sort(scoreboard_pos, 1, 1, 1);
168         if(teamplay) { PlayerScore_TeamStats(); }
169
170         FOREACH_CLIENT(true, {
171                 // add personal score rank
172                 PlayerStats_GameReport_Event_Player(it, PLAYERSTATS_RANK, it.score_dummyfield);
173
174                 // scoreboard data
175                 if(it.scoreboard_pos)
176                 {
177                         // scoreboard is valid!
178                         PlayerStats_GameReport_Event_Player(it, PLAYERSTATS_SCOREBOARD_VALID, 1);
179
180                         // add scoreboard position
181                         PlayerStats_GameReport_Event_Player(it, PLAYERSTATS_SCOREBOARD_POS, it.scoreboard_pos);
182
183                         // add scoreboard data
184                         PlayerScore_PlayerStats(it);
185
186                         // if the match ended normally, add winning info
187                         if(finished)
188                         {
189                                 PlayerStats_GameReport_Event_Player(it, PLAYERSTATS_WINS, it.winning);
190                                 PlayerStats_GameReport_Event_Player(it, PLAYERSTATS_MATCHES, 1);
191                         }
192                 }
193
194                 // collect final player information
195                 PlayerStats_GameReport_FinalizePlayer(it);
196         });
197
198         if(autocvar_g_playerstats_gamereport_uri != "")
199         {
200                 PlayerStats_GameReport_DelayMapVote = true;
201                 url_multi_fopen(
202                         autocvar_g_playerstats_gamereport_uri,
203                         FILE_APPEND,
204                         PlayerStats_GameReport_Handler,
205                         NULL
206                 );
207         }
208         else
209         {
210                 PlayerStats_GameReport_DelayMapVote = false;
211                 db_close(PS_GR_OUT_DB);
212                 PS_GR_OUT_DB = -1;
213         }
214 }
215
216 void PlayerStats_GameReport_Init() // initiated before InitGameplayMode so that scores are added properly
217 {
218         if(autocvar_g_playerstats_gamereport_uri == "") { return; }
219
220         PS_GR_OUT_DB = db_create();
221
222         if(PS_GR_OUT_DB >= 0)
223         {
224                 PlayerStats_GameReport_DelayMapVote = true;
225
226                 serverflags |= SERVERFLAG_PLAYERSTATS;
227
228                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ALIVETIME);
229                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_AVGLATENCY);
230                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_WINS);
231                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_MATCHES);
232                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_JOINS);
233                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_SCOREBOARD_VALID);
234                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_SCOREBOARD_POS);
235                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_RANK);
236
237                 // accuracy stats
238                 FOREACH(Weapons, it != WEP_Null, {
239                         PlayerStats_GameReport_AddEvent(strcat("acc-", it.netname, "-hit"));
240                         PlayerStats_GameReport_AddEvent(strcat("acc-", it.netname, "-fired"));
241                         PlayerStats_GameReport_AddEvent(strcat("acc-", it.netname, "-cnt-hit"));
242                         PlayerStats_GameReport_AddEvent(strcat("acc-", it.netname, "-cnt-fired"));
243                         PlayerStats_GameReport_AddEvent(strcat("acc-", it.netname, "-frags"));
244                 });
245
246                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_3);
247                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_5);
248                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_10);
249                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_15);
250                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_20);
251                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_25);
252                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_KILL_SPREE_30);
253                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_BOTLIKE);
254                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_FIRSTBLOOD);
255                 PlayerStats_GameReport_AddEvent(PLAYERSTATS_ACHIEVEMENT_FIRSTVICTIM);
256
257                 anticheat_register_to_playerstats();
258         }
259         else { PlayerStats_GameReport_DelayMapVote = false; }
260 }
261
262 // this... is a hack, a temporary one until we get a proper duel gametype
263 // TODO: remove duel hack after servers have migrated to the proper duel gametype!
264 string PlayerStats_GetGametype()
265 {
266         if(IS_GAMETYPE(DEATHMATCH) && autocvar_g_maxplayers == 2)
267         {
268                 // probably duel, but let's make sure
269                 int plcount = 0;
270                 FOREACH_CLIENT(IS_PLAYER(it), ++plcount);
271                 if(plcount <= 2)
272                         return "duel";
273         }
274         return GetGametype();
275 }
276
277 void PlayerStats_GameReport_Handler(entity fh, entity pass, float status)
278 {
279         string t, tn;
280         string p, pn;
281         string e, en;
282         string nn, tt;
283         string s;
284
285         switch(status)
286         {
287                 // ======================================
288                 // -- OUTGOING GAME REPORT INFORMATION --
289                 // ======================================
290                 /* SPECIFICATIONS:
291                  * V: format version (always a fixed number) - this MUST be the first line!
292                  * #: comment (MUST be ignored by any parser)
293                  * R: release information on the server
294                  * G: game type
295                  * O: mod name (icon request) as in server browser
296                  * M: map name
297                  * I: match ID (see "matchid" in g_world.qc)
298                  * S: "hostname" of the server
299                  * C: number of "unpure" cvar changes
300                  * U: UDP port number of the server
301                  * D: duration of the match
302                  * L: "ladder" in which the server is participating in
303                  * P: player ID of an existing player; this also sets the owner for all following "n", "e" and "t" lines (lower case!)
304                  * Q: team number of an existing team (format: team#NN); this also sets the owner for all following "e" lines (lower case!)
305                  * i: player index
306                  * n: nickname of the player (optional)
307                  * t: team ID
308                  * e: followed by an event name, a space, and the event count/score
309                  *  event names can be:
310                  *   alivetime: total playing time of the player
311                  *   avglatency: average network latency compounded throughout the match
312                  *   wins: number of games won (can only be set if matches is set)
313                  *   matches: number of matches played to the end (not aborted by map switch)
314                  *   joins: number of matches joined (always 1 unless player never played during the match)
315                  *   scoreboardvalid: set to 1 if the player was there at the end of the match
316                  *   total-<scoreboardname>: total score of that scoreboard item
317                  *   scoreboard-<scoreboardname>: end-of-game score of that scoreboard item (can differ in non-team games)
318                  *   achievement-<achievementname>: achievement counters (their "count" is usually 1 if nonzero at all)
319                  *   kills-<index>: number of kills against the indexed player
320                  *   rank <number>: rank of player
321                  *   acc-<weapon netname>-hit: total damage dealt
322                  *   acc-<weapon netname>-fired: total damage that all fired projectiles *could* have dealt
323                  *   acc-<weapon netname>-cnt-hit: amount of shots that actually hit
324                  *   acc-<weapon netname>-cnt-fired: amount of fired shots
325                  *   acc-<weapon netname>-frags: amount of frags dealt by weapon
326                  */
327                 case URL_READY_CANWRITE:
328                 {
329                         url_fputs(fh, "V 9\n");
330                         #ifdef WATERMARK
331                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
332                         #endif
333                         url_fputs(fh, sprintf("G %s\n", PlayerStats_GetGametype()));
334                         url_fputs(fh, sprintf("O %s\n", modname));
335                         url_fputs(fh, sprintf("M %s\n", GetMapname()));
336                         url_fputs(fh, sprintf("I %s\n", matchid));
337                         url_fputs(fh, sprintf("S %s\n", cvar_string("hostname")));
338                         url_fputs(fh, sprintf("C %d\n", cvar_purechanges_count));
339                         url_fputs(fh, sprintf("U %d\n", cvar("port")));
340                         url_fputs(fh, sprintf("D %f\n", max(0, time - game_starttime)));
341                         url_fputs(fh, sprintf("L %s\n", autocvar_g_playerstats_gamereport_ladder));
342
343                         // TEAMS
344                         if(teamplay)
345                         {
346                                 for(t = PS_GR_OUT_TL; (tn = db_get(PS_GR_OUT_DB, sprintf("%d", stof(t)))) != ""; t = tn)
347                                 {
348                                         // start team section
349                                         url_fputs(fh, sprintf("Q team#%s\n", t));
350
351                                         // output team events // todo: does this do unnecessary loops? perhaps we should do a separate "team_events_last" tracker..."
352                                         for(e = PS_GR_OUT_EVL; (en = db_get(PS_GR_OUT_DB, sprintf("*:%s", e))) != ""; e = en)
353                                         {
354                                                 float v = stof(db_get(PS_GR_OUT_DB, sprintf("team#%d:%s", stof(t), e)));
355                                                 if(v != 0) { url_fputs(fh, sprintf("e %s %g\n", e, v)); }
356                                         }
357                                 }
358                         }
359
360                         // PLAYERS
361                         for(p = PS_GR_OUT_PL; (pn = db_get(PS_GR_OUT_DB, sprintf("%s:*", p))) != ""; p = pn)
362                         {
363                                 // start player section
364                                 url_fputs(fh, sprintf("P %s\n", p));
365
366                                 // playerid/index (entity number for this server)
367                                 nn = db_get(PS_GR_OUT_DB, sprintf("%s:_playerid", p));
368                                 if(nn != "") { url_fputs(fh, sprintf("i %s\n", nn)); }
369
370                                 // player name
371                                 nn = db_get(PS_GR_OUT_DB, sprintf("%s:_netname", p));
372                                 if(nn != "") { url_fputs(fh, sprintf("n %s\n", nn)); }
373
374                                 // team identification number
375                                 if(teamplay)
376                                 {
377                                         tt = db_get(PS_GR_OUT_DB, sprintf("%s:_team", p));
378                                         url_fputs(fh, sprintf("t %s\n", tt));
379                                 }
380
381                                 // elo ranking enabled
382                                 nn = db_get(PS_GR_OUT_DB, sprintf("%s:_ranked", p));
383                                 if(nn != "") { url_fputs(fh, sprintf("r %s\n", nn)); }
384
385                                 // output player events
386                                 for(e = PS_GR_OUT_EVL; (en = db_get(PS_GR_OUT_DB, sprintf("*:%s", e))) != ""; e = en)
387                                 {
388                                         float v = stof(db_get(PS_GR_OUT_DB, sprintf("%s:%s", p, e)));
389                                         if(v != 0) { url_fputs(fh, sprintf("e %s %g\n", e, v)); }
390                                 }
391                         }
392                         url_fputs(fh, "\n");
393                         url_fclose(fh);
394                         break;
395                 }
396
397                 // ======================================
398                 // -- INCOMING GAME REPORT INFORMATION --
399                 // ======================================
400                 /* SPECIFICATIONS:
401                  * stuff
402                  */
403                 case URL_READY_CANREAD:
404                 {
405                         // url_fclose is processing, we got a response for writing the data
406                         // this must come from HTTP
407                         LOG_TRACE("Got response from player stats server:");
408                         while((s = url_fgets(fh))) { LOG_TRACE("  ", s); }
409                         LOG_TRACE("End of response.");
410                         url_fclose(fh);
411                         break;
412                 }
413
414                 case URL_READY_CLOSED:
415                 {
416                         // url_fclose has finished
417                         LOG_TRACE("Player stats written");
418                         PlayerStats_GameReport_DelayMapVote = false;
419                         if(PS_GR_OUT_DB >= 0)
420                         {
421                                 db_close(PS_GR_OUT_DB);
422                                 PS_GR_OUT_DB = -1;
423                         }
424                         break;
425                 }
426
427                 case URL_READY_ERROR:
428                 default:
429                 {
430                         LOG_INFO("Player stats writing failed: ", ftos(status));
431                         PlayerStats_GameReport_DelayMapVote = false;
432                         if(PS_GR_OUT_DB >= 0)
433                         {
434                                 db_close(PS_GR_OUT_DB);
435                                 PS_GR_OUT_DB = -1;
436                         }
437                         break;
438                 }
439         }
440 }
441
442 void PlayerStats_PlayerBasic(entity joiningplayer, float newrequest)
443 {
444         GameRules_scoring_add(joiningplayer, ELO, -1);
445         // http://stats.xonotic.org/player/GgXRw6piDtFIbMArMuiAi8JG4tiin8VLjZgsKB60Uds=/elo.txt
446         if(autocvar_g_playerstats_playerbasic_uri != "")
447         {
448                 string uri = autocvar_g_playerstats_playerbasic_uri;
449                 if (joiningplayer.crypto_idfp == "") {
450                         GameRules_scoring_add(joiningplayer, ELO, -1);
451                 } else {
452                         // create the database if it doesn't already exist
453                         if(PS_B_IN_DB < 0)
454                                 PS_B_IN_DB = db_create();
455
456                         // now request the information
457                         uri = strcat(uri, "/player/", uri_escape(uri_escape(uri_escape(joiningplayer.crypto_idfp))), "/elo.txt");
458                         LOG_TRACE("Retrieving playerstats from URL: ", uri);
459                         url_single_fopen(
460                                 uri,
461                                 FILE_APPEND,
462                                 PlayerStats_PlayerBasic_Handler,
463                                 joiningplayer
464                         );
465
466                         // set status appropriately // todo: check whether the player info exists in the database previously
467                         if(newrequest)
468                         {
469                                 // database still contains useful information, so don't clear it of a useful status
470                                 joiningplayer.playerstats_basicstatus = PS_B_STATUS_WAITING;
471                         }
472                         else
473                         {
474                                 // database was previously empty or never hit received status for some reason
475                                 joiningplayer.playerstats_basicstatus = PS_B_STATUS_UPDATING;
476                         }
477                 }
478         }
479         else
480         {
481                 // server has this disabled, kill the DB and set status to idle
482                 GameRules_scoring_add(joiningplayer, ELO, -1);
483                 if(PS_B_IN_DB >= 0)
484                 {
485                         db_close(PS_B_IN_DB);
486                         PS_B_IN_DB = -1;
487
488                         FOREACH_CLIENT(IS_REAL_CLIENT(it), it.playerstats_basicstatus = PS_B_STATUS_IDLE);
489                 }
490         }
491 }
492
493 void PlayerStats_PlayerBasic_CheckUpdate(entity joiningplayer)
494 {
495         // determine whether we should retrieve playerbasic information again
496
497         LOG_TRACEF("PlayerStats_PlayerBasic_CheckUpdate('%s'): %f",
498                 joiningplayer.netname,
499                 time
500         );
501
502         // TODO: check to see if this playerid is inside the database already somehow...
503         // for now we'll just check the field, but this won't work for players who disconnect and reconnect properly
504         // although maybe we should just submit another request ANYWAY?
505         if(!joiningplayer.playerstats_basicstatus)
506         {
507                 PlayerStats_PlayerBasic(
508                         joiningplayer,
509                         (joiningplayer.playerstats_basicstatus == PS_B_STATUS_RECEIVED)
510                 );
511         }
512 }
513
514 void PlayerStats_PlayerBasic_Handler(entity fh, entity p, float status)
515 {
516         switch(status)
517         {
518                 case URL_READY_CANWRITE:
519                 {
520                         LOG_TRACE("-- Sending data to player stats server");
521                         /*url_fputs(fh, "V 1\n");
522                         #ifdef WATERMARK
523                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
524                         #endif
525                         url_fputs(fh, sprintf("l %s\n", cvar_string("_menu_prvm_language"))); // language
526                         url_fputs(fh, sprintf("c %s\n", cvar_string("_menu_prvm_country"))); // country
527                         url_fputs(fh, sprintf("g %s\n", cvar_string("_cl_gender"))); // gender
528                         url_fputs(fh, sprintf("n %s\n", cvar_string("_cl_name"))); // name
529                         url_fputs(fh, sprintf("m %s %s\n", cvar_string("_cl_playermodel"), cvar_string("_cl_playerskin"))); // model/skin
530                         */url_fputs(fh, "\n");
531                         url_fclose(fh);
532                         return;
533                 }
534
535                 case URL_READY_CANREAD:
536                 {
537                         bool handled = false;
538                         string gt = string_null;
539                         for (string s = ""; (s = url_fgets(fh)); ) {
540                                 int n = tokenizebyseparator(s, " "); // key value? data
541                                 if (n == 1) continue;
542                                 string key = "", value = "", data = "";
543                                 if (n == 2) {
544                     key = argv(0);
545                     data = argv(1);
546                                 } else if (n >= 3) {
547                     key = argv(0);
548                     value = argv(1);
549                     data = argv(2);
550                                 }
551                 switch (key) {
552                     case "V":
553                         // PlayerInfo_AddItem(p, "_version", data);
554                         break;
555                     case "R":
556                         // PlayerInfo_AddItem(p, "_release", data);
557                         break;
558                     case "T":
559                         // PlayerInfo_AddItem(p, "_time", data);
560                         break;
561                     case "S":
562                         // PlayerInfo_AddItem(p, "_statsurl", data);
563                         break;
564                     case "P":
565                         // PlayerInfo_AddItem(p, "_hashkey", data);
566                         break;
567                     case "n":
568                         // PlayerInfo_AddItem(p, "_playernick", data);
569                         break;
570                     case "i":
571                         // PlayerInfo_AddItem(p, "_playerid", data);
572                         // p.xonstat_id = stof(data);
573                         break;
574                     case "G":
575                         gt = data;
576                         break;
577                     case "e":
578                         LOG_TRACE("G: ", gt);
579                         LOG_TRACE("e: ", data);
580                         if (gt == PlayerStats_GetGametype()) {
581                             handled = true;
582                             float e = stof(data);
583                             GameRules_scoring_add(p, ELO, +1 + e);
584                         }
585                         if (gt == "") {
586                             // PlayerInfo_AddItem(p, value, data);
587                         } else {
588                             // PlayerInfo_AddItem(p, sprintf("%s/%s", gt, value), data);
589                         }
590                         break;
591                 }
592                         }
593                         url_fclose(fh);
594                         if (handled) return;
595                         break;
596                 }
597                 case URL_READY_CLOSED:
598                 {
599                         // url_fclose has finished
600                         LOG_INFO("Player stats synchronized with server");
601                         return;
602                 }
603
604                 case URL_READY_ERROR:
605                 default:
606                 {
607                         LOG_INFO("Receiving player stats failed: ", ftos(status));
608                         break;
609                 }
610         }
611         GameRules_scoring_add(p, ELO, -1);
612 }
613 #endif // SVQC
614
615 #ifdef MENUQC
616
617
618 #if 0 // reading the entire DB at once
619         string e = "", en = "";
620         float i = 0;
621         for(e = PS_D_IN_EVL; (en = db_get(PS_D_IN_DB, e)) != ""; e = en)
622         {
623                 LOG_INFOF("%d:%s:%s", i, e, db_get(PS_D_IN_DB, sprintf("#%s", e)));
624                 ++i;
625         }
626 #endif
627
628 void PlayerStats_PlayerDetail_AddItem(string event, string data)
629 {
630         if(PS_D_IN_DB < 0) { return; }
631
632         // create a marker for the event so that we can access it later
633         string marker = sprintf("%s", event);
634         if(db_get(PS_D_IN_DB, marker) == "")
635         {
636                 if(PS_D_IN_EVL)
637                 {
638                         db_put(PS_D_IN_DB, marker, PS_D_IN_EVL);
639                         strunzone(PS_D_IN_EVL);
640                 }
641                 else { db_put(PS_D_IN_DB, marker, "#"); }
642                 PS_D_IN_EVL = strzone(marker);
643         }
644
645         // now actually set the event data
646         db_put(PS_D_IN_DB, sprintf("#%s", event), data);
647         LOG_TRACE("Added item ", sprintf("#%s", event), "=", data, " to PS_D_IN_DB");
648 }
649
650 void PlayerStats_PlayerDetail()
651 {
652         // http://stats.xonotic.org/player/me
653         if((autocvar_g_playerstats_playerdetail_uri != "") && (crypto_getmyidstatus(0) > 0))
654         {
655                 // create the database if it doesn't already exist
656                 if(PS_D_IN_DB < 0)
657                         PS_D_IN_DB = db_create();
658
659                 //uri = strcat(uri, "/player/", uri_escape(crypto_getmyidfp(0)));
660                 LOG_TRACE("Retrieving playerstats from URL: ", autocvar_g_playerstats_playerdetail_uri);
661                 url_single_fopen(
662                         autocvar_g_playerstats_playerdetail_uri,
663                         FILE_APPEND,
664                         PlayerStats_PlayerDetail_Handler,
665                         NULL
666                 );
667
668                 PlayerStats_PlayerDetail_Status = PS_D_STATUS_WAITING;
669         }
670         else
671         {
672                 // player has this disabled, kill the DB and set status to idle
673                 if(PS_D_IN_DB >= 0)
674                 {
675                         db_close(PS_D_IN_DB);
676                         PS_D_IN_DB = -1;
677                 }
678
679                 PlayerStats_PlayerDetail_Status = PS_D_STATUS_IDLE;
680         }
681 }
682
683 void PlayerStats_PlayerDetail_CheckUpdate()
684 {
685         // determine whether we should retrieve playerdetail information again
686         float gamecount = cvar("cl_matchcount");
687
688         #if 0
689         LOG_INFOF("PlayerStats_PlayerDetail_CheckUpdate(): %f >= %f, %d > %d",
690                 time,
691                 PS_D_NEXTUPDATETIME,
692                 PS_D_LASTGAMECOUNT,
693                 gamecount
694         );
695         #endif
696
697         if(
698                 (time >= PS_D_NEXTUPDATETIME)
699                 ||
700                 (gamecount > PS_D_LASTGAMECOUNT)
701         )
702         {
703                 PlayerStats_PlayerDetail();
704                 PS_D_NEXTUPDATETIME = (time + autocvar_g_playerstats_playerdetail_autoupdatetime);
705                 PS_D_LASTGAMECOUNT = gamecount;
706         }
707 }
708
709 void PlayerStats_PlayerDetail_Handler(entity fh, entity unused, float status)
710 {
711         switch(status)
712         {
713                 case URL_READY_CANWRITE:
714                 {
715                         LOG_TRACE("PlayerStats_PlayerDetail_Handler(): Sending data to player stats server...");
716                         url_fputs(fh, "V 1\n");
717                         #ifdef WATERMARK
718                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
719                         #endif
720                         url_fputs(fh, sprintf("l %s\n", cvar_string("_menu_prvm_language"))); // language
721                         //url_fputs(fh, sprintf("c %s\n", cvar_string("_cl_country"))); // country
722                         //url_fputs(fh, sprintf("g %s\n", cvar_string("_cl_gender"))); // gender
723                         url_fputs(fh, sprintf("n %s\n", cvar_string("_cl_name"))); // name
724                         url_fputs(fh, sprintf("m %s %s\n", cvar_string("_cl_playermodel"), cvar_string("_cl_playerskin"))); // model/skin
725                         url_fputs(fh, "\n");
726                         url_fclose(fh);
727                         break;
728                 }
729
730                 case URL_READY_CANREAD:
731                 {
732                         //print("PlayerStats_PlayerDetail_Handler(): Got response from player stats server:\n");
733                         string input = "";
734                         string gametype = "overall";
735                         while((input = url_fgets(fh)))
736                         {
737                                 float count = tokenizebyseparator(input, " ");
738                                 string key = "", event = "", data = "";
739
740                                 if(argv(0) == "#") { continue; }
741
742                                 if(count == 2)
743                                 {
744                                         key = argv(0);
745                                         data = substring(input, argv_start_index(1), strlen(input) - argv_start_index(1));
746                                 }
747                                 else if(count >= 3)
748                                 {
749                                         key = argv(0);
750                                         event = argv(1);
751                                         data = substring(input, argv_start_index(2), strlen(input) - argv_start_index(2));
752                                 }
753                                 else { continue; }
754
755                                 switch(key)
756                                 {
757                                         // general info
758                                         case "V": PlayerStats_PlayerDetail_AddItem("version", data); break;
759                                         case "R": PlayerStats_PlayerDetail_AddItem("release", data); break;
760                                         case "T": PlayerStats_PlayerDetail_AddItem("time", data); break;
761
762                                         // player info
763                                         case "S": PlayerStats_PlayerDetail_AddItem("statsurl", data); break;
764                                         case "P": PlayerStats_PlayerDetail_AddItem("hashkey", data); break;
765                                         case "n": PlayerStats_PlayerDetail_AddItem("playernick", data); break;
766                                         case "i": PlayerStats_PlayerDetail_AddItem("playerid", data); break;
767
768                                         // other/event info
769                                         case "G": gametype = data; break;
770                                         case "e":
771                                         {
772                                                 if(event != "" && data != "")
773                                                 {
774                                                         PlayerStats_PlayerDetail_AddItem(
775                                                                 sprintf(
776                                                                         "%s/%s",
777                                                                         gametype,
778                                                                         event
779                                                                 ),
780                                                                 data
781                                                         );
782                                                 }
783                                                 break;
784                                         }
785
786                                         default:
787                                         {
788                                                 LOG_INFOF(
789                                                         "PlayerStats_PlayerDetail_Handler(): ERROR: "
790                                                         "Key went unhandled? Is our version outdated?\n"
791                                                         "PlayerStats_PlayerDetail_Handler(): "
792                                                         "Key '%s', Event '%s', Data '%s'",
793                                                         key,
794                                                         event,
795                                                         data
796                                                 );
797                                                 break;
798                                         }
799                                 }
800
801                                 #if 0
802                                 LOG_INFOF(
803                                         "PlayerStats_PlayerDetail_Handler(): "
804                                         "Key '%s', Event '%s', Data '%s'",
805                                         key,
806                                         event,
807                                         data
808                                 );
809                                 #endif
810                         }
811                         //print("PlayerStats_PlayerDetail_Handler(): End of response.\n");
812                         url_fclose(fh);
813                         PlayerStats_PlayerDetail_Status = PS_D_STATUS_RECEIVED;
814                         statslist.getStats(statslist);
815                         break;
816                 }
817
818                 case URL_READY_CLOSED:
819                 {
820                         // url_fclose has finished
821                         LOG_INFO("PlayerStats_PlayerDetail_Handler(): Player stats synchronized with server.");
822                         break;
823                 }
824
825                 case URL_READY_ERROR:
826                 default:
827                 {
828                         LOG_INFO("PlayerStats_PlayerDetail_Handler(): Receiving player stats failed: ", ftos(status));
829                         PlayerStats_PlayerDetail_Status = PS_D_STATUS_ERROR;
830                         if(PS_D_IN_DB >= 0)
831                         {
832                                 db_close(PS_D_IN_DB);
833                                 PS_D_IN_DB = -1;
834                         }
835                         break;
836                 }
837         }
838 }
839 #endif
840
841 /*
842 void PlayerInfo_AddPlayer(entity e)
843 {
844         if(playerinfo_db < 0)
845                 return;
846
847         string key;
848         key = sprintf("#%d:*", e.playerid); // TODO: use hashkey instead?
849
850         string p;
851         p = db_get(playerinfo_db, key);
852         if(p == "")
853         {
854                 if(playerinfo_last)
855                 {
856                         db_put(playerinfo_db, key, playerinfo_last);
857                         strunzone(playerinfo_last);
858                 }
859                 else
860                         db_put(playerinfo_db, key, "#");
861                 playerinfo_last = strzone(ftos(e.playerid));
862                 print("  Added player ", ftos(e.playerid), " to playerinfo_db\n");//DEBUG//
863         }
864 }
865
866 void PlayerInfo_AddItem(entity e, string item_id, string val)
867 {
868         if(playerinfo_db < 0)
869                 return;
870
871         string key;
872         key = sprintf("*:%s", item_id);
873
874         string p;
875         p = db_get(playerinfo_db, key);
876         if(p == "")
877         {
878                 if(playerinfo_events_last)
879                 {
880                         db_put(playerinfo_db, key, playerinfo_events_last);
881                         strunzone(playerinfo_events_last);
882                 }
883                 else
884                         db_put(playerinfo_db, key, "#");
885                 playerinfo_events_last = strzone(item_id);
886         }
887
888         key = sprintf("#%d:%s", e.playerid, item_id);
889         db_put(playerinfo_db, key, val);
890         print("  Added item ", key, "=", val, " to playerinfo_db\n");//DEBUG//
891 }
892
893 string PlayerInfo_GetItem(entity e, string item_id)
894 {
895         if(playerinfo_db < 0)
896                 return "";
897
898         string key;
899         key = sprintf("#%d:%s",  e.playerid, item_id);
900         return db_get(playerinfo_db, key);
901 }
902
903 string PlayerInfo_GetItemLocal(string item_id)
904 {
905         entity p = spawn();
906         p.playerid = 0;
907         return PlayerInfo_GetItem(p, item_id);
908 }
909
910 void PlayerInfo_ready(entity fh, entity p, float status)
911 {
912         float n;
913         string s;
914
915         PlayerInfo_AddPlayer(p);
916
917         switch(status)
918         {
919                 case URL_READY_CANWRITE:
920                         print("-- Sending data to player stats server\n");
921                         url_fputs(fh, "V 1\n");
922 #ifdef WATERMARK
923                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
924 #endif
925 #ifdef MENUQC
926                         url_fputs(fh, sprintf("l %s\n", cvar_string("_menu_prvm_language"))); // language
927                         url_fputs(fh, sprintf("c %s\n", cvar_string("_menu_prvm_country"))); // country
928                         url_fputs(fh, sprintf("g %s\n", cvar_string("_cl_gender"))); // gender
929                         url_fputs(fh, sprintf("n %s\n", cvar_string("_cl_name"))); // name
930                         url_fputs(fh, sprintf("m %s %s\n", cvar_string("_cl_playermodel"), cvar_string("_cl_playerskin"))); // model/skin
931 #endif
932                         url_fputs(fh, "\n");
933                         url_fclose(fh);
934                         break;
935                 case URL_READY_CANREAD:
936                         print("-- Got response from player stats server:\n");
937                         string gametype = string_null;
938                         while((s = url_fgets(fh)))
939                         {
940                                 print("  ", s, "\n");
941
942                                 string key = "", value = "", data = "";
943
944                                 n = tokenizebyseparator(s, " "); // key (value) data
945                                 if (n == 1)
946                                         continue;
947                                 else if (n == 2)
948                                 {
949                                         key = argv(0);
950                                         data = argv(1);
951                                 }
952                                 else if (n >= 3)
953                                 {
954                                         key = argv(0);
955                                         value = argv(1);
956                                         data = argv(2);
957                                 }
958
959                                 if (data == "")
960                                         continue;
961
962                                 if (key == "#")
963                                         continue;
964                                 else if (key == "V")
965                                         PlayerInfo_AddItem(p, "_version", data);
966                                 else if (key == "R")
967                                         PlayerInfo_AddItem(p, "_release", data);
968                                 else if (key == "T")
969                                         PlayerInfo_AddItem(p, "_time", data);
970                                 else if (key == "S")
971                                         PlayerInfo_AddItem(p, "_statsurl", data);
972                                 else if (key == "P")
973                                         PlayerInfo_AddItem(p, "_hashkey", data);
974                                 else if (key == "n")
975                                         PlayerInfo_AddItem(p, "_playernick", data);
976                                 else if (key == "i")
977                                         PlayerInfo_AddItem(p, "_playerid", data);
978                                 else if (key == "G")
979                                         gametype = data;
980                                 else if (key == "e" && value != "")
981                                 {
982                                         if (gametype == "")
983                                                 PlayerInfo_AddItem(p, value, data);
984                                         else
985                                                 PlayerInfo_AddItem(p, sprintf("%s/%s", gametype, value), data);
986                                 }
987                                 else
988                                         continue;
989                         }
990                         print("-- End of response.\n");
991                         url_fclose(fh);
992                         break;
993                 case URL_READY_CLOSED:
994                         // url_fclose has finished
995                         print("Player stats synchronized with server\n");
996                         break;
997                 case URL_READY_ERROR:
998                 default:
999                         print("Receiving player stats failed: ", ftos(status), "\n");
1000                         break;
1001         }
1002 }
1003
1004 void PlayerInfo_Init()
1005 {
1006         playerinfo_db = db_create();
1007 }
1008
1009 #ifdef SVQC
1010 void PlayerInfo_Basic(entity p)
1011 {
1012         print("-- Getting basic PlayerInfo for player ",ftos(p.playerid)," (SVQC)\n");
1013
1014         if(playerinfo_db < 0)
1015                 return;
1016
1017         string uri;
1018         uri = autocvar_g_playerinfo_uri;
1019         if(uri != "" && p.crypto_idfp != "")
1020         {
1021                 uri = strcat(uri, "/elo/", uri_escape(p.crypto_idfp));
1022                 print("Retrieving playerstats from URL: ", uri, "\n");
1023                 url_single_fopen(uri, FILE_READ, PlayerInfo_ready, p);
1024         }
1025 }
1026 #endif
1027
1028 #ifdef MENUQC
1029 void PlayerInfo_Details()
1030 {
1031         print("-- Getting detailed PlayerInfo for local player (MENUQC)\n");
1032
1033         if(playerinfo_db < 0)
1034                 return;
1035
1036         string uri;
1037         uri = autocvar_g_playerinfo_uri; // FIXME
1038         if(uri != "" && crypto_getmyidstatus(0) > 0)
1039         {
1040                 //uri = strcat(uri, "/player/", uri_escape(crypto_getmyidfp(0)));
1041                 uri = strcat(uri, "/player/me");
1042                 print("Retrieving playerstats from URL: ", uri, "\n");
1043                 url_single_fopen(uri, FILE_APPEND, PlayerInfo_ready, NULL);
1044         }
1045 }
1046 #endif
1047
1048 #ifdef CSQC
1049 // FIXME - crypto_* builtin functions missing in CSQC (csprogsdefs.qh:885)
1050 void PlayerInfo_Details()
1051 {
1052         print("-- Getting detailed PlayerInfo for local player (CSQC)\n");
1053
1054         if(playerinfo_db < 0)
1055                 return;
1056
1057         string uri;
1058         uri = autocvar_g_playerinfo_uri; // FIXME
1059         if(uri != "" && crypto_getmyidstatus(0) > 0)
1060         {
1061                 uri = strcat(uri, "/player/", uri_escape(crypto_getmyidfp(0)));
1062                 print("Retrieving playerstats from URL: ", uri, "\n");
1063                 url_single_fopen(uri, FILE_READ, PlayerInfo_ready, p);
1064         }
1065 }
1066
1067 #endif
1068 */