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