]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Better debugging
[friendica.git] / include / dba.php
1 <?php
2 require_once("dbm.php");
3 require_once('include/datetime.php');
4
5 /**
6  * @class MySQL database class
7  *
8  * For debugging, insert 'dbg(1);' anywhere in the program flow.
9  * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
10  * When logging, all binary info is converted to text and html entities are escaped so that
11  * the debugging stream is safe to view within both terminals and web pages.
12  *
13  */
14
15 class dba {
16
17         private $debug = 0;
18         private $db;
19         private $result;
20         private $driver;
21         public  $connected = false;
22         public  $error = false;
23         private $_server_info = '';
24         private static $dbo;
25
26         function __construct($server, $user, $pass, $db, $install = false) {
27                 $a = get_app();
28
29                 $stamp1 = microtime(true);
30
31                 $server = trim($server);
32                 $user = trim($user);
33                 $pass = trim($pass);
34                 $db = trim($db);
35
36                 if (!(strlen($server) && strlen($user))) {
37                         $this->connected = false;
38                         $this->db = null;
39                         return;
40                 }
41
42                 if ($install) {
43                         if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
44                                 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
45                                         $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
46                                         $this->connected = false;
47                                         $this->db = null;
48                                         return;
49                                 }
50                         }
51                 }
52
53                 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
54                         $this->driver = 'pdo';
55                         $connect = "mysql:host=".$server.";dbname=".$db;
56                         if (isset($a->config["system"]["db_charset"])) {
57                                 $connect .= ";charset=".$a->config["system"]["db_charset"];
58                         }
59                         $this->db = @new PDO($connect, $user, $pass);
60                         if (!$this->db->errorCode()) {
61                                 $this->connected = true;
62                         }
63                 } elseif (class_exists('mysqli')) {
64                         $this->driver = 'mysqli';
65                         $this->db = @new mysqli($server,$user,$pass,$db);
66                         if (!mysqli_connect_errno()) {
67                                 $this->connected = true;
68
69                                 if (isset($a->config["system"]["db_charset"])) {
70                                         $this->db->set_charset($a->config["system"]["db_charset"]);
71                                 }
72                         }
73                 } elseif (function_exists('mysql_connect')) {
74                         $this->driver = 'mysql';
75                         $this->db = mysql_connect($server,$user,$pass);
76                         if ($this->db && mysql_select_db($db,$this->db)) {
77                                 $this->connected = true;
78
79                                 if (isset($a->config["system"]["db_charset"])) {
80                                         mysql_set_charset($a->config["system"]["db_charset"], $this->db);
81                                 }
82                         }
83                 } else {
84                         // No suitable SQL driver was found.
85                         if (!$install) {
86                                 system_unavailable();
87                         }
88                 }
89
90                 if (!$this->connected) {
91                         $this->db = null;
92                         if (!$install) {
93                                 system_unavailable();
94                         }
95                 }
96                 $a->save_timestamp($stamp1, "network");
97
98                 self::$dbo = $this;
99         }
100
101         /**
102          * @brief Returns the MySQL server version string
103          * 
104          * This function discriminate between the deprecated mysql API and the current
105          * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
106          *
107          * @return string
108          */
109         public function server_info() {
110                 if ($this->_server_info == '') {
111                         switch ($this->driver) {
112                                 case 'pdo':
113                                         $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
114                                         break;
115                                 case 'mysqli':
116                                         $this->_server_info = $this->db->server_info;
117                                         break;
118                                 case 'mysql':
119                                         $this->_server_info = mysql_get_server_info($this->db);
120                                         break;
121                         }
122                 }
123                 return $this->_server_info;
124         }
125
126         /**
127          * @brief Returns the selected database name
128          *
129          * @return string
130          */
131         public function database_name() {
132                 $r = $this->q("SELECT DATABASE() AS `db`");
133
134                 return $r[0]['db'];
135         }
136
137         /**
138          * @brief Analyze a database query and log this if some conditions are met.
139          *
140          * @param string $query The database query that will be analyzed
141          */
142         public function log_index($query) {
143                 $a = get_app();
144
145                 if ($a->config["system"]["db_log_index"] == "") {
146                         return;
147                 }
148
149                 // Don't explain an explain statement
150                 if (strtolower(substr($query, 0, 7)) == "explain") {
151                         return;
152                 }
153
154                 // Only do the explain on "select", "update" and "delete"
155                 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
156                         return;
157                 }
158
159                 $r = $this->q("EXPLAIN ".$query);
160                 if (!dbm::is_result($r)) {
161                         return;
162                 }
163
164                 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
165                 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
166
167                 foreach ($r AS $row) {
168                         if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
169                                 $log = (in_array($row['key'], $watchlist) AND
170                                         ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
171                         } else {
172                                 $log = false;
173                         }
174
175                         if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
176                                 $log = true;
177                         }
178
179                         if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
180                                 $log = false;
181                         }
182
183                         if ($log) {
184                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
185                                 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
186                                                 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
187                                                 basename($backtrace[1]["file"])."\t".
188                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
189                                                 substr($query, 0, 2000)."\n", FILE_APPEND);
190                         }
191                 }
192         }
193
194         public function q($sql, $onlyquery = false) {
195                 $a = get_app();
196
197                 if (!$this->db || !$this->connected) {
198                         return false;
199                 }
200
201                 $this->error = '';
202
203                 $connstr = ($this->connected() ? "Connected" : "Disonnected");
204
205                 $stamp1 = microtime(true);
206
207                 $orig_sql = $sql;
208
209                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
210                         $sql = "/*".$a->callstack()." */ ".$sql;
211                 }
212
213                 $columns = 0;
214
215                 switch ($this->driver) {
216                         case 'pdo':
217                                 $result = @$this->db->query($sql);
218                                 // Is used to separate between queries that returning data - or not
219                                 if (!is_bool($result)) {
220                                         $columns = $result->columnCount();
221                                 }
222                                 break;
223                         case 'mysqli':
224                                 $result = @$this->db->query($sql);
225                                 break;
226                         case 'mysql':
227                                 $result = @mysql_query($sql,$this->db);
228                                 break;
229                 }
230                 $stamp2 = microtime(true);
231                 $duration = (float)($stamp2 - $stamp1);
232
233                 $a->save_timestamp($stamp1, "database");
234
235                 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
236                         $a->save_timestamp($stamp1, "database_write");
237                 }
238                 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
239                         if (($duration > $a->config["system"]["db_loglimit"])) {
240                                 $duration = round($duration, 3);
241                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
242                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
243                                                 basename($backtrace[1]["file"])."\t".
244                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
245                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
246                         }
247                 }
248
249                 switch ($this->driver) {
250                         case 'pdo':
251                                 $errorInfo = $this->db->errorInfo();
252                                 if ($errorInfo) {
253                                         $this->error = $errorInfo[2];
254                                         $this->errorno = $errorInfo[1];
255                                 }
256                                 break;
257                         case 'mysqli':
258                                 if ($this->db->errno) {
259                                         $this->error = $this->db->error;
260                                         $this->errorno = $this->db->errno;
261                                 }
262                                 break;
263                         case 'mysql':
264                                 if (mysql_errno($this->db)) {
265                                         $this->error = mysql_error($this->db);
266                                         $this->errorno = mysql_errno($this->db);
267                                 }
268                                 break;
269                 }
270                 if (strlen($this->error)) {
271                         logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
272                 }
273
274                 if ($this->debug) {
275
276                         $mesg = '';
277
278                         if ($result === false) {
279                                 $mesg = 'false';
280                         } elseif ($result === true) {
281                                 $mesg = 'true';
282                         } else {
283                                 switch ($this->driver) {
284                                         case 'pdo':
285                                                 $mesg = $result->rowCount().' results'.EOL;
286                                                 break;
287                                         case 'mysqli':
288                                                 $mesg = $result->num_rows.' results'.EOL;
289                                                 break;
290                                         case 'mysql':
291                                                 $mesg = mysql_num_rows($result).' results'.EOL;
292                                                 break;
293                                 }
294                         }
295
296                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
297                                 . (($this->error) ? ' error: ' . $this->error : '')
298                                 . EOL;
299
300                         logger('dba: ' . $str );
301                 }
302
303                 /**
304                  * If dbfail.out exists, we will write any failed calls directly to it,
305                  * regardless of any logging that may or may nor be in effect.
306                  * These usually indicate SQL syntax errors that need to be resolved.
307                  */
308
309                 if ($result === false) {
310                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
311                         if (file_exists('dbfail.out')) {
312                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
313                         }
314                 }
315
316                 if (is_bool($result)) {
317                         return $result;
318                 }
319                 if ($onlyquery) {
320                         $this->result = $result;
321                         return true;
322                 }
323
324                 $r = array();
325                 switch ($this->driver) {
326                         case 'pdo':
327                                 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
328                                         $r[] = $x;
329                                 }
330                                 $result->closeCursor();
331                                 break;
332                         case 'mysqli':
333                                 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
334                                         $r[] = $x;
335                                 }
336                                 $result->free_result();
337                                 break;
338                         case 'mysql':
339                                 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
340                                         $r[] = $x;
341                                 }
342                                 mysql_free_result($result);
343                                 break;
344                 }
345
346                 // PDO doesn't return "true" on successful operations - like mysqli does
347                 // Emulate this behaviour by checking if the query returned data and had columns
348                 // This should be reliable enough
349                 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
350                         return true;
351                 }
352
353                 //$a->save_timestamp($stamp1, "database");
354
355                 if ($this->debug) {
356                         logger('dba: ' . printable(print_r($r, true)));
357                 }
358                 return($r);
359         }
360
361         public function dbg($dbg) {
362                 $this->debug = $dbg;
363         }
364
365         public function escape($str) {
366                 if ($this->db && $this->connected) {
367                         switch ($this->driver) {
368                                 case 'pdo':
369                                         return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
370                                 case 'mysqli':
371                                         return @$this->db->real_escape_string($str);
372                                 case 'mysql':
373                                         return @mysql_real_escape_string($str,$this->db);
374                         }
375                 }
376         }
377
378         function connected() {
379                 switch ($this->driver) {
380                         case 'pdo':
381                                 // Not sure if this really is working like expected
382                                 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
383                                 break;
384                         case 'mysqli':
385                                 $connected = $this->db->ping();
386                                 break;
387                         case 'mysql':
388                                 $connected = mysql_ping($this->db);
389                                 break;
390                 }
391                 return $connected;
392         }
393
394         function insert_id() {
395                 switch ($this->driver) {
396                         case 'pdo':
397                                 $id = $this->db->lastInsertId();
398                                 break;
399                         case 'mysqli':
400                                 $id = $this->db->insert_id;
401                                 break;
402                         case 'mysql':
403                                 $id = mysql_insert_id($this->db);
404                                 break;
405                 }
406                 return $id;
407         }
408
409         function __destruct() {
410                 if ($this->db) {
411                         switch ($this->driver) {
412                                 case 'pdo':
413                                         $this->db = null;
414                                         break;
415                                 case 'mysqli':
416                                         $this->db->close();
417                                         break;
418                                 case 'mysql':
419                                         mysql_close($this->db);
420                                         break;
421                         }
422                 }
423         }
424
425         /**
426          * @brief Replaces ANY_VALUE() function by MIN() function,
427          *  if the database server does not support ANY_VALUE().
428          *
429          * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
430          * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
431          * A standard fall-back is to use MIN().
432          *
433          * @param string $sql An SQL string without the values
434          * @return string The input SQL string modified if necessary.
435          */
436         public function any_value_fallback($sql) {
437                 $server_info = $this->server_info();
438                 if (version_compare($server_info, '5.7.5', '<') ||
439                         (stripos($server_info, 'MariaDB') !== false)) {
440                         $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
441                 }
442                 return $sql;
443         }
444
445         /**
446          * @brief Replaces the ? placeholders with the parameters in the $args array
447          *
448          * @param string $sql SQL query
449          * @param array $args The parameters that are to replace the ? placeholders
450          * @return string The replaced SQL query
451          */
452         static private function replace_parameters($sql, $args) {
453                 $offset = 0;
454                 foreach ($args AS $param => $value) {
455                         if (is_int($args[$param]) OR is_float($args[$param])) {
456                                 $replace = intval($args[$param]);
457                         } else {
458                                 $replace = "'".dbesc($args[$param])."'";
459                         }
460
461                         $pos = strpos($sql, '?', $offset);
462                         if ($pos !== false) {
463                                 $sql = substr_replace($sql, $replace, $pos, 1);
464                         }
465                         $offset = $pos + strlen($replace);
466                 }
467                 return $sql;
468         }
469
470         /**
471          * @brief Executes a prepared statement that returns data
472          * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
473          * @param string $sql SQL statement
474          * @return object statement object
475          */
476         static public function p($sql) {
477                 $a = get_app();
478
479                 $stamp1 = microtime(true);
480
481                 $args = func_get_args();
482                 unset($args[0]);
483
484                 if (!self::$dbo OR !self::$dbo->connected) {
485                         return false;
486                 }
487
488                 $sql = self::$dbo->any_value_fallback($sql);
489
490                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
491                         $sql = "/*".$a->callstack()." */ ".$sql;
492                 }
493
494                 switch (self::$dbo->driver) {
495                         case 'pdo':
496                                 if (!$stmt = self::$dbo->db->prepare($sql)) {
497                                         $errorInfo = self::$dbo->db->errorInfo();
498                                         self::$dbo->error = $errorInfo[2];
499                                         self::$dbo->errorno = $errorInfo[1];
500                                         $retval = false;
501                                         break;
502                                 }
503
504                                 foreach ($args AS $param => $value) {
505                                         $stmt->bindParam($param, $args[$param]);
506                                 }
507
508                                 if (!$stmt->execute()) {
509                                         $errorInfo = self::$dbo->db->errorInfo();
510                                         self::$dbo->error = $errorInfo[2];
511                                         self::$dbo->errorno = $errorInfo[1];
512                                         $retval = false;
513                                 } else {
514                                         $retval = $stmt;
515                                 }
516                                 break;
517                         case 'mysqli':
518                                 $stmt = self::$dbo->db->stmt_init();
519
520                                 if (!$stmt->prepare($sql)) {
521                                         self::$dbo->error = self::$dbo->db->error;
522                                         self::$dbo->errorno = self::$dbo->db->errno;
523                                         $retval = false;
524                                         break;
525                                 }
526
527                                 $params = '';
528                                 $values = array();
529                                 foreach ($args AS $param => $value) {
530                                         if (is_int($args[$param])) {
531                                                 $params .= 'i';
532                                         } elseif (is_float($args[$param])) {
533                                                 $params .= 'd';
534                                         } elseif (is_string($args[$param])) {
535                                                 $params .= 's';
536                                         } else {
537                                                 $params .= 'b';
538                                         }
539                                         $values[] = &$args[$param];
540                                 }
541
542                                 array_unshift($values, $params);
543
544                                 call_user_func_array(array($stmt, 'bind_param'), $values);
545
546                                 if (!$stmt->execute()) {
547                                         self::$dbo->error = self::$dbo->db->error;
548                                         self::$dbo->errorno = self::$dbo->db->errno;
549                                         $retval = false;
550                                 } else {
551                                         $stmt->store_result();
552                                         $retval = $stmt;
553                                 }
554                                 break;
555                         case 'mysql':
556                                 // For the old "mysql" functions we cannot use prepared statements
557                                 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
558                                 if (mysql_errno(self::$dbo->db)) {
559                                         self::$dbo->error = mysql_error(self::$dbo->db);
560                                         self::$dbo->errorno = mysql_errno(self::$dbo->db);
561                                 }
562                                 break;
563                 }
564
565                 $a->save_timestamp($stamp1, 'database');
566
567                 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
568
569                         $stamp2 = microtime(true);
570                         $duration = (float)($stamp2 - $stamp1);
571
572                         if (($duration > $a->config["system"]["db_loglimit"])) {
573                                 $duration = round($duration, 3);
574                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
575
576                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
577                                                 basename($backtrace[1]["file"])."\t".
578                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
579                                                 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
580                         }
581                 }
582                 return $retval;
583         }
584
585         /**
586          * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
587          *
588          * @param string $sql SQL statement
589          * @return boolean Was the query successfull? False is returned only if an error occurred
590          */
591         static public function e($sql) {
592                 $a = get_app();
593
594                 $stamp = microtime(true);
595
596                 $args = func_get_args();
597
598                 $stmt = call_user_func_array('self::p', $args);
599
600                 if (is_bool($stmt)) {
601                         $retval = $stmt;
602                 } elseif (is_object($stmt)) {
603                         $retval = true;
604                 } else {
605                         $retval = false;
606                 }
607
608                 self::close($stmt);
609
610                 $a->save_timestamp($stamp, "database_write");
611
612                 return $retval;
613         }
614
615         /**
616          * @brief Check if data exists
617          *
618          * @param string $sql SQL statement
619          * @return boolean Are there rows for that query?
620          */
621         static public function exists($sql) {
622                 $args = func_get_args();
623
624                 $stmt = call_user_func_array('self::p', $args);
625
626                 if (is_bool($stmt)) {
627                         $retval = $stmt;
628                 } else {
629                         $retval = (self::rows($stmt) > 0);
630                 }
631
632                 self::close($stmt);
633
634                 return $retval;
635         }
636
637         /**
638          * @brief Returns the number of rows of a statement
639          *
640          * @param object Statement object
641          * @return int Number of rows
642          */
643         static public function num_rows($stmt) {
644                 switch (self::$dbo->driver) {
645                         case 'pdo':
646                                 return $stmt->rowCount();
647                         case 'mysqli':
648                                 return $stmt->num_rows;
649                         case 'mysql':
650                                 return mysql_num_rows($stmt);
651                 }
652                 return 0;
653         }
654
655         /**
656          * @brief Fetch a single row
657          *
658          * @param object $stmt statement object
659          * @return array current row
660          */
661         static public function fetch($stmt) {
662                 if (!is_object($stmt)) {
663                         return false;
664                 }
665
666                 switch (self::$dbo->driver) {
667                         case 'pdo':
668                                 return $stmt->fetch(PDO::FETCH_ASSOC);
669                         case 'mysqli':
670                                 // This code works, but is slow
671
672                                 // Bind the result to a result array
673                                 $cols = array();
674
675                                 $cols_num = array();
676                                 for ($x = 0; $x < $stmt->field_count; $x++) {
677                                         $cols[] = &$cols_num[$x];
678                                 }
679
680                                 call_user_func_array(array($stmt, 'bind_result'), $cols);
681
682                                 if (!$stmt->fetch()) {
683                                         return false;
684                                 }
685
686                                 // The slow part:
687                                 // We need to get the field names for the array keys
688                                 // It seems that there is no better way to do this.
689                                 $result = $stmt->result_metadata();
690                                 $fields = $result->fetch_fields();
691
692                                 $columns = array();
693                                 foreach ($cols_num AS $param => $col) {
694                                         $columns[$fields[$param]->name] = $col;
695                                 }
696                                 return $columns;
697                         case 'mysql':
698                                 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
699                 }
700         }
701
702         /**
703          * @brief Closes the current statement
704          *
705          * @param object $stmt statement object
706          * @return boolean was the close successfull?
707          */
708         static public function close($stmt) {
709                 if (!is_object($stmt)) {
710                         return false;
711                 }
712
713                 switch (self::$dbo->driver) {
714                         case 'pdo':
715                                 return $stmt->closeCursor();
716                         case 'mysqli':
717                                 return $stmt->free_result();
718                                 return $stmt->close();
719                         case 'mysql':
720                                 return mysql_free_result($stmt);
721                 }
722         }
723 }
724
725 function printable($s) {
726         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
727         $s = str_replace("\x00",'.',$s);
728         if (x($_SERVER,'SERVER_NAME')) {
729                 $s = escape_tags($s);
730         }
731         return $s;
732 }
733
734 // Procedural functions
735 function dbg($state) {
736         global $db;
737
738         if ($db) {
739                 $db->dbg($state);
740         }
741 }
742
743 function dbesc($str) {
744         global $db;
745
746         if ($db && $db->connected) {
747                 return($db->escape($str));
748         } else {
749                 return(str_replace("'","\\'",$str));
750         }
751 }
752
753 // Function: q($sql,$args);
754 // Description: execute SQL query with printf style args.
755 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
756 //                   'user', 1);
757 function q($sql) {
758         global $db;
759         $args = func_get_args();
760         unset($args[0]);
761
762         if ($db && $db->connected) {
763                 $sql = $db->any_value_fallback($sql);
764                 $stmt = @vsprintf($sql,$args); // Disabled warnings
765                 //logger("dba: q: $stmt", LOGGER_ALL);
766                 if ($stmt === false)
767                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
768
769                 $db->log_index($stmt);
770
771                 return $db->q($stmt);
772         }
773
774         /**
775          *
776          * This will happen occasionally trying to store the
777          * session data after abnormal program termination
778          *
779          */
780         logger('dba: no database: ' . print_r($args,true));
781         return false;
782 }
783
784 /**
785  * @brief Performs a query with "dirty reads"
786  *
787  * By doing dirty reads (reading uncommitted data) no locks are performed
788  * This function can be used to fetch data that doesn't need to be reliable.
789  *
790  * @param $args Query parameters (1 to N parameters of different types)
791  * @return array Query array
792  */
793 function qu($sql) {
794         global $db;
795
796         $args = func_get_args();
797         unset($args[0]);
798
799         if ($db && $db->connected) {
800                 $sql = $db->any_value_fallback($sql);
801                 $stmt = @vsprintf($sql,$args); // Disabled warnings
802                 if ($stmt === false)
803                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
804
805                 $db->log_index($stmt);
806
807                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
808                 $retval = $db->q($stmt);
809                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
810                 return $retval;
811         }
812
813         /**
814          *
815          * This will happen occasionally trying to store the
816          * session data after abnormal program termination
817          *
818          */
819         logger('dba: no database: ' . print_r($args,true));
820         return false;
821 }
822
823 /**
824  *
825  * Raw db query, no arguments
826  *
827  */
828 function dbq($sql) {
829         global $db;
830
831         if ($db && $db->connected) {
832                 $ret = $db->q($sql);
833         } else {
834                 $ret = false;
835         }
836         return $ret;
837 }
838
839 // Caller is responsible for ensuring that any integer arguments to
840 // dbesc_array are actually integers and not malformed strings containing
841 // SQL injection vectors. All integer array elements should be specifically
842 // cast to int to avoid trouble.
843 function dbesc_array_cb(&$item, $key) {
844         if (is_string($item))
845                 $item = dbesc($item);
846 }
847
848 function dbesc_array(&$arr) {
849         if (is_array($arr) && count($arr)) {
850                 array_walk($arr,'dbesc_array_cb');
851         }
852 }
853
854 function dba_timer() {
855         return microtime(true);
856 }