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