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