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