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