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