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