]> git.mxchange.org Git - friendica.git/blob - include/dba_pdo.php
add the module to the page title
[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       $intErrorCode = false;
130         
131     } catch (\Exception $objException) {
132       $result = false;
133       $intErrorCode = $objPreparedQueryPool->get($strQueryAlias)->get('PDOStatement')->errorCode();
134     }
135
136                 $stamp2 = microtime(true);
137                 $duration = (float)($stamp2-$stamp1);
138
139                 $a->save_timestamp($stamp1, "database");
140
141                 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
142                         if (($duration > $a->config["system"]["db_loglimit"])) {
143                                 $duration = round($duration, 3);
144                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
145                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
146                                                 basename($backtrace[1]["file"])."\t".
147                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
148                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
149                         }
150                 }
151
152                 if($intErrorCode)
153       $this->error = $intErrorCode;
154
155                 if(strlen($this->error)) {
156                         logger('dba: ' . $this->error);
157                 }
158
159                 if($this->debug) {
160
161                         $mesg = '';
162
163                         if($result === false)
164                                 $mesg = 'false';
165                         elseif($result === true)
166                                 $mesg = 'true';
167                         else {
168         # this needs fixing, but is a bug itself
169                                 #$mesg = mysql_num_rows($result) . ' results' . EOL; 
170                         }
171
172                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
173                                 . (($this->error) ? ' error: ' . $this->error : '')
174                                 . EOL;
175
176                         logger('dba: ' . $str );
177                 }
178
179                 /**
180                  * If dbfail.out exists, we will write any failed calls directly to it,
181                  * regardless of any logging that may or may nor be in effect.
182                  * These usually indicate SQL syntax errors that need to be resolved.
183                  */
184
185                 if(isset($result) AND ($result === false)) {
186                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
187                         if(file_exists('dbfail.out'))
188                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
189                 }
190
191                 if(isset($result) AND (($result === true) || ($result === false)))
192                         return $result;
193     
194                 if ($onlyquery) {
195                         $this->result = $r;       # this will store an PDOStatement Object in result
196       $this->result->execute(); # execute the Statement, to get its result
197                         return true;
198                 }
199     
200                 //$a->save_timestamp($stamp1, "database");
201
202                 if($this->debug)
203                         logger('dba: ' . printable(print_r($r, true)));
204                 return($r);
205         }
206
207         public function qfetch() {
208
209                 if (false === $this->result)
210       return false;
211
212     return $this->result->fetch();
213
214         }
215   
216         public function qclose() {
217                 if ($this->result)
218       return $this->result->closeCursor();
219         }
220
221         public function dbg($dbg) {
222                 $this->debug = $dbg;
223         }
224
225         public function escape($str) {
226                 if($this->db && $this->connected) {
227       $strQuoted = $this->db->quote($str);
228       # this workaround is needed, because quote creates "'" and the beginning and the end
229       # of the string, which is correct. but until now the queries set this delimiter manually,
230       # so we must remove them from here and wait until everything uses prepared statements
231       return mb_substr($strQuoted, 1, mb_strlen($strQuoted) - 2); 
232                 }
233         }
234
235         function __destruct() {
236                 if ($this->db) 
237                   \DDDBL\disconnect();
238         }
239 }}
240
241 if(! function_exists('printable')) {
242 function printable($s) {
243         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
244         $s = str_replace("\x00",'.',$s);
245         if(x($_SERVER,'SERVER_NAME'))
246                 $s = escape_tags($s);
247         return $s;
248 }}
249
250 // Procedural functions
251 if(! function_exists('dbg')) { 
252 function dbg($state) {
253         global $db;
254         if($db)
255         $db->dbg($state);
256 }}
257
258 if(! function_exists('dbesc')) { 
259 function dbesc($str) {
260         global $db;
261         if($db && $db->connected)
262                 return($db->escape($str));
263         else
264                 return(str_replace("'","\\'",$str));
265 }}
266
267
268
269 // Function: q($sql,$args);
270 // Description: execute SQL query with printf style args.
271 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
272 //                   'user', 1);
273
274 if(! function_exists('q')) { 
275 function q($sql) {
276
277         global $db;
278         $args = func_get_args();
279         unset($args[0]);
280
281         if($db && $db->connected) {
282                 $stmt = @vsprintf($sql,$args); // Disabled warnings
283                 //logger("dba: q: $stmt", LOGGER_ALL);
284                 if($stmt === false)
285                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
286                 return $db->q($stmt);
287         }
288
289         /**
290          *
291          * This will happen occasionally trying to store the 
292          * session data after abnormal program termination 
293          *
294          */
295         logger('dba: no database: ' . print_r($args,true));
296         return false; 
297
298 }}
299
300 /**
301  *
302  * Raw db query, no arguments
303  *
304  */
305
306 if(! function_exists('dbq')) { 
307 function dbq($sql) {
308
309         global $db;
310         if($db && $db->connected)
311                 $ret = $db->q($sql);
312         else
313                 $ret = false;
314         return $ret;
315 }}
316
317
318 // Caller is responsible for ensuring that any integer arguments to 
319 // dbesc_array are actually integers and not malformed strings containing
320 // SQL injection vectors. All integer array elements should be specifically 
321 // cast to int to avoid trouble. 
322
323
324 if(! function_exists('dbesc_array_cb')) {
325 function dbesc_array_cb(&$item, $key) {
326         if(is_string($item))
327                 $item = dbesc($item);
328 }}
329
330
331 if(! function_exists('dbesc_array')) {
332 function dbesc_array(&$arr) {
333         if(is_array($arr) && count($arr)) {
334                 array_walk($arr,'dbesc_array_cb');
335         }
336 }}
337
338 if(! function_exists('dba_timer')) {
339 function dba_timer() {
340   return microtime(true);
341 }}