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