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