pg_query wrapper to recovery if it fails
[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
161     
162     function login_verify($login, $pass)
163     {
164         GLOBAL $G_dbpfx;
165         
166         $ret = FALSE;
167         
168         log_main("login_verify: ".$login);
169         
170         
171         //O /* check the existence of the nick in the BriskDB */
172         //O for ($i = 0 ; $i < $this->item_n ; $i++) {
173         //O log_main("login_verify: BEGIN");
174         
175         if (($user_obj = $this->getrecord_bylogin($login)) == FALSE) {
176             return FALSE;
177         }
178
179         log_main("login[".$user_obj->code."]: ".$user_obj->login);
180         
181         /* if it exists check for a valid challenge */
182         if (($a_sem = Challenges::lock_data(TRUE)) != FALSE) { 
183             if (($chals = &Challenges::load_data()) != FALSE) {
184                 for ($e = 0 ; $e < $chals->item_n ; $e++) {
185                     log_main("challenge[".$e."]: ".$chals->item[$e]->login);
186                     if (strcmp($login, $chals->item[$e]->login) == 0) {
187                         log_main("login_verify [".$pass."] with [".md5($chals->item[$e]->token.$user_obj->pass)."]");
188                         
189                         if (strcmp($pass, md5($chals->item[$e]->token.$user_obj->pass)) == 0) {
190                             log_main("login_verify SUCCESS for ".$login);
191                             
192                             $chals->rem($login);
193                             $ret = LoginDBItem::LoginDBItemFromRecord($user_obj);
194                             break;
195                         }
196                     }
197                 } // end for ($e = 0 ...
198             }
199             
200             if ($chals->ismod()) {
201                 Challenges::save_data(&$chals);
202             }
203             
204             Challenges::unlock_data($a_sem);
205         }
206         //O break;
207         // O } //  if (strcasecmp($this->item[$i]->login, ...
208         //O }
209     
210         return ($ret);
211     }
212
213     function getitem_bylogin($login, &$id) {
214         $ret = FALSE;
215         $id = -1;
216         
217         log_main("getitem_bylogin: ".$login);
218         
219         if (($user_obj = $this->getrecord_bylogin($login)) == FALSE)
220             return $ret;
221
222         $id = $user_obj->code;
223         return (LoginDBItem::LoginDBItemFromRecord($user_obj));
224     }
225     
226     // TODO FOR DB
227     function getmail($login)
228     {
229         log_main("getmail");
230
231         if (($ret = $this->getrecord_bylogin($login)) == FALSE)
232             return FALSE;
233         
234         return ($ret->email);
235     }
236
237     function addusers_from_olddb($olddb, &$cont)
238     {
239         GLOBAL $G_dbpfx;
240
241         for ($i = 0 ; $i < $olddb->count() ; $i++) {
242             $user_sql = sprintf("INSERT INTO %susers ( login, pass, email, type) VALUES ('%s', '%s', '%s', %d);",
243                                 $G_dbpfx, escsql(strtolower($olddb->item[$i]->login)), escsql($olddb->item[$i]->pass),
244                                 escsql($olddb->item[$i]->email), $olddb->item[$i]->type & USER_FLAG_TY_ALL); 
245             
246             // if ( ! (($user_pg = pg_exec($dbconn,$order_add_sql)) != FALSE && pg_affected_rows($order_pg) == 1) ) {
247
248             if ( ! (($user_pg  = $this->query($user_sql)) != FALSE && pg_affected_rows($user_pg) == 1) ) {
249                 $cont .= sprintf("ERROR IN LINE: %s\n", eschtml($user_sql));
250
251                 return FALSE;
252             }
253         }
254         return TRUE;
255     }
256
257     function getdbconn()
258     {
259         return ($this->dbconn);
260     }
261
262     //   ttok   text UNIQUE,      
263     //   tidx   
264     function bin5_points_save($date, $ttok, $tidx, $ucodes, $pts)
265     {
266         GLOBAL $G_dbpfx;
267
268         $is_trans = FALSE;
269         $ret = FALSE;
270
271         $n = count($ucodes);
272         /* check the existence of the nick in the BriskDB */
273         log_main("bin5_points_save: ");
274         
275         do {
276             if ($this->query("BEGIN") == FALSE) {
277                 break;
278             }
279             $is_trans = TRUE;
280
281             /*
282              * matches management
283              */
284             $mtc_sql = sprintf("SELECT * FROM %sbin5_matches WHERE ttok = '%s';", $G_dbpfx, escsql($ttok));
285             if (($mtc_pg  = $this->query($mtc_sql)) == FALSE || pg_numrows($mtc_pg) != 1) {
286                 // match not exists, insert it
287                 $mtc_sql = sprintf("INSERT INTO %sbin5_matches (ttok, tidx) VALUES ('%s', %d) RETURNING *;",
288                                    $G_dbpfx, escsql($ttok), $tidx);
289                 if ( ! (($mtc_pg  = $this->query($mtc_sql)) != FALSE &&
290                         pg_affected_rows($mtc_pg) == 1) ) {
291                     log_crit(sprintf("bin5_points_save: failed at insert match [%s]", $mtc_sql));
292                     break;
293                 }
294             }
295             $mtc_obj = pg_fetch_object($mtc_pg,0);
296
297             /*
298              * games management
299              */
300             $gam_sql = sprintf("INSERT INTO %sbin5_games (mcode, tstamp) 
301                                                VALUES (%d, to_timestamp(%d)) RETURNING *;",
302                                $G_dbpfx, $mtc_obj->code, $date);
303             if ( ! (($gam_pg  = $this->query($gam_sql)) != FALSE &&
304                     pg_affected_rows($gam_pg) == 1) ) {
305                 log_crit(sprintf("bin5_points_save: failed at insert game [%s]", $gam_sql));
306                 break;                        
307             }
308         
309             $gam_obj = pg_fetch_object($gam_pg,0);
310
311             /*
312              * points management
313              */
314             for ($i = 0 ; $i < $n ; $i++) {
315                 /* put points */
316                 $pts_sql = sprintf("INSERT INTO %sbin5_points (gcode, ucode, pts) 
317                                                VALUES (%d, %d, %d);",
318                                    $G_dbpfx, $gam_obj->code, $ucodes[$i], $pts[$i]);
319                 if ( ! (($pts_pg  = $this->query($pts_sql)) != FALSE &&
320                         pg_affected_rows($pts_pg) == 1) ) {
321                     log_crit(sprintf("bin5_points_save: failed at insert point [%s]", $pts_sql));
322                     break;                        
323                 }
324             }
325
326             if ($i < $n)
327                 break;
328             
329             if ($this->query("COMMIT") == FALSE) {
330                 break;
331             }
332              
333             $is_trans = FALSE;
334
335             $ret =  TRUE;
336         } while (0);
337         
338         if ($is_trans)
339             $this->query("ROLLBACK");
340         
341         return $ret;
342     }
343
344 } // End class BriskDB
345
346 class LoginDBOld 
347 {
348     var $item;
349     var $item_n;
350
351     function LoginDBOld($filename)
352     {
353         GLOBAL $DOCUMENT_ROOT;
354         log_main("LoginDBOld create:start");
355
356         if (file_exists("$DOCUMENT_ROOT/Etc/".$filename)) {
357             require("$DOCUMENT_ROOT/Etc/".$filename);
358         }
359         else {
360             return (FALSE);
361         }
362         $this->item_n = count($this->item);
363         log_main("LoginDBOld create:end");
364     }
365
366     function count()
367     {
368         return ($this->item_n);
369     }
370
371 } // End class LoginDBOld
372
373 ?>