]> git.mxchange.org Git - friendica.git/blob - include/dba.php
We now can work with prepared statements
[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         /**
471          * @brief Replaces ANY_VALUE() function by MIN() function,
472          *  if the database server does not support ANY_VALUE().
473          *
474          * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
475          * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
476          * A standard fall-back is to use MIN().
477          *
478          * @param string $sql An SQL string without the values
479          * @return string The input SQL string modified if necessary.
480          */
481         public function any_value_fallback($sql) {
482                 $server_info = $this->server_info();
483                 if (version_compare($server_info, '5.7.5', '<') ||
484                         (stripos($server_info, 'MariaDB') !== false)) {
485                         $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
486                 }
487                 return $sql;
488         }
489
490         function __destruct() {
491                 if ($this->db) {
492                         switch ($this->driver) {
493                                 case 'pdo':
494                                         $this->db = null;
495                                         break;
496                                 case 'mysqli':
497                                         $this->db->close();
498                                         break;
499                                 case 'mysql':
500                                         mysql_close($this->db);
501                                         break;
502                         }
503                 }
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         }
639
640         /**
641          * @brief Fetch a single row
642          *
643          * @param object $stmt statement object
644          * @return array current row
645          */
646         static public function fetch($stmt) {
647                 switch (self::$dbo->driver) {
648                         case 'pdo':
649                                 return $stmt->fetch(PDO::FETCH_ASSOC);
650                         case 'mysqli':
651                                 // When mysqlnd is installed, we can use a shortcut
652                                 if (method_exists($stmt, 'fetch_array')) {
653                                         return $stmt->fetch_array(MYSQLI_ASSOC);
654                                 }
655
656                                 // This code works, but is slow
657
658                                 // Bind the result to a result array
659                                 $cols = array();
660
661                                 $cols_num = array();
662                                 for ($x = 0; $x < $stmt->field_count; $x++) {
663                                         $cols[] = &$cols_num[$x];
664                                 }
665
666                                 call_user_func_array(array($stmt, 'bind_result'), $cols);
667
668                                 $success = $stmt->fetch();
669
670                                 if (!$success) {
671                                         return false;
672                                 }
673
674                                 // The slow part:
675                                 // We need to get the field names for the array keys
676                                 // It seems that there is no better way to do this.
677                                 $result = $stmt->result_metadata();
678
679                                 $columns = array();
680                                 foreach ($cols_num AS $col) {
681                                         $field = $result->fetch_field();
682                                         $columns[$field->name] = $col;
683                                 }
684                                 return $columns;
685                         case 'mysql':
686                                 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
687                 }
688         }
689
690         /**
691          * @brief Closes the current statement
692          *
693          * @param object $stmt statement object
694          * @return boolean was the close successfull?
695          */
696         static public function close($stmt) {
697                 switch (self::$dbo->driver) {
698                         case 'pdo':
699                                 return $stmt->closeCursor();
700                         case 'mysqli':
701                                 return $stmt->close();
702                         case 'mysql':
703                                 return mysql_free_result($stmt);
704                 }
705         }
706 }
707
708 function printable($s) {
709         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
710         $s = str_replace("\x00",'.',$s);
711         if (x($_SERVER,'SERVER_NAME')) {
712                 $s = escape_tags($s);
713         }
714         return $s;
715 }
716
717 // Procedural functions
718 function dbg($state) {
719         global $db;
720
721         if ($db) {
722                 $db->dbg($state);
723         }
724 }
725
726 function dbesc($str) {
727         global $db;
728
729         if ($db && $db->connected) {
730                 return($db->escape($str));
731         } else {
732                 return(str_replace("'","\\'",$str));
733         }
734 }
735
736 // Function: q($sql,$args);
737 // Description: execute SQL query with printf style args.
738 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
739 //                   'user', 1);
740 function q($sql) {
741         global $db;
742         $args = func_get_args();
743         unset($args[0]);
744
745         if ($db && $db->connected) {
746                 $sql = $db->any_value_fallback($sql);
747                 $stmt = @vsprintf($sql,$args); // Disabled warnings
748                 //logger("dba: q: $stmt", LOGGER_ALL);
749                 if ($stmt === false)
750                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
751
752                 $db->log_index($stmt);
753
754                 return $db->q($stmt);
755         }
756
757         /**
758          *
759          * This will happen occasionally trying to store the
760          * session data after abnormal program termination
761          *
762          */
763         logger('dba: no database: ' . print_r($args,true));
764         return false;
765 }
766
767 /**
768  * @brief Performs a query with "dirty reads"
769  *
770  * By doing dirty reads (reading uncommitted data) no locks are performed
771  * This function can be used to fetch data that doesn't need to be reliable.
772  *
773  * @param $args Query parameters (1 to N parameters of different types)
774  * @return array Query array
775  */
776 function qu($sql) {
777         global $db;
778
779         $args = func_get_args();
780         unset($args[0]);
781
782         if ($db && $db->connected) {
783                 $sql = $db->any_value_fallback($sql);
784                 $stmt = @vsprintf($sql,$args); // Disabled warnings
785                 if ($stmt === false)
786                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
787
788                 $db->log_index($stmt);
789
790                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
791                 $retval = $db->q($stmt);
792                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
793                 return $retval;
794         }
795
796         /**
797          *
798          * This will happen occasionally trying to store the
799          * session data after abnormal program termination
800          *
801          */
802         logger('dba: no database: ' . print_r($args,true));
803         return false;
804 }
805
806 /**
807  *
808  * Raw db query, no arguments
809  *
810  */
811 function dbq($sql) {
812         global $db;
813
814         if ($db && $db->connected) {
815                 $ret = $db->q($sql);
816         } else {
817                 $ret = false;
818         }
819         return $ret;
820 }
821
822 // Caller is responsible for ensuring that any integer arguments to
823 // dbesc_array are actually integers and not malformed strings containing
824 // SQL injection vectors. All integer array elements should be specifically
825 // cast to int to avoid trouble.
826 function dbesc_array_cb(&$item, $key) {
827         if (is_string($item))
828                 $item = dbesc($item);
829 }
830
831 function dbesc_array(&$arr) {
832         if (is_array($arr) && count($arr)) {
833                 array_walk($arr,'dbesc_array_cb');
834         }
835 }
836
837 function dba_timer() {
838         return microtime(true);
839 }