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