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