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