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