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