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