3599e84e617b53fcd40a4c78204f725ed3b501f0
[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(float 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(float 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 string PlayerStats_GetGametype()
264 {
265         if(IS_GAMETYPE(DEATHMATCH) && autocvar_g_maxplayers == 2)
266         {
267                 // probably duel, but let's make sure
268                 int plcount = 0;
269                 FOREACH_CLIENT(IS_PLAYER(it), ++plcount);
270                 if(plcount <= 2)
271                         return "duel";
272         }
273         return GetGametype();
274 }
275
276 void PlayerStats_GameReport_Handler(entity fh, entity pass, float status)
277 {
278         string t, tn;
279         string p, pn;
280         string e, en;
281         string nn, tt;
282         string s;
283
284         switch(status)
285         {
286                 // ======================================
287                 // -- OUTGOING GAME REPORT INFORMATION --
288                 // ======================================
289                 /* SPECIFICATIONS:
290                  * V: format version (always a fixed number) - this MUST be the first line!
291                  * #: comment (MUST be ignored by any parser)
292                  * R: release information on the server
293                  * G: game type
294                  * O: mod name (icon request) as in server browser
295                  * M: map name
296                  * I: match ID (see "matchid" in g_world.qc)
297                  * S: "hostname" of the server
298                  * C: number of "unpure" cvar changes
299                  * U: UDP port number of the server
300                  * D: duration of the match
301                  * L: "ladder" in which the server is participating in
302                  * P: player ID of an existing player; this also sets the owner for all following "n", "e" and "t" lines (lower case!)
303                  * Q: team number of an existing team (format: team#NN); this also sets the owner for all following "e" lines (lower case!)
304                  * i: player index
305                  * n: nickname of the player (optional)
306                  * t: team ID
307                  * e: followed by an event name, a space, and the event count/score
308                  *  event names can be:
309                  *   alivetime: total playing time of the player
310                  *   avglatency: average network latency compounded throughout the match
311                  *   wins: number of games won (can only be set if matches is set)
312                  *   matches: number of matches played to the end (not aborted by map switch)
313                  *   joins: number of matches joined (always 1 unless player never played during the match)
314                  *   scoreboardvalid: set to 1 if the player was there at the end of the match
315                  *   total-<scoreboardname>: total score of that scoreboard item
316                  *   scoreboard-<scoreboardname>: end-of-game score of that scoreboard item (can differ in non-team games)
317                  *   achievement-<achievementname>: achievement counters (their "count" is usually 1 if nonzero at all)
318                  *   kills-<index>: number of kills against the indexed player
319                  *   rank <number>: rank of player
320                  *   acc-<weapon netname>-hit: total damage dealt
321                  *   acc-<weapon netname>-fired: total damage that all fired projectiles *could* have dealt
322                  *   acc-<weapon netname>-cnt-hit: amount of shots that actually hit
323                  *   acc-<weapon netname>-cnt-fired: amount of fired shots
324                  *   acc-<weapon netname>-frags: amount of frags dealt by weapon
325                  */
326                 case URL_READY_CANWRITE:
327                 {
328                         url_fputs(fh, "V 9\n");
329                         #ifdef WATERMARK
330                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
331                         #endif
332                         url_fputs(fh, sprintf("G %s\n", PlayerStats_GetGametype()));
333                         url_fputs(fh, sprintf("O %s\n", modname));
334                         url_fputs(fh, sprintf("M %s\n", GetMapname()));
335                         url_fputs(fh, sprintf("I %s\n", matchid));
336                         url_fputs(fh, sprintf("S %s\n", cvar_string("hostname")));
337                         url_fputs(fh, sprintf("C %d\n", cvar_purechanges_count));
338                         url_fputs(fh, sprintf("U %d\n", cvar("port")));
339                         url_fputs(fh, sprintf("D %f\n", max(0, time - game_starttime)));
340                         url_fputs(fh, sprintf("L %s\n", autocvar_g_playerstats_gamereport_ladder));
341
342                         // TEAMS
343                         if(teamplay)
344                         {
345                                 for(t = PS_GR_OUT_TL; (tn = db_get(PS_GR_OUT_DB, sprintf("%d", stof(t)))) != ""; t = tn)
346                                 {
347                                         // start team section
348                                         url_fputs(fh, sprintf("Q team#%s\n", t));
349
350                                         // output team events // todo: does this do unnecessary loops? perhaps we should do a separate "team_events_last" tracker..."
351                                         for(e = PS_GR_OUT_EVL; (en = db_get(PS_GR_OUT_DB, sprintf("*:%s", e))) != ""; e = en)
352                                         {
353                                                 float v = stof(db_get(PS_GR_OUT_DB, sprintf("team#%d:%s", stof(t), e)));
354                                                 if(v != 0) { url_fputs(fh, sprintf("e %s %g\n", e, v)); }
355                                         }
356                                 }
357                         }
358
359                         // PLAYERS
360                         for(p = PS_GR_OUT_PL; (pn = db_get(PS_GR_OUT_DB, sprintf("%s:*", p))) != ""; p = pn)
361                         {
362                                 // start player section
363                                 url_fputs(fh, sprintf("P %s\n", p));
364
365                                 // playerid/index (entity number for this server)
366                                 nn = db_get(PS_GR_OUT_DB, sprintf("%s:_playerid", p));
367                                 if(nn != "") { url_fputs(fh, sprintf("i %s\n", nn)); }
368
369                                 // player name
370                                 nn = db_get(PS_GR_OUT_DB, sprintf("%s:_netname", p));
371                                 if(nn != "") { url_fputs(fh, sprintf("n %s\n", nn)); }
372
373                                 // team identification number
374                                 if(teamplay)
375                                 {
376                                         tt = db_get(PS_GR_OUT_DB, sprintf("%s:_team", p));
377                                         url_fputs(fh, sprintf("t %s\n", tt));
378                                 }
379
380                                 // elo ranking enabled
381                                 nn = db_get(PS_GR_OUT_DB, sprintf("%s:_ranked", p));
382                                 if(nn != "") { url_fputs(fh, sprintf("r %s\n", nn)); }
383
384                                 // output player events
385                                 for(e = PS_GR_OUT_EVL; (en = db_get(PS_GR_OUT_DB, sprintf("*:%s", e))) != ""; e = en)
386                                 {
387                                         float v = stof(db_get(PS_GR_OUT_DB, sprintf("%s:%s", p, e)));
388                                         if(v != 0) { url_fputs(fh, sprintf("e %s %g\n", e, v)); }
389                                 }
390                         }
391                         url_fputs(fh, "\n");
392                         url_fclose(fh);
393                         break;
394                 }
395
396                 // ======================================
397                 // -- INCOMING GAME REPORT INFORMATION --
398                 // ======================================
399                 /* SPECIFICATIONS:
400                  * stuff
401                  */
402                 case URL_READY_CANREAD:
403                 {
404                         // url_fclose is processing, we got a response for writing the data
405                         // this must come from HTTP
406                         LOG_TRACE("Got response from player stats server:");
407                         while((s = url_fgets(fh))) { LOG_TRACE("  ", s); }
408                         LOG_TRACE("End of response.");
409                         url_fclose(fh);
410                         break;
411                 }
412
413                 case URL_READY_CLOSED:
414                 {
415                         // url_fclose has finished
416                         LOG_TRACE("Player stats written");
417                         PlayerStats_GameReport_DelayMapVote = false;
418                         if(PS_GR_OUT_DB >= 0)
419                         {
420                                 db_close(PS_GR_OUT_DB);
421                                 PS_GR_OUT_DB = -1;
422                         }
423                         break;
424                 }
425
426                 case URL_READY_ERROR:
427                 default:
428                 {
429                         LOG_INFO("Player stats writing failed: ", ftos(status));
430                         PlayerStats_GameReport_DelayMapVote = false;
431                         if(PS_GR_OUT_DB >= 0)
432                         {
433                                 db_close(PS_GR_OUT_DB);
434                                 PS_GR_OUT_DB = -1;
435                         }
436                         break;
437                 }
438         }
439 }
440
441 void PlayerStats_PlayerBasic(entity joiningplayer, float newrequest)
442 {
443         GameRules_scoring_add(joiningplayer, ELO, -1);
444         // http://stats.xonotic.org/player/GgXRw6piDtFIbMArMuiAi8JG4tiin8VLjZgsKB60Uds=/elo.txt
445         if(autocvar_g_playerstats_playerbasic_uri != "")
446         {
447                 string uri = autocvar_g_playerstats_playerbasic_uri;
448                 if (joiningplayer.crypto_idfp == "") {
449                         GameRules_scoring_add(joiningplayer, ELO, -1);
450                 } else {
451                         // create the database if it doesn't already exist
452                         if(PS_B_IN_DB < 0)
453                                 PS_B_IN_DB = db_create();
454
455                         // now request the information
456                         uri = strcat(uri, "/player/", uri_escape(uri_escape(uri_escape(joiningplayer.crypto_idfp))), "/elo.txt");
457                         LOG_TRACE("Retrieving playerstats from URL: ", uri);
458                         url_single_fopen(
459                                 uri,
460                                 FILE_APPEND,
461                                 PlayerStats_PlayerBasic_Handler,
462                                 joiningplayer
463                         );
464
465                         // set status appropriately // todo: check whether the player info exists in the database previously
466                         if(newrequest)
467                         {
468                                 // database still contains useful information, so don't clear it of a useful status
469                                 joiningplayer.playerstats_basicstatus = PS_B_STATUS_WAITING;
470                         }
471                         else
472                         {
473                                 // database was previously empty or never hit received status for some reason
474                                 joiningplayer.playerstats_basicstatus = PS_B_STATUS_UPDATING;
475                         }
476                 }
477         }
478         else
479         {
480                 // server has this disabled, kill the DB and set status to idle
481                 GameRules_scoring_add(joiningplayer, ELO, -1);
482                 if(PS_B_IN_DB >= 0)
483                 {
484                         db_close(PS_B_IN_DB);
485                         PS_B_IN_DB = -1;
486
487                         FOREACH_CLIENT(IS_REAL_CLIENT(it), it.playerstats_basicstatus = PS_B_STATUS_IDLE);
488                 }
489         }
490 }
491
492 void PlayerStats_PlayerBasic_CheckUpdate(entity joiningplayer)
493 {
494         // determine whether we should retrieve playerbasic information again
495
496         LOG_TRACEF("PlayerStats_PlayerBasic_CheckUpdate('%s'): %f",
497                 joiningplayer.netname,
498                 time
499         );
500
501         // TODO: check to see if this playerid is inside the database already somehow...
502         // for now we'll just check the field, but this won't work for players who disconnect and reconnect properly
503         // although maybe we should just submit another request ANYWAY?
504         if(!joiningplayer.playerstats_basicstatus)
505         {
506                 PlayerStats_PlayerBasic(
507                         joiningplayer,
508                         (joiningplayer.playerstats_basicstatus == PS_B_STATUS_RECEIVED)
509                 );
510         }
511 }
512
513 void PlayerStats_PlayerBasic_Handler(entity fh, entity p, float status)
514 {
515         switch(status)
516         {
517                 case URL_READY_CANWRITE:
518                 {
519                         LOG_TRACE("-- Sending data to player stats server");
520                         /*url_fputs(fh, "V 1\n");
521                         #ifdef WATERMARK
522                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
523                         #endif
524                         url_fputs(fh, sprintf("l %s\n", cvar_string("_menu_prvm_language"))); // language
525                         url_fputs(fh, sprintf("c %s\n", cvar_string("_menu_prvm_country"))); // country
526                         url_fputs(fh, sprintf("g %s\n", cvar_string("_cl_gender"))); // gender
527                         url_fputs(fh, sprintf("n %s\n", cvar_string("_cl_name"))); // name
528                         url_fputs(fh, sprintf("m %s %s\n", cvar_string("_cl_playermodel"), cvar_string("_cl_playerskin"))); // model/skin
529                         */url_fputs(fh, "\n");
530                         url_fclose(fh);
531                         return;
532                 }
533
534                 case URL_READY_CANREAD:
535                 {
536                         bool handled = false;
537                         string gt = string_null;
538                         for (string s = ""; (s = url_fgets(fh)); ) {
539                                 int n = tokenizebyseparator(s, " "); // key value? data
540                                 if (n == 1) continue;
541                                 string key = "", value = "", data = "";
542                                 if (n == 2) {
543                     key = argv(0);
544                     data = argv(1);
545                                 } else if (n >= 3) {
546                     key = argv(0);
547                     value = argv(1);
548                     data = argv(2);
549                                 }
550                 switch (key) {
551                     case "V":
552                         // PlayerInfo_AddItem(p, "_version", data);
553                         break;
554                     case "R":
555                         // PlayerInfo_AddItem(p, "_release", data);
556                         break;
557                     case "T":
558                         // PlayerInfo_AddItem(p, "_time", data);
559                         break;
560                     case "S":
561                         // PlayerInfo_AddItem(p, "_statsurl", data);
562                         break;
563                     case "P":
564                         // PlayerInfo_AddItem(p, "_hashkey", data);
565                         break;
566                     case "n":
567                         // PlayerInfo_AddItem(p, "_playernick", data);
568                         break;
569                     case "i":
570                         // PlayerInfo_AddItem(p, "_playerid", data);
571                         // p.xonstat_id = stof(data);
572                         break;
573                     case "G":
574                         gt = data;
575                         break;
576                     case "e":
577                         LOG_TRACE("G: ", gt);
578                         LOG_TRACE("e: ", data);
579                         if (gt == PlayerStats_GetGametype()) {
580                             handled = true;
581                             float e = stof(data);
582                             GameRules_scoring_add(p, ELO, +1 + e);
583                         }
584                         if (gt == "") {
585                             // PlayerInfo_AddItem(p, value, data);
586                         } else {
587                             // PlayerInfo_AddItem(p, sprintf("%s/%s", gt, value), data);
588                         }
589                         break;
590                 }
591                         }
592                         url_fclose(fh);
593                         if (handled) return;
594                         break;
595                 }
596                 case URL_READY_CLOSED:
597                 {
598                         // url_fclose has finished
599                         LOG_INFO("Player stats synchronized with server");
600                         return;
601                 }
602
603                 case URL_READY_ERROR:
604                 default:
605                 {
606                         LOG_INFO("Receiving player stats failed: ", ftos(status));
607                         break;
608                 }
609         }
610         GameRules_scoring_add(p, ELO, -1);
611 }
612 #endif // SVQC
613
614 #ifdef MENUQC
615
616
617 #if 0 // reading the entire DB at once
618         string e = "", en = "";
619         float i = 0;
620         for(e = PS_D_IN_EVL; (en = db_get(PS_D_IN_DB, e)) != ""; e = en)
621         {
622                 LOG_INFOF("%d:%s:%s", i, e, db_get(PS_D_IN_DB, sprintf("#%s", e)));
623                 ++i;
624         }
625 #endif
626
627 void PlayerStats_PlayerDetail_AddItem(string event, string data)
628 {
629         if(PS_D_IN_DB < 0) { return; }
630
631         // create a marker for the event so that we can access it later
632         string marker = sprintf("%s", event);
633         if(db_get(PS_D_IN_DB, marker) == "")
634         {
635                 if(PS_D_IN_EVL)
636                 {
637                         db_put(PS_D_IN_DB, marker, PS_D_IN_EVL);
638                         strunzone(PS_D_IN_EVL);
639                 }
640                 else { db_put(PS_D_IN_DB, marker, "#"); }
641                 PS_D_IN_EVL = strzone(marker);
642         }
643
644         // now actually set the event data
645         db_put(PS_D_IN_DB, sprintf("#%s", event), data);
646         LOG_TRACE("Added item ", sprintf("#%s", event), "=", data, " to PS_D_IN_DB");
647 }
648
649 void PlayerStats_PlayerDetail()
650 {
651         // http://stats.xonotic.org/player/me
652         if((autocvar_g_playerstats_playerdetail_uri != "") && (crypto_getmyidstatus(0) > 0))
653         {
654                 // create the database if it doesn't already exist
655                 if(PS_D_IN_DB < 0)
656                         PS_D_IN_DB = db_create();
657
658                 //uri = strcat(uri, "/player/", uri_escape(crypto_getmyidfp(0)));
659                 LOG_TRACE("Retrieving playerstats from URL: ", autocvar_g_playerstats_playerdetail_uri);
660                 url_single_fopen(
661                         autocvar_g_playerstats_playerdetail_uri,
662                         FILE_APPEND,
663                         PlayerStats_PlayerDetail_Handler,
664                         NULL
665                 );
666
667                 PlayerStats_PlayerDetail_Status = PS_D_STATUS_WAITING;
668         }
669         else
670         {
671                 // player has this disabled, kill the DB and set status to idle
672                 if(PS_D_IN_DB >= 0)
673                 {
674                         db_close(PS_D_IN_DB);
675                         PS_D_IN_DB = -1;
676                 }
677
678                 PlayerStats_PlayerDetail_Status = PS_D_STATUS_IDLE;
679         }
680 }
681
682 void PlayerStats_PlayerDetail_CheckUpdate()
683 {
684         // determine whether we should retrieve playerdetail information again
685         float gamecount = cvar("cl_matchcount");
686
687         #if 0
688         LOG_INFOF("PlayerStats_PlayerDetail_CheckUpdate(): %f >= %f, %d > %d",
689                 time,
690                 PS_D_NEXTUPDATETIME,
691                 PS_D_LASTGAMECOUNT,
692                 gamecount
693         );
694         #endif
695
696         if(
697                 (time >= PS_D_NEXTUPDATETIME)
698                 ||
699                 (gamecount > PS_D_LASTGAMECOUNT)
700         )
701         {
702                 PlayerStats_PlayerDetail();
703                 PS_D_NEXTUPDATETIME = (time + autocvar_g_playerstats_playerdetail_autoupdatetime);
704                 PS_D_LASTGAMECOUNT = gamecount;
705         }
706 }
707
708 void PlayerStats_PlayerDetail_Handler(entity fh, entity unused, float status)
709 {
710         switch(status)
711         {
712                 case URL_READY_CANWRITE:
713                 {
714                         LOG_TRACE("PlayerStats_PlayerDetail_Handler(): Sending data to player stats server...");
715                         url_fputs(fh, "V 1\n");
716                         #ifdef WATERMARK
717                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
718                         #endif
719                         url_fputs(fh, sprintf("l %s\n", cvar_string("_menu_prvm_language"))); // language
720                         //url_fputs(fh, sprintf("c %s\n", cvar_string("_cl_country"))); // country
721                         //url_fputs(fh, sprintf("g %s\n", cvar_string("_cl_gender"))); // gender
722                         url_fputs(fh, sprintf("n %s\n", cvar_string("_cl_name"))); // name
723                         url_fputs(fh, sprintf("m %s %s\n", cvar_string("_cl_playermodel"), cvar_string("_cl_playerskin"))); // model/skin
724                         url_fputs(fh, "\n");
725                         url_fclose(fh);
726                         break;
727                 }
728
729                 case URL_READY_CANREAD:
730                 {
731                         //print("PlayerStats_PlayerDetail_Handler(): Got response from player stats server:\n");
732                         string input = "";
733                         string gametype = "overall";
734                         while((input = url_fgets(fh)))
735                         {
736                                 float count = tokenizebyseparator(input, " ");
737                                 string key = "", event = "", data = "";
738
739                                 if(argv(0) == "#") { continue; }
740
741                                 if(count == 2)
742                                 {
743                                         key = argv(0);
744                                         data = substring(input, argv_start_index(1), strlen(input) - argv_start_index(1));
745                                 }
746                                 else if(count >= 3)
747                                 {
748                                         key = argv(0);
749                                         event = argv(1);
750                                         data = substring(input, argv_start_index(2), strlen(input) - argv_start_index(2));
751                                 }
752                                 else { continue; }
753
754                                 switch(key)
755                                 {
756                                         // general info
757                                         case "V": PlayerStats_PlayerDetail_AddItem("version", data); break;
758                                         case "R": PlayerStats_PlayerDetail_AddItem("release", data); break;
759                                         case "T": PlayerStats_PlayerDetail_AddItem("time", data); break;
760
761                                         // player info
762                                         case "S": PlayerStats_PlayerDetail_AddItem("statsurl", data); break;
763                                         case "P": PlayerStats_PlayerDetail_AddItem("hashkey", data); break;
764                                         case "n": PlayerStats_PlayerDetail_AddItem("playernick", data); break;
765                                         case "i": PlayerStats_PlayerDetail_AddItem("playerid", data); break;
766
767                                         // other/event info
768                                         case "G": gametype = data; break;
769                                         case "e":
770                                         {
771                                                 if(event != "" && data != "")
772                                                 {
773                                                         PlayerStats_PlayerDetail_AddItem(
774                                                                 sprintf(
775                                                                         "%s/%s",
776                                                                         gametype,
777                                                                         event
778                                                                 ),
779                                                                 data
780                                                         );
781                                                 }
782                                                 break;
783                                         }
784
785                                         default:
786                                         {
787                                                 LOG_INFOF(
788                                                         "PlayerStats_PlayerDetail_Handler(): ERROR: "
789                                                         "Key went unhandled? Is our version outdated?\n"
790                                                         "PlayerStats_PlayerDetail_Handler(): "
791                                                         "Key '%s', Event '%s', Data '%s'",
792                                                         key,
793                                                         event,
794                                                         data
795                                                 );
796                                                 break;
797                                         }
798                                 }
799
800                                 #if 0
801                                 LOG_INFOF(
802                                         "PlayerStats_PlayerDetail_Handler(): "
803                                         "Key '%s', Event '%s', Data '%s'",
804                                         key,
805                                         event,
806                                         data
807                                 );
808                                 #endif
809                         }
810                         //print("PlayerStats_PlayerDetail_Handler(): End of response.\n");
811                         url_fclose(fh);
812                         PlayerStats_PlayerDetail_Status = PS_D_STATUS_RECEIVED;
813                         statslist.getStats(statslist);
814                         break;
815                 }
816
817                 case URL_READY_CLOSED:
818                 {
819                         // url_fclose has finished
820                         LOG_INFO("PlayerStats_PlayerDetail_Handler(): Player stats synchronized with server.");
821                         break;
822                 }
823
824                 case URL_READY_ERROR:
825                 default:
826                 {
827                         LOG_INFO("PlayerStats_PlayerDetail_Handler(): Receiving player stats failed: ", ftos(status));
828                         PlayerStats_PlayerDetail_Status = PS_D_STATUS_ERROR;
829                         if(PS_D_IN_DB >= 0)
830                         {
831                                 db_close(PS_D_IN_DB);
832                                 PS_D_IN_DB = -1;
833                         }
834                         break;
835                 }
836         }
837 }
838 #endif
839
840 /*
841 void PlayerInfo_AddPlayer(entity e)
842 {
843         if(playerinfo_db < 0)
844                 return;
845
846         string key;
847         key = sprintf("#%d:*", e.playerid); // TODO: use hashkey instead?
848
849         string p;
850         p = db_get(playerinfo_db, key);
851         if(p == "")
852         {
853                 if(playerinfo_last)
854                 {
855                         db_put(playerinfo_db, key, playerinfo_last);
856                         strunzone(playerinfo_last);
857                 }
858                 else
859                         db_put(playerinfo_db, key, "#");
860                 playerinfo_last = strzone(ftos(e.playerid));
861                 print("  Added player ", ftos(e.playerid), " to playerinfo_db\n");//DEBUG//
862         }
863 }
864
865 void PlayerInfo_AddItem(entity e, string item_id, string val)
866 {
867         if(playerinfo_db < 0)
868                 return;
869
870         string key;
871         key = sprintf("*:%s", item_id);
872
873         string p;
874         p = db_get(playerinfo_db, key);
875         if(p == "")
876         {
877                 if(playerinfo_events_last)
878                 {
879                         db_put(playerinfo_db, key, playerinfo_events_last);
880                         strunzone(playerinfo_events_last);
881                 }
882                 else
883                         db_put(playerinfo_db, key, "#");
884                 playerinfo_events_last = strzone(item_id);
885         }
886
887         key = sprintf("#%d:%s", e.playerid, item_id);
888         db_put(playerinfo_db, key, val);
889         print("  Added item ", key, "=", val, " to playerinfo_db\n");//DEBUG//
890 }
891
892 string PlayerInfo_GetItem(entity e, string item_id)
893 {
894         if(playerinfo_db < 0)
895                 return "";
896
897         string key;
898         key = sprintf("#%d:%s",  e.playerid, item_id);
899         return db_get(playerinfo_db, key);
900 }
901
902 string PlayerInfo_GetItemLocal(string item_id)
903 {
904         entity p = spawn();
905         p.playerid = 0;
906         return PlayerInfo_GetItem(p, item_id);
907 }
908
909 void PlayerInfo_ready(entity fh, entity p, float status)
910 {
911         float n;
912         string s;
913
914         PlayerInfo_AddPlayer(p);
915
916         switch(status)
917         {
918                 case URL_READY_CANWRITE:
919                         print("-- Sending data to player stats server\n");
920                         url_fputs(fh, "V 1\n");
921 #ifdef WATERMARK
922                         url_fputs(fh, sprintf("R %s\n", WATERMARK));
923 #endif
924 #ifdef MENUQC
925                         url_fputs(fh, sprintf("l %s\n", cvar_string("_menu_prvm_language"))); // language
926                         url_fputs(fh, sprintf("c %s\n", cvar_string("_menu_prvm_country"))); // country
927                         url_fputs(fh, sprintf("g %s\n", cvar_string("_cl_gender"))); // gender
928                         url_fputs(fh, sprintf("n %s\n", cvar_string("_cl_name"))); // name
929                         url_fputs(fh, sprintf("m %s %s\n", cvar_string("_cl_playermodel"), cvar_string("_cl_playerskin"))); // model/skin
930 #endif
931                         url_fputs(fh, "\n");
932                         url_fclose(fh);
933                         break;
934                 case URL_READY_CANREAD:
935                         print("-- Got response from player stats server:\n");
936                         string gametype = string_null;
937                         while((s = url_fgets(fh)))
938                         {
939                                 print("  ", s, "\n");
940
941                                 string key = "", value = "", data = "";
942
943                                 n = tokenizebyseparator(s, " "); // key (value) data
944                                 if (n == 1)
945                                         continue;
946                                 else if (n == 2)
947                                 {
948                                         key = argv(0);
949                                         data = argv(1);
950                                 }
951                                 else if (n >= 3)
952                                 {
953                                         key = argv(0);
954                                         value = argv(1);
955                                         data = argv(2);
956                                 }
957
958                                 if (data == "")
959                                         continue;
960
961                                 if (key == "#")
962                                         continue;
963                                 else if (key == "V")
964                                         PlayerInfo_AddItem(p, "_version", data);
965                                 else if (key == "R")
966                                         PlayerInfo_AddItem(p, "_release", data);
967                                 else if (key == "T")
968                                         PlayerInfo_AddItem(p, "_time", data);
969                                 else if (key == "S")
970                                         PlayerInfo_AddItem(p, "_statsurl", data);
971                                 else if (key == "P")
972                                         PlayerInfo_AddItem(p, "_hashkey", data);
973                                 else if (key == "n")
974                                         PlayerInfo_AddItem(p, "_playernick", data);
975                                 else if (key == "i")
976                                         PlayerInfo_AddItem(p, "_playerid", data);
977                                 else if (key == "G")
978                                         gametype = data;
979                                 else if (key == "e" && value != "")
980                                 {
981                                         if (gametype == "")
982                                                 PlayerInfo_AddItem(p, value, data);
983                                         else
984                                                 PlayerInfo_AddItem(p, sprintf("%s/%s", gametype, value), data);
985                                 }
986                                 else
987                                         continue;
988                         }
989                         print("-- End of response.\n");
990                         url_fclose(fh);
991                         break;
992                 case URL_READY_CLOSED:
993                         // url_fclose has finished
994                         print("Player stats synchronized with server\n");
995                         break;
996                 case URL_READY_ERROR:
997                 default:
998                         print("Receiving player stats failed: ", ftos(status), "\n");
999                         break;
1000         }
1001 }
1002
1003 void PlayerInfo_Init()
1004 {
1005         playerinfo_db = db_create();
1006 }
1007
1008 #ifdef SVQC
1009 void PlayerInfo_Basic(entity p)
1010 {
1011         print("-- Getting basic PlayerInfo for player ",ftos(p.playerid)," (SVQC)\n");
1012
1013         if(playerinfo_db < 0)
1014                 return;
1015
1016         string uri;
1017         uri = autocvar_g_playerinfo_uri;
1018         if(uri != "" && p.crypto_idfp != "")
1019         {
1020                 uri = strcat(uri, "/elo/", uri_escape(p.crypto_idfp));
1021                 print("Retrieving playerstats from URL: ", uri, "\n");
1022                 url_single_fopen(uri, FILE_READ, PlayerInfo_ready, p);
1023         }
1024 }
1025 #endif
1026
1027 #ifdef MENUQC
1028 void PlayerInfo_Details()
1029 {
1030         print("-- Getting detailed PlayerInfo for local player (MENUQC)\n");
1031
1032         if(playerinfo_db < 0)
1033                 return;
1034
1035         string uri;
1036         uri = autocvar_g_playerinfo_uri; // FIXME
1037         if(uri != "" && crypto_getmyidstatus(0) > 0)
1038         {
1039                 //uri = strcat(uri, "/player/", uri_escape(crypto_getmyidfp(0)));
1040                 uri = strcat(uri, "/player/me");
1041                 print("Retrieving playerstats from URL: ", uri, "\n");
1042                 url_single_fopen(uri, FILE_APPEND, PlayerInfo_ready, NULL);
1043         }
1044 }
1045 #endif
1046
1047 #ifdef CSQC
1048 // FIXME - crypto_* builtin functions missing in CSQC (csprogsdefs.qh:885)
1049 void PlayerInfo_Details()
1050 {
1051         print("-- Getting detailed PlayerInfo for local player (CSQC)\n");
1052
1053         if(playerinfo_db < 0)
1054                 return;
1055
1056         string uri;
1057         uri = autocvar_g_playerinfo_uri; // FIXME
1058         if(uri != "" && crypto_getmyidstatus(0) > 0)
1059         {
1060                 uri = strcat(uri, "/player/", uri_escape(crypto_getmyidfp(0)));
1061                 print("Retrieving playerstats from URL: ", uri, "\n");
1062                 url_single_fopen(uri, FILE_READ, PlayerInfo_ready, p);
1063         }
1064 }
1065
1066 #endif
1067 */