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