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