add points archiver, manages the upper limit of time in placing to produce exactly...
[brisk.git] / web / briskin5 / statadm.php
1 <?php
2 /*
3  *  brisk - statadm.php
4  *
5  *  Copyright (C) 2009-2011 Matteo Nastasi
6  *                          mailto: nastasi@alternativeoutput.it 
7  *                                  matteo.nastasi@milug.org
8  *                          web: http://www.alternativeoutput.it
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABLILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details. You should have received a
19  * copy of the GNU General Public License along with this program; if
20  * not, write to the Free Software Foundation, Inc, 59 Temple Place -
21  * Suite 330, Boston, MA 02111-1307, USA.
22  *
23  */
24
25 /*
26   line example:
27 1246428948|492e4e9e856b0|N|tre|172.22.1.90|STAT:BRISKIN5:FINISH_GAME|4a4afd4983039|6|3|tre|1|due|2|uno|-1|
28    
29 */
30
31 $G_base = "../";
32
33 ini_set("max_execution_time",  "240");
34
35 require_once("../Obj/brisk.phh");
36 require_once("../Obj/auth.phh");
37 require_once("../Obj/dbase_${G_dbasetype}.phh");
38 require_once("Obj/briskin5.phh");
39 require_once("Obj/placing.phh");
40
41 function main_file($curtime)
42 {
43   GLOBAL $G_alarm_passwd;
44   $tri = array();
45   $mon = array();
46   $wee = array();
47   
48   if (($fp = @fopen(LEGAL_PATH."/points.log", 'r')) == FALSE) {
49     echo "Open data file error";
50     exit;
51   }
52   echo "prima<br>";
53  
54   if (($fp_start = @fopen(LEGAL_PATH."/points.start", 'r')) != FALSE) {
55     $skip = intval(fgets($fp_start));
56     if ($skip > 0)
57       fseek($fp, $skip, SEEK_SET);
58     fclose($fp_start);
59   }
60
61   $bdb = new BriskDB();
62   $bdb->users_load();
63
64   for ($i = 0 ; $i < $bdb->count() ; $i++) {
65     $login = $bdb->getlogin_byidx($i);
66     $tri[$i] = new Ptsgam($login);
67     $mon[$i] = new Ptsgam($login);
68     $wee[$i] = new Ptsgam($login);
69   }
70
71   // recalculate all the placings
72   // 1246428948|492e4e9e856b0|N|tre|172.22.1.90|STAT:BRISKIN5:FINISH_GAME|4a4afd4983039|6|3|tre|1|due|2|uno|-1|
73   while (!feof($fp)) {
74     $p = 0;
75     $bf = fgets($fp, 4096);
76     $ar = csplitter($bf, '|');
77     // if not auth table, continue
78     if (count($ar) < 15)
79       continue;
80     
81     // echo $p++."<br>";
82     if ($ar[7] >= TABLES_AUTH_N)
83       continue;
84     // echo $p++." ".$ar[5]."<br>";
85     // if not FINISH_GAME line, continue
86     if ($ar[5] != "STAT:BRISKIN5:FINISH_GAME")
87       continue;
88     // echo $p++."<br>";
89     // if to much old points, continue
90     if ($ar[0] < $curtime - TRI_LIMIT) {
91       if (($fp_start = @fopen(LEGAL_PATH."/points.start", 'w')) != FALSE) {
92         $curpos = ftell($fp);
93         fwrite($fp_start, sprintf("%d\n", $curpos));
94         fclose($fp_start);
95       }
96       
97       continue;
98     }
99     // echo $p++." ".BRISKIN5_PLAYERS_N."<br>";
100     
101     $found = FALSE;
102     $mult = 1;
103     for ($i = 0 ; $i < BRISKIN5_PLAYERS_N ; $i++) {
104       for ($e = $i + 1 ; $e < BRISKIN5_PLAYERS_N ; $e++) {
105         if ($ar[10+($i*2)] == $ar[10+($e*2)]) {
106           $mult = abs($ar[10+($i*2)]);
107           $found = TRUE;
108         }
109       }
110       if ($found)
111         break;
112     }
113
114     if ($mult == 0)
115        continue;
116     for ($i = 0 ; $i < BRISKIN5_PLAYERS_N ; $i++) {
117       // echo $p." i) ".$i."<br>";
118       $username = $ar[9+($i*2)];
119       if (($item = $bdb->getitem_bylogin($username, &$id)) == FALSE) {
120         echo "WARNING: the user [".$username."] NOT EXISTS!<br>";
121         continue;
122       }
123       
124       // echo $item->login." id)".$id."  ".$ar[10+($i*2)]." mult: ".$mult."<br>";
125       $tri[$id]->add($ar[10+($i*2)] / $mult);
126       if ($ar[0] >= $curtime - MON_LIMIT) 
127         $mon[$id]->add($ar[10+($i*2)] / $mult);
128       if ($ar[0] >= $curtime - WEE_LIMIT) 
129         $wee[$id]->add($ar[10+($i*2)] / $mult);
130     }
131     // $p++; echo $p++."<br>";
132   }
133   fclose($fp);
134   
135   usort($tri, ptsgam_cmp);
136   usort($mon, ptsgam_cmp);
137   usort($wee, ptsgam_cmp);
138   
139   echo "<br><br>TRI<br>\n";
140
141   if (($fplo = @fopen(LEGAL_PATH."/class_tri_lo.log", 'w')) == FALSE) {
142     echo "Open tri_lo failed<br>";
143     exit;
144   }
145   if (($fphi = @fopen(LEGAL_PATH."/class_tri_hi.log", 'w')) == FALSE) {
146     echo "Open tri_hi failed<br>";
147     exit;
148   }
149
150   for ($i = 0 ; $i < count($tri) ; $i++) {
151     if ($tri[$i]->gam == 0.0)
152       continue;
153     printf("%s: %s (%d) <br>\n",  $tri[$i]->username,  $tri[$i]->snormpts(), $tri[$i]->gam);
154     if ($tri[$i]->gam >= TRI_MAX_GAMES) 
155       fwrite($fphi, sprintf("%s|%d|%d|\n", xcapelt($tri[$i]->username), $tri[$i]->pts, $tri[$i]->gam));
156     else if ($tri[$i]->gam > TRI_MIN_GAMES) 
157       fwrite($fplo, sprintf("%s|%d|%d|\n", xcapelt($tri[$i]->username), $tri[$i]->pts, $tri[$i]->gam));
158   }
159   fclose($fphi);
160   fclose($fplo);
161
162   echo "<br><br>MON<br>\n";
163
164   if (($fplo = @fopen(LEGAL_PATH."/class_mon_lo.log", 'w')) == FALSE) {
165     echo "Open tri_lo failed<br>";
166     exit;
167   }
168   if (($fphi = @fopen(LEGAL_PATH."/class_mon_hi.log", 'w')) == FALSE) {
169     echo "Open tri_hi failed<br>";
170     exit;
171   }
172
173   for ($i = 0 ; $i < count($mon) ; $i++) {
174     if ($mon[$i]->gam == 0.0)
175       continue;
176     printf("%s: %s (%d) <br>\n",  $mon[$i]->username,  $mon[$i]->snormpts(), $mon[$i]->gam);
177     if ($mon[$i]->gam >= MON_MAX_GAMES) 
178       fwrite($fphi, sprintf("%s|%d|%d|\n", xcapelt($mon[$i]->username), $mon[$i]->pts, $mon[$i]->gam));
179     else if ($mon[$i]->gam > MON_MIN_GAMES) 
180       fwrite($fplo, sprintf("%s|%d|%d|\n", xcapelt($mon[$i]->username), $mon[$i]->pts, $mon[$i]->gam));
181   }
182   fclose($fphi);
183   fclose($fplo);
184
185   echo "<br><br>WEE<br>\n";
186   if (($fplo = @fopen(LEGAL_PATH."/class_wee_lo.log", 'w')) == FALSE) {
187     echo "Open wee_lo failed<br>";
188     exit;
189   }
190   if (($fphi = @fopen(LEGAL_PATH."/class_wee_hi.log", 'w')) == FALSE) {
191     echo "Open wee_hi failed<br>";
192     exit;
193   }
194
195   for ($i = 0 ; $i < count($wee) ; $i++) {
196     if ($wee[$i]->gam == 0.0) 
197       continue;
198     printf("%s: %s (%d) <br>\n",  $wee[$i]->username,  $wee[$i]->snormpts(), $wee[$i]->gam);
199     if ($wee[$i]->gam >= WEE_MAX_GAMES) 
200       fwrite($fphi, sprintf("%s|%d|%d|\n", xcapelt($wee[$i]->username), $wee[$i]->pts, $wee[$i]->gam));
201     else if ($wee[$i]->gam > WEE_MIN_GAMES) 
202       fwrite($fplo, sprintf("%s|%d|%d|\n", xcapelt($wee[$i]->username), $wee[$i]->pts, $wee[$i]->gam));
203   }
204   fclose($fphi);
205   fclose($fplo);
206
207 }
208
209 function main_pgsql($curtime)
210 {
211     GLOBAL $G_dbpfx;
212
213     $bdb = new BriskDB();
214
215     $limi = array( TRI_LIMIT, MON_LIMIT, WEE_LIMIT );
216     $ming = array( TRI_MIN_GAMES, MON_MIN_GAMES, WEE_MIN_GAMES );
217     $maxg = array( TRI_MAX_GAMES, MON_MAX_GAMES, WEE_MAX_GAMES );
218
219     do {
220         if (pg_query($bdb->dbconn->db(), "BEGIN") == FALSE) {
221             log_crit("statadm: begin failed");
222             break;
223         }
224         
225         $mtc_sql = sprintf("CREATE TEMPORARY TABLE %sbin5_temp_matches ON COMMIT DROP AS SELECT m.code, max(g.tstamp) AS tstamp 
226                             FROM %sbin5_matches as m, %sbin5_games as g 
227                             WHERE g.mcode = m.code GROUP BY m.code, m.ttok",
228                            $G_dbpfx, $G_dbpfx, $G_dbpfx);
229         // error_log($mtc_sql, 0);
230         if (pg_query($bdb->dbconn->db(), $mtc_sql) == FALSE) {
231             log_crit("statadm: temporary matches table creation [$mtc_sql] failed");
232             break;
233         }
234         
235         $tmt_sql = sprintf("SELECT * FROM %sbin5_temp_matches WHERE  tstamp < to_timestamp(%d)",
236                            $G_dbpfx, $curtime - TRI_LIMIT);
237         // error_log($tmt_sql, 0);
238
239         // if deletable old matches exists then ...
240         if (($tmt_pg = pg_query($bdb->dbconn->db(), $tmt_sql)) != FALSE) {
241             //
242             // store matches before clean them
243             //
244             $fname = sprintf("%s/pts_archive%s.log", LEGAL_PATH, date("Ymd", $curtime));
245             if (($fp = @fopen($fname, 'a')) == FALSE) {
246                 log_crit("statadm: log file [$fname] open failed");
247                 break;
248             }
249             
250             $tmt_n = pg_numrows($tmt_pg);
251             // get matches
252             for ($m = 0 ; $m < $tmt_n ; $m++) {
253                 $tmt_obj = pg_fetch_object($tmt_pg, $m);
254                 
255                 $mtc_sql = sprintf("SELECT * from %sbin5_matches WHERE code = %d",
256                                    $G_dbpfx, $tmt_obj->code);
257                 
258                 error_log($mtc_sql, 0);
259                 if (($mtc_pg  = pg_query($bdb->dbconn->db(), $mtc_sql)) == FALSE || pg_numrows($mtc_pg) != 1) {
260                     log_crit("statadm: matches row select failed");
261                     break;
262                 }
263                 $mtc_obj = pg_fetch_object($mtc_pg, 0);
264                 
265                 if (fwrite($fp, sprintf("M|%d|%s|%d|\n", $mtc_obj->code, xcapelt($mtc_obj->ttok), $mtc_obj->tidx)) == FALSE) {
266                     log_crit("statadm: log file [$fname] write match failed");
267                     break;
268                 }
269                 
270                 // get games associated to each match
271                 $gam_sql = sprintf("SELECT code, mcode, EXTRACT(epoch FROM tstamp) AS tstamp FROM %sbin5_games 
272                                     WHERE mcode = %d ORDER BY tstamp",
273                                    $G_dbpfx, $mtc_obj->code);
274                 if (($gam_pg  = pg_query($bdb->dbconn->db(), $gam_sql)) == FALSE) {
275                     log_crit("statadm: games row select failed");
276                     break;
277                 }
278                 
279                 $gam_n = pg_numrows($gam_pg);
280                 for ($g = 0 ; $g < $gam_n ; $g++) {
281                     $gam_obj = pg_fetch_object($gam_pg, $g);
282                     
283                     if (fwrite($fp, sprintf("G|%d|%d|%d|\n", $gam_obj->mcode, $gam_obj->code, $gam_obj->tstamp)) == FALSE) {
284                         log_crit("statadm: log file [$fname] write game failed");
285                         break;
286                     }
287                     $pts_sql = sprintf("SELECT * FROM %sbin5_points WHERE gcode = %d", $G_dbpfx, $gam_obj->code);
288                     if (($pts_pg  = pg_query($bdb->dbconn->db(), $pts_sql)) == FALSE) {
289                         log_crit("statadm: points row select [$pts_sql] failed");
290                         break;
291                     }
292                     $pts_n = pg_numrows($pts_pg);
293                     for ($p = 0 ; $p < $pts_n ; $p++) {
294                         $pts_obj = pg_fetch_object($pts_pg, $p);
295                         
296                         if (fwrite($fp, sprintf("P|%d|%d|%d|\n", $pts_obj->gcode, $pts_obj->ucode, $pts_obj->pts)) == FALSE) {
297                             log_crit("statadm: log file [$fname] write pts failed");
298                             break;
299                         }
300                     }
301                     if ($p < $pts_n)
302                         break;
303                 }
304                 if ($g < $gam_n)
305                     break;
306                 
307                 // delete match and all it's childs (games and points)
308                 $del_sql = sprintf("DELETE FROM %sbin5_matches WHERE code = %d",
309                                    $G_dbpfx, $tmt_obj->code);
310                 if (($del_pg = pg_query($bdb->dbconn->db(),$del_sql)) == FALSE || pg_affected_rows($del_pg) != 1) {
311                     log_crit("statadm: matches row deletion failed");
312                     break;
313                 }
314                 
315             }
316             if ($m < $tmt_n)
317                 break;
318         } // if (($tmt_pg = pg_query($bdb->dbco...
319
320         // GEN: Truncate table (postgresql extension, in other SQL you must user unqualified DELETE
321         $tru_sql = sprintf("TRUNCATE %sbin5_places;", $G_dbpfx);
322         if (pg_query($bdb->dbconn->db(), $tru_sql) == FALSE) {
323             log_crit("statadm: truncate failed");
324             break;
325         }
326         
327         for ($dtime = 0 ; $dtime < count($limi) ; $dtime++) {
328             $old_score = array( 1000000000, 1000000000);
329             $old_gam   = array( -1, -1);
330             $rank      = array(  0,  0);
331             
332             $pla_sql = sprintf("SELECT (float4(sum(p.pts)) * 100.0 ) /  float4(count(p.pts)) as score, sum(p.pts) as points, count(p.pts) as games, u.code as ucode, u.login as login
333                                 FROM %sbin5_points as p, %sbin5_games as g, %sbin5_matches as m, %susers as u 
334                                 WHERE p.ucode = u.code AND p.gcode = g.code AND g.mcode = m.code AND 
335                                       g.tstamp > to_timestamp(%d) AND g.tstamp <= to_timestamp(%d)
336                                 GROUP BY u.code, u.login
337                                 ORDER BY (float4(sum(p.pts)) * 100.0 ) /  float4(count(p.pts)) DESC, 
338                                          count(p.pts) DESC",
339                                $G_dbpfx, $G_dbpfx, $G_dbpfx, $G_dbpfx, $curtime - $limi[$dtime], $curtime);
340
341             // log_crit("statadm: INFO: [$pla_sql]");
342
343             if (($pla_pg  = pg_query($bdb->dbconn->db(), $pla_sql)) == FALSE) {
344                 // no point found, abort
345                 log_crit("statadm: main placement select failed [$pla_sql]");
346                 break;
347             }
348             
349             for ($i = 0 ; $i < pg_numrows($pla_pg) ; $i++) {
350                 $pla_obj = pg_fetch_object($pla_pg,$i);
351                 if ($pla_obj->games < $ming[$dtime])
352                     continue;
353
354                 if ($pla_obj->games < $maxg[$dtime])
355                     $subty = 0;
356                 else
357                     $subty = 1;
358                 
359                 $ty = ($dtime * 2) + $subty;
360                 
361                 if ($pla_obj->games != $old_gam[$subty] || $pla_obj->score != $old_score[$subty]) {
362                     $rank[$subty]++;
363                 }
364                 $new_sql = sprintf("INSERT INTO %sbin5_places (type, rank, ucode, login, pts, games, score)
365                                     VALUES (%d, %d, %d, '%s', %d, %d, %f);",
366                                    $G_dbpfx, $ty, $rank[$subty], $pla_obj->ucode, escsql($pla_obj->login), 
367                                    $pla_obj->points, $pla_obj->games, $pla_obj->score);
368                 if ( ! (($new_pg  = pg_query($bdb->dbconn->db(), $new_sql)) != FALSE && 
369                         pg_affected_rows($new_pg) == 1) ) {
370                     log_crit("statadm: new place insert failed: ".print_r($pla_obj, TRUE));
371                     break;                        
372                 }
373                 
374                 $old_gam[$subty]   = $pla_obj->games;
375                 $old_score[$subty] = $pla_obj->score;
376             } // for ($i = 0 ; $i < pg_numrows($pla_pg) ; $i++) {
377             if ($i < pg_numrows($pla_pg)) {
378                 break;
379             }
380         } // for ($dtime = 0 ; $dtime < count($limi) ; $dtime++) {
381         if ($dtime < count($limi)) {
382             break;
383         }
384
385         $mti_sql = sprintf("UPDATE %sbin5_places_mtime SET mtime = (to_timestamp(%d)) WHERE code = 0;",
386                            $G_dbpfx, $curtime);
387         if ( ! (($mti_pg  = pg_query($bdb->dbconn->db(), $mti_sql)) != FALSE && 
388                 pg_affected_rows($mti_pg) == 1) ) {
389             log_crit("statadm: new mtime insert failed.");
390             break;                        
391         }
392         
393         if (pg_query($bdb->dbconn->db(), "COMMIT") == FALSE) {
394             break;
395         }
396         return (TRUE);
397     } while (0);
398
399     pg_query($bdb->dbconn->db(), "ROLLBACK");
400
401     return (FALSE);
402 }
403
404 function main()
405 {
406     GLOBAL $G_dbasetype, $G_alarm_passwd, $pazz;
407     
408     echo "Inizio.<br>";
409     flush();
410     if ($pazz != $G_alarm_passwd) {
411         echo "Wrong password<br>";
412         flush();
413         exit;
414     }
415     
416     $fun_name = "main_${G_dbasetype}";
417     
418     $ctime = time();
419
420     $curtime = ((int)($ctime / (24 * 3600))) * 24 * 3600 - (((int)substr(date("O", $ctime), 0, -2)) * 3600);
421     if ($ret = $fun_name($curtime))
422         echo "Success.<br>\n";
423     else
424         echo "Failed.<br>\n";
425     
426     echo "Fine.\n";
427     flush();
428 }
429
430 main();
431 ?>