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