]> git.mxchange.org Git - friendica.git/blob - include/dba.php
DFRN: Improved delivery status handling
[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         public  $errorno = 0;
25         public  $affected_rows = 0;
26         private $_server_info = '';
27         private static $in_transaction = false;
28         private static $dbo;
29         private static $relation = array();
30
31         function __construct($serveraddr, $user, $pass, $db, $install = false) {
32                 $a = get_app();
33
34                 $stamp1 = microtime(true);
35
36                 $serveraddr = trim($serveraddr);
37
38                 $serverdata = explode(':', $serveraddr);
39                 $server = $serverdata[0];
40
41                 if (count($serverdata) > 1) {
42                         $port = trim($serverdata[1]);
43                 }
44
45                 $server = trim($server);
46                 $user = trim($user);
47                 $pass = trim($pass);
48                 $db = trim($db);
49
50                 if (!(strlen($server) && strlen($user))) {
51                         $this->connected = false;
52                         $this->db = null;
53                         return;
54                 }
55
56                 if ($install) {
57                         if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
58                                 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
59                                         $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
60                                         $this->connected = false;
61                                         $this->db = null;
62                                         return;
63                                 }
64                         }
65                 }
66
67                 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
68                         $this->driver = 'pdo';
69                         $connect = "mysql:host=".$server.";dbname=".$db;
70
71                         if (isset($port)) {
72                                 $connect .= ";port=".$port;
73                         }
74
75                         if (isset($a->config["system"]["db_charset"])) {
76                                 $connect .= ";charset=".$a->config["system"]["db_charset"];
77                         }
78                         try {
79                                 $this->db = @new PDO($connect, $user, $pass);
80                                 $this->connected = true;
81                         } catch (PDOException $e) {
82                                 $this->connected = false;
83                         }
84                 }
85
86                 if (!$this->connected && class_exists('mysqli')) {
87                         $this->driver = 'mysqli';
88                         $this->db = @new mysqli($server, $user, $pass, $db, $port);
89                         if (!mysqli_connect_errno()) {
90                                 $this->connected = true;
91
92                                 if (isset($a->config["system"]["db_charset"])) {
93                                         $this->db->set_charset($a->config["system"]["db_charset"]);
94                                 }
95                         }
96                 }
97
98                 if (!$this->connected && function_exists('mysql_connect')) {
99                         $this->driver = 'mysql';
100                         $this->db = mysql_connect($serveraddr, $user, $pass);
101                         if ($this->db && mysql_select_db($db, $this->db)) {
102                                 $this->connected = true;
103
104                                 if (isset($a->config["system"]["db_charset"])) {
105                                         mysql_set_charset($a->config["system"]["db_charset"], $this->db);
106                                 }
107                         }
108                 }
109
110                 // No suitable SQL driver was found.
111                 if (!$this->connected) {
112                         $this->db = null;
113                         if (!$install) {
114                                 system_unavailable();
115                         }
116                 }
117                 $a->save_timestamp($stamp1, "network");
118
119                 self::$dbo = $this;
120         }
121
122         /**
123          * @brief Returns the MySQL server version string
124          *
125          * This function discriminate between the deprecated mysql API and the current
126          * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
127          *
128          * @return string
129          */
130         public function server_info() {
131                 if ($this->_server_info == '') {
132                         switch ($this->driver) {
133                                 case 'pdo':
134                                         $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
135                                         break;
136                                 case 'mysqli':
137                                         $this->_server_info = $this->db->server_info;
138                                         break;
139                                 case 'mysql':
140                                         $this->_server_info = mysql_get_server_info($this->db);
141                                         break;
142                         }
143                 }
144                 return $this->_server_info;
145         }
146
147         /**
148          * @brief Returns the selected database name
149          *
150          * @return string
151          */
152         public function database_name() {
153                 $r = $this->q("SELECT DATABASE() AS `db`");
154
155                 return $r[0]['db'];
156         }
157
158         /**
159          * @brief Analyze a database query and log this if some conditions are met.
160          *
161          * @param string $query The database query that will be analyzed
162          */
163         public function log_index($query) {
164                 $a = get_app();
165
166                 if (empty($a->config["system"]["db_log_index"])) {
167                         return;
168                 }
169
170                 // Don't explain an explain statement
171                 if (strtolower(substr($query, 0, 7)) == "explain") {
172                         return;
173                 }
174
175                 // Only do the explain on "select", "update" and "delete"
176                 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
177                         return;
178                 }
179
180                 $r = $this->q("EXPLAIN ".$query);
181                 if (!dbm::is_result($r)) {
182                         return;
183                 }
184
185                 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
186                 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
187
188                 foreach ($r AS $row) {
189                         if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
190                                 $log = (in_array($row['key'], $watchlist) &&
191                                         ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
192                         } else {
193                                 $log = false;
194                         }
195
196                         if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
197                                 $log = true;
198                         }
199
200                         if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
201                                 $log = false;
202                         }
203
204                         if ($log) {
205                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
206                                 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
207                                                 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
208                                                 basename($backtrace[1]["file"])."\t".
209                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
210                                                 substr($query, 0, 2000)."\n", FILE_APPEND);
211                         }
212                 }
213         }
214
215         public function q($sql, $onlyquery = false) {
216                 $a = get_app();
217
218                 if (!$this->db || !$this->connected) {
219                         return false;
220                 }
221
222                 $this->error = '';
223
224                 $connstr = ($this->connected() ? "Connected" : "Disonnected");
225
226                 $stamp1 = microtime(true);
227
228                 $orig_sql = $sql;
229
230                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
231                         $sql = "/*".$a->callstack()." */ ".$sql;
232                 }
233
234                 $columns = 0;
235
236                 switch ($this->driver) {
237                         case 'pdo':
238                                 $result = @$this->db->query($sql);
239                                 // Is used to separate between queries that returning data - or not
240                                 if (!is_bool($result)) {
241                                         $columns = $result->columnCount();
242                                 }
243                                 break;
244                         case 'mysqli':
245                                 $result = @$this->db->query($sql);
246                                 break;
247                         case 'mysql':
248                                 $result = @mysql_query($sql,$this->db);
249                                 break;
250                 }
251                 $stamp2 = microtime(true);
252                 $duration = (float)($stamp2 - $stamp1);
253
254                 $a->save_timestamp($stamp1, "database");
255
256                 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
257                         $a->save_timestamp($stamp1, "database_write");
258                 }
259                 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
260                         if (($duration > $a->config["system"]["db_loglimit"])) {
261                                 $duration = round($duration, 3);
262                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
263                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
264                                                 basename($backtrace[1]["file"])."\t".
265                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
266                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
267                         }
268                 }
269
270                 switch ($this->driver) {
271                         case 'pdo':
272                                 $errorInfo = $this->db->errorInfo();
273                                 if ($errorInfo) {
274                                         $this->error = $errorInfo[2];
275                                         $this->errorno = $errorInfo[1];
276                                 }
277                                 break;
278                         case 'mysqli':
279                                 if ($this->db->errno) {
280                                         $this->error = $this->db->error;
281                                         $this->errorno = $this->db->errno;
282                                 }
283                                 break;
284                         case 'mysql':
285                                 if (mysql_errno($this->db)) {
286                                         $this->error = mysql_error($this->db);
287                                         $this->errorno = mysql_errno($this->db);
288                                 }
289                                 break;
290                 }
291                 if (strlen($this->error)) {
292                         logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
293                 }
294
295                 if ($this->debug) {
296
297                         $mesg = '';
298
299                         if ($result === false) {
300                                 $mesg = 'false';
301                         } elseif ($result === true) {
302                                 $mesg = 'true';
303                         } else {
304                                 switch ($this->driver) {
305                                         case 'pdo':
306                                                 $mesg = $result->rowCount().' results'.EOL;
307                                                 break;
308                                         case 'mysqli':
309                                                 $mesg = $result->num_rows.' results'.EOL;
310                                                 break;
311                                         case 'mysql':
312                                                 $mesg = mysql_num_rows($result).' results'.EOL;
313                                                 break;
314                                 }
315                         }
316
317                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
318                                 . (($this->error) ? ' error: ' . $this->error : '')
319                                 . EOL;
320
321                         logger('dba: ' . $str );
322                 }
323
324                 /**
325                  * If dbfail.out exists, we will write any failed calls directly to it,
326                  * regardless of any logging that may or may nor be in effect.
327                  * These usually indicate SQL syntax errors that need to be resolved.
328                  */
329
330                 if ($result === false) {
331                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
332                         if (file_exists('dbfail.out')) {
333                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
334                         }
335                 }
336
337                 if (is_bool($result)) {
338                         return $result;
339                 }
340                 if ($onlyquery) {
341                         $this->result = $result;
342                         return true;
343                 }
344
345                 $r = array();
346                 switch ($this->driver) {
347                         case 'pdo':
348                                 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
349                                         $r[] = $x;
350                                 }
351                                 $result->closeCursor();
352                                 break;
353                         case 'mysqli':
354                                 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
355                                         $r[] = $x;
356                                 }
357                                 $result->free_result();
358                                 break;
359                         case 'mysql':
360                                 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
361                                         $r[] = $x;
362                                 }
363                                 mysql_free_result($result);
364                                 break;
365                 }
366
367                 // PDO doesn't return "true" on successful operations - like mysqli does
368                 // Emulate this behaviour by checking if the query returned data and had columns
369                 // This should be reliable enough
370                 if (($this->driver == 'pdo') && (count($r) == 0) && ($columns == 0)) {
371                         return true;
372                 }
373
374                 //$a->save_timestamp($stamp1, "database");
375
376                 if ($this->debug) {
377                         logger('dba: ' . printable(print_r($r, true)));
378                 }
379                 return($r);
380         }
381
382         public function dbg($dbg) {
383                 $this->debug = $dbg;
384         }
385
386         public function escape($str) {
387                 if ($this->db && $this->connected) {
388                         switch ($this->driver) {
389                                 case 'pdo':
390                                         return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
391                                 case 'mysqli':
392                                         return @$this->db->real_escape_string($str);
393                                 case 'mysql':
394                                         return @mysql_real_escape_string($str,$this->db);
395                         }
396                 }
397         }
398
399         function connected() {
400                 switch ($this->driver) {
401                         case 'pdo':
402                                 // Not sure if this really is working like expected
403                                 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
404                                 break;
405                         case 'mysqli':
406                                 $connected = $this->db->ping();
407                                 break;
408                         case 'mysql':
409                                 $connected = mysql_ping($this->db);
410                                 break;
411                 }
412                 return $connected;
413         }
414
415         function __destruct() {
416                 if ($this->db) {
417                         switch ($this->driver) {
418                                 case 'pdo':
419                                         $this->db = null;
420                                         break;
421                                 case 'mysqli':
422                                         $this->db->close();
423                                         break;
424                                 case 'mysql':
425                                         mysql_close($this->db);
426                                         break;
427                         }
428                 }
429         }
430
431         /**
432          * @brief Replaces ANY_VALUE() function by MIN() function,
433          *  if the database server does not support ANY_VALUE().
434          *
435          * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
436          * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
437          * A standard fall-back is to use MIN().
438          *
439          * @param string $sql An SQL string without the values
440          * @return string The input SQL string modified if necessary.
441          */
442         public function any_value_fallback($sql) {
443                 $server_info = $this->server_info();
444                 if (version_compare($server_info, '5.7.5', '<') ||
445                         (stripos($server_info, 'MariaDB') !== false)) {
446                         $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
447                 }
448                 return $sql;
449         }
450
451         /**
452          * @brief beautifies the query - useful for "SHOW PROCESSLIST"
453          *
454          * This is safe when we bind the parameters later.
455          * The parameter values aren't part of the SQL.
456          *
457          * @param string $sql An SQL string without the values
458          * @return string The input SQL string modified if necessary.
459          */
460         public function clean_query($sql) {
461                 $search = array("\t", "\n", "\r", "  ");
462                 $replace = array(' ', ' ', ' ', ' ');
463                 do {
464                         $oldsql = $sql;
465                         $sql = str_replace($search, $replace, $sql);
466                 } while ($oldsql != $sql);
467
468                 return $sql;
469         }
470
471
472         /**
473          * @brief Replaces the ? placeholders with the parameters in the $args array
474          *
475          * @param string $sql SQL query
476          * @param array $args The parameters that are to replace the ? placeholders
477          * @return string The replaced SQL query
478          */
479         static private function replace_parameters($sql, $args) {
480                 $offset = 0;
481                 foreach ($args AS $param => $value) {
482                         if (is_int($args[$param]) || is_float($args[$param])) {
483                                 $replace = intval($args[$param]);
484                         } else {
485                                 $replace = "'".self::$dbo->escape($args[$param])."'";
486                         }
487
488                         $pos = strpos($sql, '?', $offset);
489                         if ($pos !== false) {
490                                 $sql = substr_replace($sql, $replace, $pos, 1);
491                         }
492                         $offset = $pos + strlen($replace);
493                 }
494                 return $sql;
495         }
496
497         /**
498          * @brief Convert parameter array to an universal form
499          * @param array $args Parameter array
500          * @return array universalized parameter array
501          */
502         private static function getParam($args) {
503                 unset($args[0]);
504
505                 // When the second function parameter is an array then use this as the parameter array
506                 if ((count($args) > 0) && (is_array($args[1]))) {
507                         return $args[1];
508                 } else {
509                         return $args;
510                 }
511         }
512
513         /**
514          * @brief Executes a prepared statement that returns data
515          * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
516          * @param string $sql SQL statement
517          * @return object statement object
518          */
519         static public function p($sql) {
520                 $a = get_app();
521
522                 $stamp1 = microtime(true);
523
524                 $params = self::getParam(func_get_args());
525
526                 // Renumber the array keys to be sure that they fit
527                 $i = 0;
528                 $args = array();
529                 foreach ($params AS $param) {
530                         $args[++$i] = $param;
531                 }
532
533                 if (!self::$dbo || !self::$dbo->connected) {
534                         return false;
535                 }
536
537                 if (substr_count($sql, '?') != count($args)) {
538                         // Question: Should we continue or stop the query here?
539                         logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
540                 }
541
542                 $sql = self::$dbo->clean_query($sql);
543                 $sql = self::$dbo->any_value_fallback($sql);
544
545                 $orig_sql = $sql;
546
547                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
548                         $sql = "/*".$a->callstack()." */ ".$sql;
549                 }
550
551                 self::$dbo->error = '';
552                 self::$dbo->errorno = 0;
553                 self::$dbo->affected_rows = 0;
554
555                 // We have to make some things different if this function is called from "e"
556                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
557
558                 if (isset($trace[1])) {
559                         $called_from = $trace[1];
560                 } else {
561                         // We use just something that is defined to avoid warnings
562                         $called_from = $trace[0];
563                 }
564                 // We are having an own error logging in the function "e"
565                 $called_from_e = ($called_from['function'] == 'e');
566
567                 switch (self::$dbo->driver) {
568                         case 'pdo':
569                                 if (!$stmt = self::$dbo->db->prepare($sql)) {
570                                         $errorInfo = self::$dbo->db->errorInfo();
571                                         self::$dbo->error = $errorInfo[2];
572                                         self::$dbo->errorno = $errorInfo[1];
573                                         $retval = false;
574                                         break;
575                                 }
576
577                                 foreach ($args AS $param => $value) {
578                                         $stmt->bindParam($param, $args[$param]);
579                                 }
580
581                                 if (!$stmt->execute()) {
582                                         $errorInfo = $stmt->errorInfo();
583                                         self::$dbo->error = $errorInfo[2];
584                                         self::$dbo->errorno = $errorInfo[1];
585                                         $retval = false;
586                                 } else {
587                                         $retval = $stmt;
588                                         self::$dbo->affected_rows = $retval->rowCount();
589                                 }
590                                 break;
591                         case 'mysqli':
592                                 // There are SQL statements that cannot be executed with a prepared statement
593                                 $parts = explode(' ', $orig_sql);
594                                 $command = strtolower($parts[0]);
595                                 $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
596
597                                 // The fallback routine currently only works with statements that doesn't return values
598                                 if (!$can_be_prepared && $called_from_e) {
599                                         $retval = self::$dbo->db->query(self::replace_parameters($sql, $args));
600                                         if (self::$dbo->db->errno) {
601                                                 self::$dbo->error = self::$dbo->db->error;
602                                                 self::$dbo->errorno = self::$dbo->db->errno;
603                                                 $retval = false;
604                                         } else {
605                                                 if (isset($retval->num_rows)) {
606                                                         self::$dbo->affected_rows = $retval->num_rows;
607                                                 } else {
608                                                         self::$dbo->affected_rows = self::$dbo->db->affected_rows;
609                                                 }
610                                         }
611                                         break;
612                                 }
613
614                                 $stmt = self::$dbo->db->stmt_init();
615
616                                 if (!$stmt->prepare($sql)) {
617                                         self::$dbo->error = $stmt->error;
618                                         self::$dbo->errorno = $stmt->errno;
619                                         $retval = false;
620                                         break;
621                                 }
622
623                                 $params = '';
624                                 $values = array();
625                                 foreach ($args AS $param => $value) {
626                                         if (is_int($args[$param])) {
627                                                 $params .= 'i';
628                                         } elseif (is_float($args[$param])) {
629                                                 $params .= 'd';
630                                         } elseif (is_string($args[$param])) {
631                                                 $params .= 's';
632                                         } else {
633                                                 $params .= 'b';
634                                         }
635                                         $values[] = &$args[$param];
636                                 }
637
638                                 if (count($values) > 0) {
639                                         array_unshift($values, $params);
640                                         call_user_func_array(array($stmt, 'bind_param'), $values);
641                                 }
642
643                                 if (!$stmt->execute()) {
644                                         self::$dbo->error = self::$dbo->db->error;
645                                         self::$dbo->errorno = self::$dbo->db->errno;
646                                         $retval = false;
647                                 } else {
648                                         $stmt->store_result();
649                                         $retval = $stmt;
650                                         self::$dbo->affected_rows = $retval->affected_rows;
651                                 }
652                                 break;
653                         case 'mysql':
654                                 // For the old "mysql" functions we cannot use prepared statements
655                                 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
656                                 if (mysql_errno(self::$dbo->db)) {
657                                         self::$dbo->error = mysql_error(self::$dbo->db);
658                                         self::$dbo->errorno = mysql_errno(self::$dbo->db);
659                                 } else {
660                                         self::$dbo->affected_rows = mysql_affected_rows($retval);
661
662                                         // Due to missing mysql_* support this here wasn't tested at all
663                                         // See here: http://php.net/manual/en/function.mysql-num-rows.php
664                                         if (self::$dbo->affected_rows <= 0) {
665                                                 self::$dbo->affected_rows = mysql_num_rows($retval);
666                                         }
667                                 }
668                                 break;
669                 }
670
671                 // We are having an own error logging in the function "e"
672                 if ((self::$dbo->errorno != 0) && !$called_from_e) {
673                         // We have to preserve the error code, somewhere in the logging it get lost
674                         $error = self::$dbo->error;
675                         $errorno = self::$dbo->errorno;
676
677                         logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
678                                 $a->callstack(8)."\n".self::replace_parameters($sql, $params));
679
680                         self::$dbo->error = $error;
681                         self::$dbo->errorno = $errorno;
682                 }
683
684                 $a->save_timestamp($stamp1, 'database');
685
686                 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
687
688                         $stamp2 = microtime(true);
689                         $duration = (float)($stamp2 - $stamp1);
690
691                         if (($duration > $a->config["system"]["db_loglimit"])) {
692                                 $duration = round($duration, 3);
693                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
694
695                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
696                                                 basename($backtrace[1]["file"])."\t".
697                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
698                                                 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
699                         }
700                 }
701                 return $retval;
702         }
703
704         /**
705          * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
706          *
707          * @param string $sql SQL statement
708          * @return boolean Was the query successfull? False is returned only if an error occurred
709          */
710         static public function e($sql) {
711                 $a = get_app();
712
713                 $stamp = microtime(true);
714
715                 $params = self::getParam(func_get_args());
716
717                 // In a case of a deadlock we are repeating the query 20 times
718                 $timeout = 20;
719
720                 do {
721                         $stmt = self::p($sql, $params);
722
723                         if (is_bool($stmt)) {
724                                 $retval = $stmt;
725                         } elseif (is_object($stmt)) {
726                                 $retval = true;
727                         } else {
728                                 $retval = false;
729                         }
730
731                         self::close($stmt);
732
733                 } while ((self::$dbo->errorno == 1213) && (--$timeout > 0));
734
735                 if (self::$dbo->errorno != 0) {
736                         // We have to preserve the error code, somewhere in the logging it get lost
737                         $error = self::$dbo->error;
738                         $errorno = self::$dbo->errorno;
739
740                         logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
741                                 $a->callstack(8)."\n".self::replace_parameters($sql, $params));
742
743                         self::$dbo->error = $error;
744                         self::$dbo->errorno = $errorno;
745                 }
746
747                 $a->save_timestamp($stamp, "database_write");
748
749                 return $retval;
750         }
751
752         /**
753          * @brief Check if data exists
754          *
755          * @param string $table Table name
756          * @param array $condition array of fields for condition
757          *
758          * @return boolean Are there rows for that condition?
759          */
760         static public function exists($table, $condition) {
761                 if (empty($table)) {
762                         return false;
763                 }
764
765                 $fields = array();
766
767                 $array_element = each($condition);
768                 $array_key = $array_element['key'];
769                 if (!is_int($array_key)) {
770                         $fields = array($array_key);
771                 }
772
773                 $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
774
775                 if (is_bool($stmt)) {
776                         $retval = $stmt;
777                 } else {
778                         $retval = (self::num_rows($stmt) > 0);
779                 }
780
781                 self::close($stmt);
782
783                 return $retval;
784         }
785
786         /**
787          * @brief Fetches the first row
788          *
789          * @param string $sql SQL statement
790          * @return array first row of query
791          */
792         static public function fetch_first($sql) {
793                 $params = self::getParam(func_get_args());
794
795                 $stmt = self::p($sql, $params);
796
797                 if (is_bool($stmt)) {
798                         $retval = $stmt;
799                 } else {
800                         $retval = self::fetch($stmt);
801                 }
802
803                 self::close($stmt);
804
805                 return $retval;
806         }
807
808         /**
809          * @brief Returns the number of affected rows of the last statement
810          *
811          * @return int Number of rows
812          */
813         static public function affected_rows() {
814                 return self::$dbo->affected_rows;
815         }
816
817         /**
818          * @brief Returns the number of rows of a statement
819          *
820          * @param object Statement object
821          * @return int Number of rows
822          */
823         static public function num_rows($stmt) {
824                 if (!is_object($stmt)) {
825                         return 0;
826                 }
827                 switch (self::$dbo->driver) {
828                         case 'pdo':
829                                 return $stmt->rowCount();
830                         case 'mysqli':
831                                 return $stmt->num_rows;
832                         case 'mysql':
833                                 return mysql_num_rows($stmt);
834                 }
835                 return 0;
836         }
837
838         /**
839          * @brief Fetch a single row
840          *
841          * @param object $stmt statement object
842          * @return array current row
843          */
844         static public function fetch($stmt) {
845                 if (!is_object($stmt)) {
846                         return false;
847                 }
848
849                 switch (self::$dbo->driver) {
850                         case 'pdo':
851                                 return $stmt->fetch(PDO::FETCH_ASSOC);
852                         case 'mysqli':
853                                 // This code works, but is slow
854
855                                 // Bind the result to a result array
856                                 $cols = array();
857
858                                 $cols_num = array();
859                                 for ($x = 0; $x < $stmt->field_count; $x++) {
860                                         $cols[] = &$cols_num[$x];
861                                 }
862
863                                 call_user_func_array(array($stmt, 'bind_result'), $cols);
864
865                                 if (!$stmt->fetch()) {
866                                         return false;
867                                 }
868
869                                 // The slow part:
870                                 // We need to get the field names for the array keys
871                                 // It seems that there is no better way to do this.
872                                 $result = $stmt->result_metadata();
873                                 $fields = $result->fetch_fields();
874
875                                 $columns = array();
876                                 foreach ($cols_num AS $param => $col) {
877                                         $columns[$fields[$param]->name] = $col;
878                                 }
879                                 return $columns;
880                         case 'mysql':
881                                 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
882                 }
883         }
884
885         /**
886          * @brief Insert a row into a table
887          *
888          * @param string $table Table name
889          * @param array $param parameter array
890          * @param bool $on_duplicate_update Do an update on a duplicate entry
891          *
892          * @return boolean was the insert successfull?
893          */
894         static public function insert($table, $param, $on_duplicate_update = false) {
895                 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
896                         substr(str_repeat("?, ", count($param)), 0, -2).")";
897
898                 if ($on_duplicate_update) {
899                         $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
900
901                         $values = array_values($param);
902                         $param = array_merge_recursive($values, $values);
903                 }
904
905                 return self::e($sql, $param);
906         }
907
908         /**
909          * @brief Fetch the id of the last insert command
910          *
911          * @return integer Last inserted id
912          */
913         function lastInsertId() {
914                 switch (self::$dbo->driver) {
915                         case 'pdo':
916                                 $id = self::$dbo->db->lastInsertId();
917                                 break;
918                         case 'mysqli':
919                                 $id = self::$dbo->db->insert_id;
920                                 break;
921                         case 'mysql':
922                                 $id = mysql_insert_id(self::$dbo);
923                                 break;
924                 }
925                 return $id;
926         }
927
928         /**
929          * @brief Locks a table for exclusive write access
930          *
931          * This function can be extended in the future to accept a table array as well.
932          *
933          * @param string $table Table name
934          *
935          * @return boolean was the lock successful?
936          */
937         static public function lock($table) {
938                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
939                 self::e("SET autocommit=0");
940                 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
941                 if (!$success) {
942                         self::e("SET autocommit=1");
943                 } else {
944                         self::$in_transaction = true;
945                 }
946                 return $success;
947         }
948
949         /**
950          * @brief Unlocks all locked tables
951          *
952          * @return boolean was the unlock successful?
953          */
954         static public function unlock() {
955                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
956                 self::e("COMMIT");
957                 $success = self::e("UNLOCK TABLES");
958                 self::e("SET autocommit=1");
959                 self::$in_transaction = false;
960                 return $success;
961         }
962
963         /**
964          * @brief Starts a transaction
965          *
966          * @return boolean Was the command executed successfully?
967          */
968         static public function transaction() {
969                 if (!self::e('COMMIT')) {
970                         return false;
971                 }
972                 if (!self::e('START TRANSACTION')) {
973                         return false;
974                 }
975                 self::$in_transaction = true;
976                 return true;
977         }
978
979         /**
980          * @brief Does a commit
981          *
982          * @return boolean Was the command executed successfully?
983          */
984         static public function commit() {
985                 if (!self::e('COMMIT')) {
986                         return false;
987                 }
988                 self::$in_transaction = false;
989                 return true;
990         }
991
992         /**
993          * @brief Does a rollback
994          *
995          * @return boolean Was the command executed successfully?
996          */
997         static public function rollback() {
998                 if (!self::e('ROLLBACK')) {
999                         return false;
1000                 }
1001                 self::$in_transaction = false;
1002                 return true;
1003         }
1004
1005         /**
1006          * @brief Build the array with the table relations
1007          *
1008          * The array is build from the database definitions in dbstructure.php
1009          *
1010          * This process must only be started once, since the value is cached.
1011          */
1012         static private function build_relation_data() {
1013                 $definition = db_definition();
1014
1015                 foreach ($definition AS $table => $structure) {
1016                         foreach ($structure['fields'] AS $field => $field_struct) {
1017                                 if (isset($field_struct['relation'])) {
1018                                         foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1019                                                 self::$relation[$rel_table][$rel_field][$table][] = $field;
1020                                         }
1021                                 }
1022                         }
1023                 }
1024         }
1025
1026         /**
1027          * @brief Delete a row from a table
1028          *
1029          * @param string $table Table name
1030          * @param array $param parameter array
1031          * @param boolean $in_process Internal use: Only do a commit after the last delete
1032          * @param array $callstack Internal use: prevent endless loops
1033          *
1034          * @return boolean|array was the delete successfull? When $in_process is set: deletion data
1035          */
1036         static public function delete($table, $param, $in_process = false, &$callstack = array()) {
1037
1038                 $commands = array();
1039
1040                 // Create a key for the loop prevention
1041                 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
1042
1043                 // We quit when this key already exists in the callstack.
1044                 if (isset($callstack[$key])) {
1045                         return $commands;
1046                 }
1047
1048                 $callstack[$key] = true;
1049
1050                 $table = self::$dbo->escape($table);
1051
1052                 $commands[$key] = array('table' => $table, 'param' => $param);
1053
1054                 // To speed up the whole process we cache the table relations
1055                 if (count(self::$relation) == 0) {
1056                         self::build_relation_data();
1057                 }
1058
1059                 // Is there a relation entry for the table?
1060                 if (isset(self::$relation[$table])) {
1061                         // We only allow a simple "one field" relation.
1062                         $field = array_keys(self::$relation[$table])[0];
1063                         $rel_def = array_values(self::$relation[$table])[0];
1064
1065                         // Create a key for preventing double queries
1066                         $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
1067
1068                         // When the search field is the relation field, we don't need to fetch the rows
1069                         // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1070                         if ((count($param) == 1) && ($field == array_keys($param)[0])) {
1071                                 foreach ($rel_def AS $rel_table => $rel_fields) {
1072                                         foreach ($rel_fields AS $rel_field) {
1073                                                 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
1074                                                 $commands = array_merge($commands, $retval);
1075                                         }
1076                                 }
1077                         // We quit when this key already exists in the callstack.
1078                         } elseif (!isset($callstack[$qkey])) {
1079
1080                                 $callstack[$qkey] = true;
1081
1082                                 // Fetch all rows that are to be deleted
1083                                 $data = self::select($table, array($field), $param);
1084
1085                                 while ($row = self::fetch($data)) {
1086                                         // Now we accumulate the delete commands
1087                                         $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
1088                                         $commands = array_merge($commands, $retval);
1089                                 }
1090
1091                                 self::close($data);
1092
1093                                 // Since we had split the delete command we don't need the original command anymore
1094                                 unset($commands[$key]);
1095                         }
1096                 }
1097
1098                 if (!$in_process) {
1099                         // Now we finalize the process
1100                         $do_transaction = !self::$in_transaction;
1101
1102                         if ($do_transaction) {
1103                                 self::transaction();
1104                         }
1105
1106                         $compacted = array();
1107                         $counter = array();
1108
1109                         foreach ($commands AS $command) {
1110                                 $condition = $command['param'];
1111                                 $array_element = each($condition);
1112                                 $array_key = $array_element['key'];
1113                                 if (is_int($array_key)) {
1114                                         $condition_string = " WHERE ".array_shift($condition);
1115                                 } else {
1116                                         $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1117                                 }
1118
1119                                 if ((count($command['param']) > 1) || is_int($array_key)) {
1120                                         $sql = "DELETE FROM `".$command['table']."`".$condition_string;
1121                                         logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
1122
1123                                         if (!self::e($sql, $condition)) {
1124                                                 if ($do_transaction) {
1125                                                         self::rollback();
1126                                                 }
1127                                                 return false;
1128                                         }
1129                                 } else {
1130                                         $key_table = $command['table'];
1131                                         $key_param = array_keys($command['param'])[0];
1132                                         $value = array_values($command['param'])[0];
1133
1134                                         // Split the SQL queries in chunks of 100 values
1135                                         // We do the $i stuff here to make the code better readable
1136                                         $i = $counter[$key_table][$key_param];
1137                                         if (count($compacted[$key_table][$key_param][$i]) > 100) {
1138                                                 ++$i;
1139                                         }
1140
1141                                         $compacted[$key_table][$key_param][$i][$value] = $value;
1142                                         $counter[$key_table][$key_param] = $i;
1143                                 }
1144                         }
1145                         foreach ($compacted AS $table => $values) {
1146                                 foreach ($values AS $field => $field_value_list) {
1147                                         foreach ($field_value_list AS $field_values) {
1148                                                 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1149                                                         substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1150
1151                                                 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
1152
1153                                                 if (!self::e($sql, $field_values)) {
1154                                                         if ($do_transaction) {
1155                                                                 self::rollback();
1156                                                         }
1157                                                         return false;
1158                                                 }
1159                                         }
1160                                 }
1161                         }
1162                         if ($do_transaction) {
1163                                 self::commit();
1164                         }
1165                         return true;
1166                 }
1167
1168                 return $commands;
1169         }
1170
1171         /**
1172          * @brief Updates rows
1173          *
1174          * Updates rows in the database. When $old_fields is set to an array,
1175          * the system will only do an update if the fields in that array changed.
1176          *
1177          * Attention:
1178          * Only the values in $old_fields are compared.
1179          * This is an intentional behaviour.
1180          *
1181          * Example:
1182          * We include the timestamp field in $fields but not in $old_fields.
1183          * Then the row will only get the new timestamp when the other fields had changed.
1184          *
1185          * When $old_fields is set to a boolean value the system will do this compare itself.
1186          * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1187          *
1188          * Attention:
1189          * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1190          * When you set $old_fields to "true" then $fields must contain all relevant fields!
1191          *
1192          * @param string $table Table name
1193          * @param array $fields contains the fields that are updated
1194          * @param array $condition condition array with the key values
1195          * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1196          *
1197          * @return boolean was the update successfull?
1198          */
1199         static public function update($table, $fields, $condition, $old_fields = array()) {
1200
1201                 $table = self::$dbo->escape($table);
1202
1203                 if (count($condition) > 0) {
1204                         $array_element = each($condition);
1205                         $array_key = $array_element['key'];
1206                         if (is_int($array_key)) {
1207                                 $condition_string = " WHERE ".array_shift($condition);
1208                         } else {
1209                                 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1210                         }
1211                 } else {
1212                         $condition_string = "";
1213                 }
1214
1215                 if (is_bool($old_fields)) {
1216                         $do_insert = $old_fields;
1217
1218                         $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1219
1220                         if (is_bool($old_fields)) {
1221                                 if ($do_insert) {
1222                                         $values = array_merge($condition, $fields);
1223                                         return self::insert($table, $values, $do_insert);
1224                                 }
1225                                 $old_fields = array();
1226                         }
1227                 }
1228
1229                 $do_update = (count($old_fields) == 0);
1230
1231                 foreach ($old_fields AS $fieldname => $content) {
1232                         if (isset($fields[$fieldname])) {
1233                                 if ($fields[$fieldname] == $content) {
1234                                         unset($fields[$fieldname]);
1235                                 } else {
1236                                         $do_update = true;
1237                                 }
1238                         }
1239                 }
1240
1241                 if (!$do_update || (count($fields) == 0)) {
1242                         return true;
1243                 }
1244
1245                 $sql = "UPDATE `".$table."` SET `".
1246                         implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1247
1248                 $params1 = array_values($fields);
1249                 $params2 = array_values($condition);
1250                 $params = array_merge_recursive($params1, $params2);
1251
1252                 return self::e($sql, $params);
1253         }
1254
1255         /**
1256          * @brief Select rows from a table
1257          *
1258          * @param string $table Table name
1259          * @param array $fields array of selected fields
1260          * @param array $condition array of fields for condition
1261          * @param array $params array of several parameters
1262          *
1263          * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1264          *
1265          * Example:
1266          * $table = "item";
1267          * $fields = array("id", "uri", "uid", "network");
1268          * $condition = array("uid" => 1, "network" => 'dspr');
1269          * $params = array("order" => array("id", "received" => true), "limit" => 1);
1270          *
1271          * $data = dba::select($table, $fields, $condition, $params);
1272          */
1273         static public function select($table, $fields = array(), $condition = array(), $params = array()) {
1274                 if ($table == '') {
1275                         return false;
1276                 }
1277
1278                 if (count($fields) > 0) {
1279                         $select_fields = "`".implode("`, `", array_values($fields))."`";
1280                 } else {
1281                         $select_fields = "*";
1282                 }
1283
1284                 if (count($condition) > 0) {
1285                         $array_element = each($condition);
1286                         $array_key = $array_element['key'];
1287                         if (is_int($array_key)) {
1288                                 $condition_string = " WHERE ".array_shift($condition);
1289                         } else {
1290                                 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1291                         }
1292                 } else {
1293                         $condition_string = "";
1294                 }
1295
1296                 $param_string = '';
1297                 $single_row = false;
1298
1299                 if (isset($params['order'])) {
1300                         $param_string .= " ORDER BY ";
1301                         foreach ($params['order'] AS $fields => $order) {
1302                                 if (!is_int($fields)) {
1303                                         $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1304                                 } else {
1305                                         $param_string .= "`".$order."`, ";
1306                                 }
1307                         }
1308                         $param_string = substr($param_string, 0, -2);
1309                 }
1310
1311                 if (isset($params['limit']) && is_int($params['limit'])) {
1312                         $param_string .= " LIMIT ".$params['limit'];
1313                         $single_row = ($params['limit'] == 1);
1314                 }
1315
1316                 if (isset($params['only_query']) && $params['only_query']) {
1317                         $single_row = !$params['only_query'];
1318                 }
1319
1320                 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1321
1322                 $result = self::p($sql, $condition);
1323
1324                 if (is_bool($result) || !$single_row) {
1325                         return $result;
1326                 } else {
1327                         $row = self::fetch($result);
1328                         self::close($result);
1329                         return $row;
1330                 }
1331         }
1332
1333
1334         /**
1335          * @brief Fills an array with data from a query
1336          *
1337          * @param object $stmt statement object
1338          * @return array Data array
1339          */
1340         static public function inArray($stmt, $do_close = true) {
1341                 if (is_bool($stmt)) {
1342                         return $stmt;
1343                 }
1344
1345                 $data = array();
1346                 while ($row = self::fetch($stmt)) {
1347                         $data[] = $row;
1348                 }
1349                 if ($do_close) {
1350                         self::close($stmt);
1351                 }
1352                 return $data;
1353         }
1354
1355         /**
1356          * @brief Closes the current statement
1357          *
1358          * @param object $stmt statement object
1359          * @return boolean was the close successfull?
1360          */
1361         static public function close($stmt) {
1362                 if (!is_object($stmt)) {
1363                         return false;
1364                 }
1365
1366                 switch (self::$dbo->driver) {
1367                         case 'pdo':
1368                                 return $stmt->closeCursor();
1369                         case 'mysqli':
1370                                 return $stmt->free_result();
1371                                 return $stmt->close();
1372                         case 'mysql':
1373                                 return mysql_free_result($stmt);
1374                 }
1375         }
1376 }
1377
1378 function printable($s) {
1379         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
1380         $s = str_replace("\x00",'.',$s);
1381         if (x($_SERVER,'SERVER_NAME')) {
1382                 $s = escape_tags($s);
1383         }
1384         return $s;
1385 }
1386
1387 // Procedural functions
1388 function dbg($state) {
1389         global $db;
1390
1391         if ($db) {
1392                 $db->dbg($state);
1393         }
1394 }
1395
1396 function dbesc($str) {
1397         global $db;
1398
1399         if ($db && $db->connected) {
1400                 return($db->escape($str));
1401         } else {
1402                 return(str_replace("'","\\'",$str));
1403         }
1404 }
1405
1406 // Function: q($sql,$args);
1407 // Description: execute SQL query with printf style args.
1408 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
1409 //                   'user', 1);
1410 function q($sql) {
1411         global $db;
1412         $args = func_get_args();
1413         unset($args[0]);
1414
1415         if ($db && $db->connected) {
1416                 $sql = $db->clean_query($sql);
1417                 $sql = $db->any_value_fallback($sql);
1418                 $stmt = @vsprintf($sql,$args); // Disabled warnings
1419                 //logger("dba: q: $stmt", LOGGER_ALL);
1420                 if ($stmt === false)
1421                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1422
1423                 $db->log_index($stmt);
1424
1425                 return $db->q($stmt);
1426         }
1427
1428         /**
1429          *
1430          * This will happen occasionally trying to store the
1431          * session data after abnormal program termination
1432          *
1433          */
1434         logger('dba: no database: ' . print_r($args,true));
1435         return false;
1436 }
1437
1438 /**
1439  * @brief Performs a query with "dirty reads"
1440  *
1441  * By doing dirty reads (reading uncommitted data) no locks are performed
1442  * This function can be used to fetch data that doesn't need to be reliable.
1443  *
1444  * @param $args Query parameters (1 to N parameters of different types)
1445  * @return array Query array
1446  */
1447 function qu($sql) {
1448         global $db;
1449
1450         $args = func_get_args();
1451         unset($args[0]);
1452
1453         if ($db && $db->connected) {
1454                 $sql = $db->clean_query($sql);
1455                 $sql = $db->any_value_fallback($sql);
1456                 $stmt = @vsprintf($sql,$args); // Disabled warnings
1457                 if ($stmt === false)
1458                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1459
1460                 $db->log_index($stmt);
1461
1462                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
1463                 $retval = $db->q($stmt);
1464                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
1465                 return $retval;
1466         }
1467
1468         /**
1469          *
1470          * This will happen occasionally trying to store the
1471          * session data after abnormal program termination
1472          *
1473          */
1474         logger('dba: no database: ' . print_r($args,true));
1475         return false;
1476 }
1477
1478 /**
1479  *
1480  * Raw db query, no arguments
1481  *
1482  */
1483 function dbq($sql) {
1484         global $db;
1485
1486         if ($db && $db->connected) {
1487                 $ret = $db->q($sql);
1488         } else {
1489                 $ret = false;
1490         }
1491         return $ret;
1492 }
1493
1494 // Caller is responsible for ensuring that any integer arguments to
1495 // dbesc_array are actually integers and not malformed strings containing
1496 // SQL injection vectors. All integer array elements should be specifically
1497 // cast to int to avoid trouble.
1498 function dbesc_array_cb(&$item, $key) {
1499         if (is_string($item))
1500                 $item = dbesc($item);
1501 }
1502
1503 function dbesc_array(&$arr) {
1504         if (is_array($arr) && count($arr)) {
1505                 array_walk($arr,'dbesc_array_cb');
1506         }
1507 }
1508
1509 function dba_timer() {
1510         return microtime(true);
1511 }