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