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