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