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