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