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