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