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