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