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