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