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