computation and store of points and match state fixed
[brisk.git] / web / Obj / dbase_pgsql.phh
1 <?php
2   /*
3    *  brisk - dbase_pgsql.phh
4    *
5    *  Copyright (C) 2006-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 require_once("${G_base}Obj/dbase_base.phh");
26
27 $escsql_from = array( "\\",   "'"   );
28 $escsql_to   = array( "\\\\", "\\'" );
29
30 function escsql($s)
31 {
32     GLOBAL $escsql_from, $escsql_to;
33
34     return str_replace($escsql_from, $escsql_to, $s);
35 }
36
37 class DBConn
38 {
39     static $dbcnnx = FALSE;
40     var $db = FALSE;
41
42     function DBConn()
43     {
44         $this->db = DBConn::$dbcnnx;
45     }
46
47     static function create()
48     {
49         GLOBAL $G_dbauth;
50
51         if (DBConn::$dbcnnx == FALSE) {
52             if (!(DBConn::$dbcnnx = @pg_connect ($G_dbauth, PGSQL_CONNECT_FORCE_NEW))) {
53                 return (FALSE);
54             }
55         }
56
57         $out = new DBConn();
58
59         return $out;
60     }
61
62     static function destroy()
63     {
64         if (DBConn::$dbcnnx != FALSE) {
65             DBConn::$dbcnnx = FALSE;
66             return (pg_close(DBConn::$dbcnnx));
67         }
68         return TRUE;
69     }
70
71     static function recover()
72     {
73         self::destroy();
74         return (self::create());
75     }
76
77     function db()
78     {
79         return ($this->db);
80     }
81 }
82
83 class BriskDB
84 {
85     var $dbconn;
86     var $item;
87     var $item_n;
88
89     function BriskDB($dbconn)
90     {
91         $this->dbconn = $dbconn;
92     }
93
94     static function create()
95     {
96         GLOBAL $DOCUMENT_ROOT, $G_dbpfx;
97
98         $ret = FALSE;
99
100         log_main("BriskDB create:start");
101
102         do {
103             if (($dbconn = DBConn::create()) == FALSE) {
104                 break;
105             }
106
107             $ret = new BriskDB($dbconn);
108         } while (0);
109
110         return ($ret);
111     }
112
113     function query($sql)
114     {
115         if (($res = pg_query($this->dbconn->db(), $sql)) == FALSE) {
116             // try to recover the connection
117             if (($this->dbconn = DBConn::recover()) == FALSE)
118                 return FALSE;
119             return (pg_query($this->dbconn->db(), $sql));
120         }
121
122         return ($res);
123     }
124
125     function users_load()
126     {
127     }
128
129     function login_exists($login)
130     {
131         GLOBAL $G_dbpfx;
132
133         /* check the existence of the nick in the BriskDB */
134         log_main("login_exists: ".$login);
135
136         $user_sql = sprintf("SELECT * FROM %susers WHERE login = lower('%s') AND (type & CAST (X'%08x' as integer)) = 0;",
137                             $G_dbpfx, escsql($login), USER_FLAG_TY_DISABLE);
138         if (($user_pg = $this->query($user_sql)) != FALSE)
139             if (pg_numrows($user_pg) == 1)
140                 return TRUE;
141
142         return FALSE;
143     }
144
145     function getrecord_bylogin($login) {
146         GLOBAL $G_dbpfx;
147
148         $user_sql = sprintf("SELECT * FROM %susers WHERE login = lower('%s') AND (type & CAST (X'%08x' as integer)) = 0;",  $G_dbpfx, escsql($login), USER_FLAG_TY_DISABLE);
149         if (($user_pg  = $this->query($user_sql)) == FALSE) {
150             return FALSE;
151         }
152         if (pg_numrows($user_pg) != 1)
153             return FALSE;
154
155         $user_obj = pg_fetch_object($user_pg, 0);
156
157         return ($user_obj);
158     }
159
160     function user_update_login_time($code, $lintm)
161     {
162         GLOBAL $G_dbpfx;
163
164         $user_sql = sprintf("UPDATE %susers SET (lintm) = (date 'epoch' + %d * INTERVAL '1 second') WHERE code = %d;", $G_dbpfx, $lintm, $code);
165
166         // $user_pg = $this->query($user_sql);
167         // $row_n = pg_affected_rows($user_pg);
168         // fprintf(STDERR, "query: %s   NUM: %d\n", ($user_pg == FALSE ? "FALSE" : "TRUE"), $row_n);
169         if ( ! (($user_pg  = $this->query($user_sql)) != FALSE && pg_affected_rows($user_pg) == 1) ) {
170              return FALSE;
171         }
172
173         return TRUE;
174     }
175
176     function user_prefs_update($code, $flags, $supp_comp)
177     {
178         GLOBAL $G_dbpfx;
179
180         $user_sql = sprintf("UPDATE %susers SET (type, supp_comp) = (%d, '%s') WHERE code = %d;",
181                             $G_dbpfx, $flags, $supp_comp, $code);
182         fprintf(STDERR, "REQUEST [%s]\n", $user_sql);
183         if ( ! (($user_pg  = $this->query($user_sql)) != FALSE && pg_affected_rows($user_pg) == 1) ) {
184              return FALSE;
185         }
186         fprintf(STDERR, "REQUEST GOOD [%s]\n", $user_sql);
187
188         return TRUE;
189     }
190
191     /*
192       if success return a LoginDBItem object
193      */
194     function login_verify($login, $pass)
195     {
196         GLOBAL $G_dbpfx;
197
198         $ret = FALSE;
199
200         log_main("login_verify: ".$login);
201
202         //O /* check the existence of the nick in the BriskDB */
203         //O for ($i = 0 ; $i < $this->item_n ; $i++) {
204         //O log_main("login_verify: BEGIN");
205
206         if (($user_obj = $this->getrecord_bylogin($login)) == FALSE) {
207             return FALSE;
208         }
209
210         log_main("login[".$user_obj->code."]: ".$user_obj->login);
211
212         /* if it exists check for a valid challenge */
213         if (($a_sem = Challenges::lock_data(TRUE)) != FALSE) {
214             if (($chals = &Challenges::load_data()) != FALSE) {
215                 for ($e = 0 ; $e < $chals->item_n ; $e++) {
216                     log_main("challenge[".$e."]: ".$chals->item[$e]->login);
217                     if (strcmp($login, $chals->item[$e]->login) == 0) {
218                         log_main("login_verify [".$pass."] with [".md5($chals->item[$e]->token.$user_obj->pass)."]");
219
220                         if (strcmp($pass, md5($chals->item[$e]->token.$user_obj->pass)) == 0) {
221                             log_main("login_verify SUCCESS for ".$login);
222
223                             $chals->rem($login);
224                             $this->user_update_login_time($user_obj->code, time());
225                             $ret = LoginDBItem::LoginDBItemFromRecord($user_obj);
226                             break;
227                         }
228                     }
229                 } // end for ($e = 0 ...
230             }
231
232             if ($chals->ismod()) {
233                 Challenges::save_data(&$chals);
234             }
235
236             Challenges::unlock_data($a_sem);
237         }
238         //O break;
239         // O } //  if (strcasecmp($this->item[$i]->login, ...
240         //O }
241
242         return ($ret);
243     }
244
245     function getitem_bylogin($login, &$id) {
246         $ret = FALSE;
247         $id = -1;
248
249         log_main("getitem_bylogin: ".$login);
250
251         if (($user_obj = $this->getrecord_bylogin($login)) == FALSE)
252             return $ret;
253
254         $id = $user_obj->code;
255         return (LoginDBItem::LoginDBItemFromRecord($user_obj));
256     }
257
258     // TODO FOR DB
259     function getmail($login)
260     {
261         log_main("getmail");
262
263         if (($ret = $this->getrecord_bylogin($login)) == FALSE)
264             return FALSE;
265
266         return ($ret->email);
267     }
268
269     function addusers_from_olddb($olddb, &$cont)
270     {
271         GLOBAL $G_dbpfx;
272
273         for ($i = 0 ; $i < $olddb->count() ; $i++) {
274             $user_sql = sprintf("INSERT INTO %susers ( login, pass, email, type) VALUES ('%s', '%s', '%s', %d);",
275                                 $G_dbpfx, escsql(strtolower($olddb->item[$i]->login)), escsql($olddb->item[$i]->pass),
276                                 escsql($olddb->item[$i]->email), $olddb->item[$i]->type & USER_FLAG_TY_ALL);
277
278             if ( ! (($user_pg  = $this->query($user_sql)) != FALSE && pg_affected_rows($user_pg) == 1) ) {
279                 $cont .= sprintf("ERROR IN LINE: %s\n", eschtml($user_sql));
280
281                 return FALSE;
282             }
283         }
284         return TRUE;
285     }
286
287     function getdbconn()
288     {
289         return ($this->dbconn);
290     }
291
292     //   ttok   text UNIQUE,
293     //   tidx
294     function bin5_points_save($date, $table, $tidx, $ucodes, $pts)
295     {
296         GLOBAL $G_dbpfx;
297         $sql_ttok = escsql($table->table_token);
298
299         $is_trans = FALSE;
300         $ret = FALSE;
301
302         $n = count($ucodes);
303         /* check the existence of the nick in the BriskDB */
304         log_main("bin5_points_save: ");
305
306         do {
307             if ($this->query("BEGIN") == FALSE) {
308                 break;
309             }
310             $is_trans = TRUE;
311
312             /*
313              * matches management
314              */
315             $mtc_sql = sprintf("UPDATE %sbin5_matches SET (mazzo_next, mult_next) = (%d, %d) WHERE ttok = '%s' RETURNING *;",
316                                $G_dbpfx, $table->mazzo, $table->mult, $sql_ttok);
317             if (($mtc_pg  = $this->query($mtc_sql)) == FALSE || pg_numrows($mtc_pg) != 1) {
318
319                 // match not exists, insert it
320                 $mtc_sql = sprintf("INSERT INTO %sbin5_matches (ttok, tidx, mazzo_next, mult_next) VALUES ('%s', %d, %d, %d) RETURNING *;",
321                                    $G_dbpfx, $sql_ttok, $tidx, $table->mazzo, $table->mult);
322                 if (($mtc_pg  = $this->query($mtc_sql)) == FALSE || pg_affected_rows($mtc_pg) != 1) {
323                     log_crit(sprintf("bin5_points_save: failed at insert match [%s]", $mtc_sql));
324                     break;
325                 }
326                 $mtc_obj = pg_fetch_object($mtc_pg,0);
327
328                 for ($i = 0 ; $i < $n ; $i++) {
329                     $ord_sql = sprintf("INSERT INTO %sbin5_table_orders (mcode, ucode, pos) VALUES (%d, %d, %d);",
330                                        $G_dbpfx, $mtc_obj->code, $ucodes[$i], $i);
331                     if (($ord_pg = $this->query($ord_sql)) == FALSE || pg_affected_rows($ord_pg) != 1 ) {
332                         log_crit(sprintf("bin5_points_save: failed at insert table order [%s]", $ord_sql));
333                         break;
334                     }
335                 }
336                 if ($i < $n)
337                     break;
338             }
339             else {
340                 $mtc_obj = pg_fetch_object($mtc_pg,0);
341             }
342
343             /*
344              * games management
345              */
346             $gam_sql = sprintf("INSERT INTO %sbin5_games (mcode, tstamp, asta_pnt, pnt, asta_win, friend, mazzo, mult)
347                                                VALUES (%d, to_timestamp(%d), %d, %d, %d, %d, %d, %d) RETURNING *;",
348                                $G_dbpfx, $mtc_obj->code, $date,
349                                $table->old_asta_pnt, $table->old_pnt,
350                                $table->old_asta_win,
351                                $table->old_friend,
352                                $table->old_mazzo, $table->old_mult);
353             if (($gam_pg  = $this->query($gam_sql)) == FALSE || pg_affected_rows($gam_pg) != 1) {
354                 log_crit(sprintf("bin5_points_save: failed at insert game [%s]", $gam_sql));
355                 break;
356             }
357
358             $gam_obj = pg_fetch_object($gam_pg,0);
359
360             /*
361              * points management
362              */
363             for ($i = 0 ; $i < $n ; $i++) {
364                 /* put points */
365                 $pts_sql = sprintf("INSERT INTO %sbin5_points (gcode, ucode, pts)
366                                                VALUES (%d, %d, %d);",
367                                    $G_dbpfx, $gam_obj->code, $ucodes[$i], $pts[$i]);
368                 if (($pts_pg  = $this->query($pts_sql)) == FALSE || pg_affected_rows($pts_pg) != 1) {
369                     log_crit(sprintf("bin5_points_save: failed at insert point [%s]", $pts_sql));
370                     break;
371                 }
372             }
373             if ($i < $n)
374                 break;
375
376             if ($this->query("COMMIT") == FALSE) {
377                 break;
378             }
379
380             $is_trans = FALSE;
381
382             $ret =  TRUE;
383         } while (0);
384
385         if ($is_trans)
386             $this->query("ROLLBACK");
387
388         return $ret;
389     }
390
391 } // End class BriskDB
392
393 class LoginDBOld
394 {
395     var $item;
396     var $item_n;
397
398     function LoginDBOld($filename)
399     {
400         GLOBAL $DOCUMENT_ROOT;
401         log_main("LoginDBOld create:start");
402
403         if (file_exists("$DOCUMENT_ROOT/Etc/".$filename)) {
404             require("$DOCUMENT_ROOT/Etc/".$filename);
405         }
406         else {
407             return (FALSE);
408         }
409         $this->item_n = count($this->item);
410         log_main("LoginDBOld create:end");
411     }
412
413     function count()
414     {
415         return ($this->item_n);
416     }
417
418 } // End class LoginDBOld
419
420 ?>