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