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