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