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