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