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