]> git.mxchange.org Git - friendica.git/blob - include/dba_pdo.php
New database system that uses PDO if present/Test script for doing database upgrades.
[friendica.git] / include / dba_pdo.php
1 <?php
2
3 require_once('include/datetime.php');
4
5 $objDDDBLResultHandler = new \DDDBL\DataObjectPool('Result-Handler');
6
7 /**
8   * create handler, which returns just the PDOStatement object
9   * this allows usage of the cursor to scroll through
10   * big result-sets
11   *
12   **/
13 $cloPDOStatementResultHandler = function(\DDDBL\Queue $objQueue) {
14
15   $objPDO = $objQueue->getState()->get('PDOStatement');
16   $objQueue->getState()->update(array('result' => $objPDO));
17   
18   # delete handler which closes the PDOStatement-cursor
19   # this will be done manual if using this handler
20   $objQueue->deleteHandler(QUEUE_CLOSE_CURSOR_POSITION);
21
22 };
23
24 $objDDDBLResultHandler->add('PDOStatement', array('HANDLER' => $cloPDOStatementResultHandler));
25
26 /**
27  *
28  * MySQL database class
29  *
30  * For debugging, insert 'dbg(1);' anywhere in the program flow.
31  * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
32  * When logging, all binary info is converted to text and html entities are escaped so that 
33  * the debugging stream is safe to view within both terminals and web pages.
34  *
35  */
36  
37 if(! class_exists('dba')) { 
38 class dba {
39
40         private $debug = 0;
41         private $db;
42         private $result;
43         public  $connected = false;
44         public  $error = false;
45
46         function __construct($server,$user,$pass,$db,$install = false) {
47                 global $a;
48     
49     # work around, to store the database - configuration in DDDBL
50     $objDataObjectPool = new \DDDBL\DataObjectPool('Database-Definition');
51     $objDataObjectPool->add('DEFAULT', array('CONNECTION' => "mysql:host=$server;dbname=$db",
52                                              'USER'       => $user,
53                                              'PASS'       => $pass,
54                                              'DEFAULT'    => true));
55
56                 $stamp1 = microtime(true);
57
58                 $server = trim($server);
59                 $user = trim($user);
60                 $pass = trim($pass);
61                 $db = trim($db);
62
63                 if (!(strlen($server) && strlen($user))){
64                         $this->connected = false;
65                         $this->db = null;
66                         return;
67                 }
68
69                 if($install) {
70                         if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
71                                 if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
72                                         $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
73                                         $this->connected = false;
74                                         $this->db = null;
75                                         return;
76                                 }
77                         }
78                 }
79
80     # etablish connection to database and store PDO object
81     \DDDBL\connect();
82     $this->db = \DDDBL\getDB();
83     
84     if(\DDDBL\isConnected()) {
85       $this->connected = true;
86     }
87   
88                 if(! $this->connected) {
89                         $this->db = null;
90                         if(! $install)
91                                 system_unavailable();
92                 }
93
94                 $a->save_timestamp($stamp1, "network");
95         }
96
97         public function getdb() {
98                 return $this->db;
99         }
100
101         public function q($sql, $onlyquery = false) {
102                 global $a;
103     
104     $strHandler = (true === $onlyquery) ? 'PDOStatement' : 'MULTI';
105     
106     $strQueryAlias = md5($sql);
107     $strSQLType    = strtoupper(strstr($sql, ' ', true));
108     
109     $objPreparedQueryPool = new \DDDBL\DataObjectPool('Query-Definition');
110     
111     # check if query do not exists till now, if so create its definition
112     if(!$objPreparedQueryPool->exists($strQueryAlias))
113       $objPreparedQueryPool->add($strQueryAlias, array('QUERY'   => $sql,
114                                                        'HANDLER' => $strHandler));
115
116                 if((! $this->db) || (! $this->connected))
117                         return false;
118
119                 $this->error = '';
120
121                 $stamp1 = microtime(true);
122
123     try {
124       $r = \DDDBL\get($strQueryAlias);
125       
126       # bad workaround to emulate the bizzare behavior of mysql_query
127       if(in_array($strSQLType, array('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'SET')))
128         $result = true;
129         
130     } catch (\Exception $objException) {
131       $result = false;
132       $intErrorCode = $objPreparedQueryPool->get($strQueryAlias)->get('PDOStatement')->errorCode();
133     }
134
135                 $stamp2 = microtime(true);
136                 $duration = (float)($stamp2-$stamp1);
137
138                 $a->save_timestamp($stamp1, "database");
139
140                 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
141                         if (($duration > $a->config["system"]["db_loglimit"])) {
142                                 $duration = round($duration, 3);
143                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
144                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
145                                                 basename($backtrace[1]["file"])."\t".
146                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
147                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
148                         }
149                 }
150
151                 if($intErrorCode)
152       $this->error = $intErrorCode;
153
154                 if(strlen($this->error)) {
155                         logger('dba: ' . $this->error);
156                 }
157
158                 if($this->debug) {
159
160                         $mesg = '';
161
162                         if($result === false)
163                                 $mesg = 'false';
164                         elseif($result === true)
165                                 $mesg = 'true';
166                         else {
167         # this needs fixing, but is a bug itself
168                                 #$mesg = mysql_num_rows($result) . ' results' . EOL; 
169                         }
170
171                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
172                                 . (($this->error) ? ' error: ' . $this->error : '')
173                                 . EOL;
174
175                         logger('dba: ' . $str );
176                 }
177
178                 /**
179                  * If dbfail.out exists, we will write any failed calls directly to it,
180                  * regardless of any logging that may or may nor be in effect.
181                  * These usually indicate SQL syntax errors that need to be resolved.
182                  */
183
184                 if($result === false) {
185                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
186                         if(file_exists('dbfail.out'))
187                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
188                 }
189
190                 if(($result === true) || ($result === false))
191                         return $result;
192
193                 if ($onlyquery) {
194                         $this->result = $result;
195                         return true;
196                 }
197     
198                 //$a->save_timestamp($stamp1, "database");
199
200                 if($this->debug)
201                         logger('dba: ' . printable(print_r($r, true)));
202                 return($r);
203         }
204
205         public function qfetch() {
206   
207                 if (!$this->result)
208       return false;
209       
210     return $this->result->fetch();
211
212         }
213   
214         public function qclose() {
215                 if ($this->result)
216       $this->result->closeCursor();
217         }
218
219         public function dbg($dbg) {
220                 $this->debug = $dbg;
221         }
222
223         public function escape($str) {
224                 if($this->db && $this->connected) {
225       $strQuoted = $this->db->quote($str);
226       # this workaround is needed, because quote creates "'" and the beginning and the end
227       # of the string, which is correct. but until now the queries set this delimiter manually,
228       # so we must remove them from here and wait until everything uses prepared statements
229       return mb_substr($strQuoted, 1, mb_strlen($strQuoted) - 2); 
230                 }
231         }
232
233         function __destruct() {
234                 if ($this->db) 
235                   \DDDBL\disconnect();
236         }
237 }}
238
239 if(! function_exists('printable')) {
240 function printable($s) {
241         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
242         $s = str_replace("\x00",'.',$s);
243         if(x($_SERVER,'SERVER_NAME'))
244                 $s = escape_tags($s);
245         return $s;
246 }}
247
248 // Procedural functions
249 if(! function_exists('dbg')) { 
250 function dbg($state) {
251         global $db;
252         if($db)
253         $db->dbg($state);
254 }}
255
256 if(! function_exists('dbesc')) { 
257 function dbesc($str) {
258         global $db;
259         if($db && $db->connected)
260                 return($db->escape($str));
261         else
262                 return(str_replace("'","\\'",$str));
263 }}
264
265
266
267 // Function: q($sql,$args);
268 // Description: execute SQL query with printf style args.
269 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
270 //                   'user', 1);
271
272 if(! function_exists('q')) { 
273 function q($sql) {
274
275         global $db;
276         $args = func_get_args();
277         unset($args[0]);
278
279         if($db && $db->connected) {
280                 $stmt = @vsprintf($sql,$args); // Disabled warnings
281                 //logger("dba: q: $stmt", LOGGER_ALL);
282                 if($stmt === false)
283                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
284                 return $db->q($stmt);
285         }
286
287         /**
288          *
289          * This will happen occasionally trying to store the 
290          * session data after abnormal program termination 
291          *
292          */
293         logger('dba: no database: ' . print_r($args,true));
294         return false; 
295
296 }}
297
298 /**
299  *
300  * Raw db query, no arguments
301  *
302  */
303
304 if(! function_exists('dbq')) { 
305 function dbq($sql) {
306
307         global $db;
308         if($db && $db->connected)
309                 $ret = $db->q($sql);
310         else
311                 $ret = false;
312         return $ret;
313 }}
314
315
316 // Caller is responsible for ensuring that any integer arguments to 
317 // dbesc_array are actually integers and not malformed strings containing
318 // SQL injection vectors. All integer array elements should be specifically 
319 // cast to int to avoid trouble. 
320
321
322 if(! function_exists('dbesc_array_cb')) {
323 function dbesc_array_cb(&$item, $key) {
324         if(is_string($item))
325                 $item = dbesc($item);
326 }}
327
328
329 if(! function_exists('dbesc_array')) {
330 function dbesc_array(&$arr) {
331         if(is_array($arr) && count($arr)) {
332                 array_walk($arr,'dbesc_array_cb');
333         }
334 }}
335
336 if(! function_exists('dba_timer')) {
337 function dba_timer() {
338   return microtime(true);
339 }}
340