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