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