]> git.mxchange.org Git - friendica.git/blob - src/Database/Database.php
Fetch a given number of posts
[friendica.git] / src / Database / Database.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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                 $stamp1 = microtime(true);
472
473                 $params = DBA::getParam(func_get_args());
474
475                 // Renumber the array keys to be sure that they fit
476                 $i    = 0;
477                 $args = [];
478                 foreach ($params AS $param) {
479                         // Avoid problems with some MySQL servers and boolean values. See issue #3645
480                         if (is_bool($param)) {
481                                 $param = (int)$param;
482                         }
483                         $args[++$i] = $param;
484                 }
485
486                 if (!$this->connected) {
487                         return false;
488                 }
489
490                 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
491                         // Question: Should we continue or stop the query here?
492                         $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
493                 }
494
495                 $sql = DBA::cleanQuery($sql);
496                 $sql = $this->anyValueFallback($sql);
497
498                 $orig_sql = $sql;
499
500                 if ($this->configCache->get('system', 'db_callstack') !== null) {
501                         $sql = "/*" . System::callstack() . " */ " . $sql;
502                 }
503
504                 $is_error            = false;
505                 $this->error         = '';
506                 $this->errorno       = 0;
507                 $this->affected_rows = 0;
508
509                 // We have to make some things different if this function is called from "e"
510                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
511
512                 if (isset($trace[1])) {
513                         $called_from = $trace[1];
514                 } else {
515                         // We use just something that is defined to avoid warnings
516                         $called_from = $trace[0];
517                 }
518                 // We are having an own error logging in the function "e"
519                 $called_from_e = ($called_from['function'] == 'e');
520
521                 if (!isset($this->connection)) {
522                         throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
523                 }
524
525                 switch ($this->driver) {
526                         case self::PDO:
527                                 // If there are no arguments we use "query"
528                                 if (count($args) == 0) {
529                                         if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
530                                                 $errorInfo     = $this->connection->errorInfo();
531                                                 $this->error   = $errorInfo[2];
532                                                 $this->errorno = $errorInfo[1];
533                                                 $retval        = false;
534                                                 $is_error      = true;
535                                                 break;
536                                         }
537                                         $this->affected_rows = $retval->rowCount();
538                                         break;
539                                 }
540
541                                 /** @var $stmt mysqli_stmt|PDOStatement */
542                                 if (!$stmt = $this->connection->prepare($sql)) {
543                                         $errorInfo     = $this->connection->errorInfo();
544                                         $this->error   = $errorInfo[2];
545                                         $this->errorno = $errorInfo[1];
546                                         $retval        = false;
547                                         $is_error      = true;
548                                         break;
549                                 }
550
551                                 foreach ($args AS $param => $value) {
552                                         if (is_int($args[$param])) {
553                                                 $data_type = PDO::PARAM_INT;
554                                         } else {
555                                                 $data_type = PDO::PARAM_STR;
556                                         }
557                                         $stmt->bindParam($param, $args[$param], $data_type);
558                                 }
559
560                                 if (!$stmt->execute()) {
561                                         $errorInfo     = $stmt->errorInfo();
562                                         $this->error   = $errorInfo[2];
563                                         $this->errorno = $errorInfo[1];
564                                         $retval        = false;
565                                         $is_error      = true;
566                                 } else {
567                                         $retval              = $stmt;
568                                         $this->affected_rows = $retval->rowCount();
569                                 }
570                                 break;
571                         case self::MYSQLI:
572                                 // There are SQL statements that cannot be executed with a prepared statement
573                                 $parts           = explode(' ', $orig_sql);
574                                 $command         = strtolower($parts[0]);
575                                 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
576
577                                 // The fallback routine is called as well when there are no arguments
578                                 if (!$can_be_prepared || (count($args) == 0)) {
579                                         $retval = $this->connection->query($this->replaceParameters($sql, $args));
580                                         if ($this->connection->errno) {
581                                                 $this->error   = $this->connection->error;
582                                                 $this->errorno = $this->connection->errno;
583                                                 $retval        = false;
584                                                 $is_error      = true;
585                                         } else {
586                                                 if (isset($retval->num_rows)) {
587                                                         $this->affected_rows = $retval->num_rows;
588                                                 } else {
589                                                         $this->affected_rows = $this->connection->affected_rows;
590                                                 }
591                                         }
592                                         break;
593                                 }
594
595                                 $stmt = $this->connection->stmt_init();
596
597                                 if (!$stmt->prepare($sql)) {
598                                         $this->error   = $stmt->error;
599                                         $this->errorno = $stmt->errno;
600                                         $retval        = false;
601                                         $is_error      = true;
602                                         break;
603                                 }
604
605                                 $param_types = '';
606                                 $values      = [];
607                                 foreach ($args AS $param => $value) {
608                                         if (is_int($args[$param])) {
609                                                 $param_types .= 'i';
610                                         } elseif (is_float($args[$param])) {
611                                                 $param_types .= 'd';
612                                         } elseif (is_string($args[$param])) {
613                                                 $param_types .= 's';
614                                         } else {
615                                                 $param_types .= 'b';
616                                         }
617                                         $values[] = &$args[$param];
618                                 }
619
620                                 if (count($values) > 0) {
621                                         array_unshift($values, $param_types);
622                                         call_user_func_array([$stmt, 'bind_param'], $values);
623                                 }
624
625                                 if (!$stmt->execute()) {
626                                         $this->error   = $this->connection->error;
627                                         $this->errorno = $this->connection->errno;
628                                         $retval        = false;
629                                         $is_error      = true;
630                                 } else {
631                                         $stmt->store_result();
632                                         $retval              = $stmt;
633                                         $this->affected_rows = $retval->affected_rows;
634                                 }
635                                 break;
636                 }
637
638                 // See issue https://github.com/friendica/friendica/issues/8572
639                 // Ensure that we always get an error message on an error.
640                 if ($is_error && empty($this->errorno)) {
641                         $this->errorno = -1;
642                 }
643
644                 if ($is_error && empty($this->error)) {
645                         $this->error = 'Unknown database error';
646                 }
647
648                 // We are having an own error logging in the function "e"
649                 if (($this->errorno != 0) && !$called_from_e) {
650                         // We have to preserve the error code, somewhere in the logging it get lost
651                         $error   = $this->error;
652                         $errorno = $this->errorno;
653
654                         if ($this->testmode) {
655                                 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $args));
656                         }
657
658                         $this->logger->error('DB Error', [
659                                 'code'      => $errorno,
660                                 'error'     => $error,
661                                 'callstack' => System::callstack(8),
662                                 'params'    => $this->replaceParameters($sql, $args),
663                         ]);
664
665                         // On a lost connection we try to reconnect - but only once.
666                         if ($errorno == 2006) {
667                                 if ($this->in_retrial || !$this->reconnect()) {
668                                         // It doesn't make sense to continue when the database connection was lost
669                                         if ($this->in_retrial) {
670                                                 $this->logger->notice('Giving up retrial because of database error', [
671                                                         'code'  => $errorno,
672                                                         'error' => $error,
673                                                 ]);
674                                         } else {
675                                                 $this->logger->notice('Couldn\'t reconnect after database error', [
676                                                         'code'  => $errorno,
677                                                         'error' => $error,
678                                                 ]);
679                                         }
680                                         exit(1);
681                                 } else {
682                                         // We try it again
683                                         $this->logger->notice('Reconnected after database error', [
684                                                 'code'  => $errorno,
685                                                 'error' => $error,
686                                         ]);
687                                         $this->in_retrial = true;
688                                         $ret              = $this->p($sql, $args);
689                                         $this->in_retrial = false;
690                                         return $ret;
691                                 }
692                         }
693
694                         $this->error   = $error;
695                         $this->errorno = $errorno;
696                 }
697
698                 $this->profiler->saveTimestamp($stamp1, 'database');
699
700                 if ($this->configCache->get('system', 'db_log')) {
701                         $stamp2   = microtime(true);
702                         $duration = (float)($stamp2 - $stamp1);
703
704                         if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
705                                 $duration  = round($duration, 3);
706                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
707
708                                 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
709                                                                                                 basename($backtrace[1]["file"]) . "\t" .
710                                                                                                 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
711                                                                                                 substr($this->replaceParameters($sql, $args), 0, 4000) . "\n", FILE_APPEND);
712                         }
713                 }
714                 return $retval;
715         }
716
717         /**
718          * Executes a prepared statement like UPDATE or INSERT that doesn't return data
719          *
720          * Please use DBA::delete, DBA::insert, DBA::update, ... instead
721          *
722          * @param string $sql SQL statement
723          *
724          * @return boolean Was the query successfull? False is returned only if an error occurred
725          * @throws \Exception
726          */
727         public function e($sql)
728         {
729
730                 $stamp = microtime(true);
731
732                 $params = DBA::getParam(func_get_args());
733
734                 // In a case of a deadlock we are repeating the query 20 times
735                 $timeout = 20;
736
737                 do {
738                         $stmt = $this->p($sql, $params);
739
740                         if (is_bool($stmt)) {
741                                 $retval = $stmt;
742                         } elseif (is_object($stmt)) {
743                                 $retval = true;
744                         } else {
745                                 $retval = false;
746                         }
747
748                         $this->close($stmt);
749
750                 } while (($this->errorno == 1213) && (--$timeout > 0));
751
752                 if ($this->errorno != 0) {
753                         // We have to preserve the error code, somewhere in the logging it get lost
754                         $error   = $this->error;
755                         $errorno = $this->errorno;
756
757                         if ($this->testmode) {
758                                 throw new DatabaseException($error, $errorno, $this->replaceParameters($sql, $params));
759                         }
760
761                         $this->logger->error('DB Error', [
762                                 'code'      => $errorno,
763                                 'error'     => $error,
764                                 'callstack' => System::callstack(8),
765                                 'params'    => $this->replaceParameters($sql, $params),
766                         ]);
767
768                         // On a lost connection we simply quit.
769                         // A reconnect like in $this->p could be dangerous with modifications
770                         if ($errorno == 2006) {
771                                 $this->logger->notice('Giving up because of database error', [
772                                         'code'  => $errorno,
773                                         'error' => $error,
774                                 ]);
775                                 exit(1);
776                         }
777
778                         $this->error   = $error;
779                         $this->errorno = $errorno;
780                 }
781
782                 $this->profiler->saveTimestamp($stamp, "database_write");
783
784                 return $retval;
785         }
786
787         /**
788          * Check if data exists
789          *
790          * @param string|array $table     Table name or array [schema => table]
791          * @param array        $condition array of fields for condition
792          *
793          * @return boolean Are there rows for that condition?
794          * @throws \Exception
795          */
796         public function exists($table, $condition)
797         {
798                 if (empty($table)) {
799                         return false;
800                 }
801
802                 $fields = [];
803
804                 if (empty($condition)) {
805                         return DBStructure::existsTable($table);
806                 }
807
808                 reset($condition);
809                 $first_key = key($condition);
810                 if (!is_int($first_key)) {
811                         $fields = [$first_key];
812                 }
813
814                 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
815
816                 if (is_bool($stmt)) {
817                         $retval = $stmt;
818                 } else {
819                         $retval = ($this->numRows($stmt) > 0);
820                 }
821
822                 $this->close($stmt);
823
824                 return $retval;
825         }
826
827         /**
828          * Fetches the first row
829          *
830          * Please use DBA::selectFirst or DBA::exists whenever this is possible.
831          *
832          * Fetches the first row
833          *
834          * @param string $sql SQL statement
835          *
836          * @return array first row of query
837          * @throws \Exception
838          */
839         public function fetchFirst($sql)
840         {
841                 $params = DBA::getParam(func_get_args());
842
843                 $stmt = $this->p($sql, $params);
844
845                 if (is_bool($stmt)) {
846                         $retval = $stmt;
847                 } else {
848                         $retval = $this->fetch($stmt);
849                 }
850
851                 $this->close($stmt);
852
853                 return $retval;
854         }
855
856         /**
857          * Returns the number of affected rows of the last statement
858          *
859          * @return int Number of rows
860          */
861         public function affectedRows()
862         {
863                 return $this->affected_rows;
864         }
865
866         /**
867          * Returns the number of columns of a statement
868          *
869          * @param object Statement object
870          *
871          * @return int Number of columns
872          */
873         public function columnCount($stmt)
874         {
875                 if (!is_object($stmt)) {
876                         return 0;
877                 }
878                 switch ($this->driver) {
879                         case self::PDO:
880                                 return $stmt->columnCount();
881                         case self::MYSQLI:
882                                 return $stmt->field_count;
883                 }
884                 return 0;
885         }
886
887         /**
888          * Returns the number of rows of a statement
889          *
890          * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
891          *
892          * @return int Number of rows
893          */
894         public function numRows($stmt)
895         {
896                 if (!is_object($stmt)) {
897                         return 0;
898                 }
899                 switch ($this->driver) {
900                         case self::PDO:
901                                 return $stmt->rowCount();
902                         case self::MYSQLI:
903                                 return $stmt->num_rows;
904                 }
905                 return 0;
906         }
907
908         /**
909          * Fetch a single row
910          *
911          * @param PDOStatement|mysqli_stmt $stmt statement object
912          *
913          * @return array|false current row
914          */
915         public function fetch($stmt)
916         {
917                 $stamp1 = microtime(true);
918
919                 $columns = [];
920
921                 if (!is_object($stmt)) {
922                         return false;
923                 }
924
925                 switch ($this->driver) {
926                         case self::PDO:
927                                 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
928                                 if (!empty($stmt->table) && is_array($columns)) {
929                                         $columns = $this->castFields($stmt->table, $columns);
930                                 }
931                                 break;
932                         case self::MYSQLI:
933                                 if (get_class($stmt) == 'mysqli_result') {
934                                         $columns = $stmt->fetch_assoc() ?? false;
935                                         break;
936                                 }
937
938                                 // This code works, but is slow
939
940                                 // Bind the result to a result array
941                                 $cols = [];
942
943                                 $cols_num = [];
944                                 for ($x = 0; $x < $stmt->field_count; $x++) {
945                                         $cols[] = &$cols_num[$x];
946                                 }
947
948                                 call_user_func_array([$stmt, 'bind_result'], $cols);
949
950                                 if (!$stmt->fetch()) {
951                                         return false;
952                                 }
953
954                                 // The slow part:
955                                 // We need to get the field names for the array keys
956                                 // It seems that there is no better way to do this.
957                                 $result = $stmt->result_metadata();
958                                 $fields = $result->fetch_fields();
959
960                                 foreach ($cols_num AS $param => $col) {
961                                         $columns[$fields[$param]->name] = $col;
962                                 }
963                 }
964
965                 $this->profiler->saveTimestamp($stamp1, 'database');
966
967                 return $columns;
968         }
969
970         /**
971          * Insert a row into a table
972          *
973          * @param string|array $table          Table name or array [schema => table]
974          * @param array        $param          parameter array
975          * @param int          $duplicate_mode What to do on a duplicated entry
976          *
977          * @return boolean was the insert successful?
978          * @throws \Exception
979          */
980         public function insert($table, array $param, int $duplicate_mode = self::INSERT_DEFAULT)
981         {
982                 if (empty($table) || empty($param)) {
983                         $this->logger->info('Table and fields have to be set');
984                         return false;
985                 }
986
987                 $param = $this->castFields($table, $param);
988
989                 $table_string = DBA::buildTableString($table);
990
991                 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
992
993                 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
994
995                 $sql = "INSERT ";
996
997                 if ($duplicate_mode == self::INSERT_IGNORE) {
998                         $sql .= "IGNORE ";
999                 }
1000
1001                 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1002
1003                 if ($duplicate_mode == self::INSERT_UPDATE) {
1004                         $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1005
1006                         $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1007
1008                         $values = array_values($param);
1009                         $param  = array_merge_recursive($values, $values);
1010                 }
1011
1012                 $result = $this->e($sql, $param);
1013                 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1014                         return $result;
1015                 }
1016
1017                 return $this->affectedRows() != 0;
1018         }
1019
1020         /**
1021          * Inserts a row with the provided data in the provided table.
1022          * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1023          *
1024          * @param string|array $table Table name or array [schema => table]
1025          * @param array        $param parameter array
1026          *
1027          * @return boolean was the insert successful?
1028          * @throws \Exception
1029          */
1030         public function replace($table, array $param)
1031         {
1032                 if (empty($table) || empty($param)) {
1033                         $this->logger->info('Table and fields have to be set');
1034                         return false;
1035                 }
1036
1037                 $param = $this->castFields($table, $param);
1038
1039                 $table_string = DBA::buildTableString($table);
1040
1041                 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1042
1043                 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1044
1045                 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1046
1047                 return $this->e($sql, $param);
1048         }
1049
1050         /**
1051          * Fetch the id of the last insert command
1052          *
1053          * @return integer Last inserted id
1054          */
1055         public function lastInsertId()
1056         {
1057                 switch ($this->driver) {
1058                         case self::PDO:
1059                                 $id = $this->connection->lastInsertId();
1060                                 break;
1061                         case self::MYSQLI:
1062                                 $id = $this->connection->insert_id;
1063                                 break;
1064                 }
1065                 return (int)$id;
1066         }
1067
1068         /**
1069          * Locks a table for exclusive write access
1070          *
1071          * This function can be extended in the future to accept a table array as well.
1072          *
1073          * @param string|array $table Table name or array [schema => table]
1074          *
1075          * @return boolean was the lock successful?
1076          * @throws \Exception
1077          */
1078         public function lock($table)
1079         {
1080                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1081                 if ($this->driver == self::PDO) {
1082                         $this->e("SET autocommit=0");
1083                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1084                 } else {
1085                         $this->connection->autocommit(false);
1086                 }
1087
1088                 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1089
1090                 if ($this->driver == self::PDO) {
1091                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1092                 }
1093
1094                 if (!$success) {
1095                         if ($this->driver == self::PDO) {
1096                                 $this->e("SET autocommit=1");
1097                         } else {
1098                                 $this->connection->autocommit(true);
1099                         }
1100                 } else {
1101                         $this->in_transaction = true;
1102                 }
1103                 return $success;
1104         }
1105
1106         /**
1107          * Unlocks all locked tables
1108          *
1109          * @return boolean was the unlock successful?
1110          * @throws \Exception
1111          */
1112         public function unlock()
1113         {
1114                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1115                 $this->performCommit();
1116
1117                 if ($this->driver == self::PDO) {
1118                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1119                 }
1120
1121                 $success = $this->e("UNLOCK TABLES");
1122
1123                 if ($this->driver == self::PDO) {
1124                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1125                         $this->e("SET autocommit=1");
1126                 } else {
1127                         $this->connection->autocommit(true);
1128                 }
1129
1130                 $this->in_transaction = false;
1131                 return $success;
1132         }
1133
1134         /**
1135          * Starts a transaction
1136          *
1137          * @return boolean Was the command executed successfully?
1138          */
1139         public function transaction()
1140         {
1141                 if (!$this->performCommit()) {
1142                         return false;
1143                 }
1144
1145                 switch ($this->driver) {
1146                         case self::PDO:
1147                                 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1148                                         return false;
1149                                 }
1150                                 break;
1151
1152                         case self::MYSQLI:
1153                                 if (!$this->connection->begin_transaction()) {
1154                                         return false;
1155                                 }
1156                                 break;
1157                 }
1158
1159                 $this->in_transaction = true;
1160                 return true;
1161         }
1162
1163         protected function performCommit()
1164         {
1165                 switch ($this->driver) {
1166                         case self::PDO:
1167                                 if (!$this->connection->inTransaction()) {
1168                                         return true;
1169                                 }
1170
1171                                 return $this->connection->commit();
1172
1173                         case self::MYSQLI:
1174                                 return $this->connection->commit();
1175                 }
1176
1177                 return true;
1178         }
1179
1180         /**
1181          * Does a commit
1182          *
1183          * @return boolean Was the command executed successfully?
1184          */
1185         public function commit()
1186         {
1187                 if (!$this->performCommit()) {
1188                         return false;
1189                 }
1190                 $this->in_transaction = false;
1191                 return true;
1192         }
1193
1194         /**
1195          * Does a rollback
1196          *
1197          * @return boolean Was the command executed successfully?
1198          */
1199         public function rollback()
1200         {
1201                 $ret = false;
1202
1203                 switch ($this->driver) {
1204                         case self::PDO:
1205                                 if (!$this->connection->inTransaction()) {
1206                                         $ret = true;
1207                                         break;
1208                                 }
1209                                 $ret = $this->connection->rollBack();
1210                                 break;
1211
1212                         case self::MYSQLI:
1213                                 $ret = $this->connection->rollback();
1214                                 break;
1215                 }
1216                 $this->in_transaction = false;
1217                 return $ret;
1218         }
1219
1220         /**
1221          * Build the array with the table relations
1222          *
1223          * The array is build from the database definitions in DBStructure.php
1224          *
1225          * This process must only be started once, since the value is cached.
1226          */
1227         private function buildRelationData()
1228         {
1229                 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1230
1231                 foreach ($definition AS $table => $structure) {
1232                         foreach ($structure['fields'] AS $field => $field_struct) {
1233                                 if (isset($field_struct['relation'])) {
1234                                         foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1235                                                 $this->relation[$rel_table][$rel_field][$table][] = $field;
1236                                         }
1237                                 }
1238                         }
1239                 }
1240         }
1241
1242         /**
1243          * Delete a row from a table
1244          *
1245          * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1246          *
1247          * @param string $table      Table name
1248          * @param array  $conditions Field condition(s)
1249          * @param array  $options
1250          *                           - cascade: If true we delete records in other tables that depend on the one we're deleting through
1251          *                           relations (default: true)
1252          * @param array  $callstack  Internal use: prevent endless loops
1253          *
1254          * @return boolean was the delete successful?
1255          * @throws \Exception
1256          */
1257         public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1258         {
1259                 if (empty($table) || empty($conditions)) {
1260                         $this->logger->info('Table and conditions have to be set');
1261                         return false;
1262                 }
1263
1264                 $commands = [];
1265
1266                 // Create a key for the loop prevention
1267                 $key = $table . ':' . json_encode($conditions);
1268
1269                 // We quit when this key already exists in the callstack.
1270                 if (isset($callstack[$key])) {
1271                         return true;
1272                 }
1273
1274                 $callstack[$key] = true;
1275
1276                 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1277
1278                 // Don't use "defaults" here, since it would set "false" to "true"
1279                 if (isset($options['cascade'])) {
1280                         $cascade = $options['cascade'];
1281                 } else {
1282                         $cascade = true;
1283                 }
1284
1285                 // To speed up the whole process we cache the table relations
1286                 if ($cascade && count($this->relation) == 0) {
1287                         $this->buildRelationData();
1288                 }
1289
1290                 // Is there a relation entry for the table?
1291                 if ($cascade && isset($this->relation[$table])) {
1292                         // We only allow a simple "one field" relation.
1293                         $field   = array_keys($this->relation[$table])[0];
1294                         $rel_def = array_values($this->relation[$table])[0];
1295
1296                         // Create a key for preventing double queries
1297                         $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1298
1299                         // When the search field is the relation field, we don't need to fetch the rows
1300                         // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1301                         if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1302                                 foreach ($rel_def AS $rel_table => $rel_fields) {
1303                                         foreach ($rel_fields AS $rel_field) {
1304                                                 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1305                                         }
1306                                 }
1307                                 // We quit when this key already exists in the callstack.
1308                         } elseif (!isset($callstack[$qkey])) {
1309                                 $callstack[$qkey] = true;
1310
1311                                 // Fetch all rows that are to be deleted
1312                                 $data = $this->select($table, [$field], $conditions);
1313
1314                                 while ($row = $this->fetch($data)) {
1315                                         $this->delete($table, [$field => $row[$field]], $options, $callstack);
1316                                 }
1317
1318                                 $this->close($data);
1319
1320                                 // Since we had split the delete command we don't need the original command anymore
1321                                 unset($commands[$key]);
1322                         }
1323                 }
1324
1325                 // Now we finalize the process
1326                 $do_transaction = !$this->in_transaction;
1327
1328                 if ($do_transaction) {
1329                         $this->transaction();
1330                 }
1331
1332                 $compacted = [];
1333                 $counter   = [];
1334
1335                 foreach ($commands AS $command) {
1336                         $conditions = $command['conditions'];
1337                         reset($conditions);
1338                         $first_key = key($conditions);
1339
1340                         $condition_string = DBA::buildCondition($conditions);
1341
1342                         if ((count($command['conditions']) > 1) || is_int($first_key)) {
1343                                 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1344                                 $this->logger->info($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1345
1346                                 if (!$this->e($sql, $conditions)) {
1347                                         if ($do_transaction) {
1348                                                 $this->rollback();
1349                                         }
1350                                         return false;
1351                                 }
1352                         } else {
1353                                 $key_table     = $command['table'];
1354                                 $key_condition = array_keys($command['conditions'])[0];
1355                                 $value         = array_values($command['conditions'])[0];
1356
1357                                 // Split the SQL queries in chunks of 100 values
1358                                 // We do the $i stuff here to make the code better readable
1359                                 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1360                                 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1361                                         ++$i;
1362                                 }
1363
1364                                 $compacted[$key_table][$key_condition][$i][$value] = $value;
1365                                 $counter[$key_table][$key_condition]               = $i;
1366                         }
1367                 }
1368                 foreach ($compacted AS $table => $values) {
1369                         foreach ($values AS $field => $field_value_list) {
1370                                 foreach ($field_value_list AS $field_values) {
1371                                         $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1372                                                substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1373
1374                                         $this->logger->info($this->replaceParameters($sql, $field_values), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1375
1376                                         if (!$this->e($sql, $field_values)) {
1377                                                 if ($do_transaction) {
1378                                                         $this->rollback();
1379                                                 }
1380                                                 return false;
1381                                         }
1382                                 }
1383                         }
1384                 }
1385                 if ($do_transaction) {
1386                         $this->commit();
1387                 }
1388                 return true;
1389         }
1390
1391         /**
1392          * Updates rows
1393          *
1394          * Updates rows in the database. When $old_fields is set to an array,
1395          * the system will only do an update if the fields in that array changed.
1396          *
1397          * Attention:
1398          * Only the values in $old_fields are compared.
1399          * This is an intentional behaviour.
1400          *
1401          * Example:
1402          * We include the timestamp field in $fields but not in $old_fields.
1403          * Then the row will only get the new timestamp when the other fields had changed.
1404          *
1405          * When $old_fields is set to a boolean value the system will do this compare itself.
1406          * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1407          *
1408          * Attention:
1409          * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1410          * When you set $old_fields to "true" then $fields must contain all relevant fields!
1411          *
1412          * @param string|array  $table      Table name or array [schema => table]
1413          * @param array         $fields     contains the fields that are updated
1414          * @param array         $condition  condition array with the key values
1415          * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1416          *
1417          * @return boolean was the update successfull?
1418          * @throws \Exception
1419          */
1420         public function update($table, $fields, $condition, $old_fields = [])
1421         {
1422                 if (empty($table) || empty($fields) || empty($condition)) {
1423                         $this->logger->info('Table, fields and condition have to be set');
1424                         return false;
1425                 }
1426
1427                 if (is_bool($old_fields)) {
1428                         $do_insert = $old_fields;
1429
1430                         $old_fields = $this->selectFirst($table, [], $condition);
1431
1432                         if (is_bool($old_fields)) {
1433                                 if ($do_insert) {
1434                                         $values = array_merge($condition, $fields);
1435                                         return $this->replace($table, $values);
1436                                 }
1437                                 $old_fields = [];
1438                         }
1439                 }
1440
1441                 foreach ($old_fields AS $fieldname => $content) {
1442                         if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1443                                 unset($fields[$fieldname]);
1444                         }
1445                 }
1446
1447                 if (count($fields) == 0) {
1448                         return true;
1449                 }
1450
1451                 $fields = $this->castFields($table, $fields);
1452
1453                 $table_string = DBA::buildTableString($table);
1454
1455                 $condition_string = DBA::buildCondition($condition);
1456
1457                 $sql = "UPDATE " . $table_string . " SET "
1458                         . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1459                         . $condition_string;
1460
1461                 // Combines the updated fields parameter values with the condition parameter values
1462                 $params  = array_merge(array_values($fields), $condition);
1463
1464                 return $this->e($sql, $params);
1465         }
1466
1467         /**
1468          * Retrieve a single record from a table and returns it in an associative array
1469          *
1470          * @param string|array $table
1471          * @param array        $fields
1472          * @param array        $condition
1473          * @param array        $params
1474          *
1475          * @return bool|array
1476          * @throws \Exception
1477          * @see   $this->select
1478          */
1479         public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1480         {
1481                 $params['limit'] = 1;
1482                 $result          = $this->select($table, $fields, $condition, $params);
1483
1484                 if (is_bool($result)) {
1485                         return $result;
1486                 } else {
1487                         $row = $this->fetch($result);
1488                         $this->close($result);
1489                         return $row;
1490                 }
1491         }
1492
1493         /**
1494          * Select rows from a table and fills an array with the data
1495          *
1496          * @param string|array $table     Table name or array [schema => table]
1497          * @param array        $fields    Array of selected fields, empty for all
1498          * @param array        $condition Array of fields for condition
1499          * @param array        $params    Array of several parameters
1500          *
1501          * @return array Data array
1502          * @throws \Exception
1503          * @see   self::select
1504          */
1505         public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1506         {
1507                 return $this->toArray($this->select($table, $fields, $condition, $params));
1508         }
1509
1510         /**
1511          * Select rows from a table
1512          *
1513          *
1514          * Example:
1515          * $table = 'post';
1516          * or:
1517          * $table = ['schema' => 'table'];
1518          * @see DBA::buildTableString()
1519          *
1520          * $fields = ['id', 'uri', 'uid', 'network'];
1521          *
1522          * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1523          * or:
1524          * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1525          * @see DBA::buildCondition()
1526          *
1527          * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1528          * @see DBA::buildParameter()
1529          *
1530          * $data = DBA::select($table, $fields, $condition, $params);
1531          *
1532          * @param string|array $table     Table name or array [schema => table]
1533          * @param array        $fields    Array of selected fields, empty for all
1534          * @param array        $condition Array of fields for condition
1535          * @param array        $params    Array of several parameters
1536          * @return boolean|object
1537          * @throws \Exception
1538          */
1539         public function select($table, array $fields = [], array $condition = [], array $params = [])
1540         {
1541                 if (empty($table)) {
1542                         return false;
1543                 }
1544
1545                 if (count($fields) > 0) {
1546                         $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1547                 } else {
1548                         $select_string = '*';
1549                 }
1550
1551                 $table_string = DBA::buildTableString($table);
1552
1553                 $condition_string = DBA::buildCondition($condition);
1554
1555                 $param_string = DBA::buildParameter($params);
1556
1557                 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1558
1559                 $result = $this->p($sql, $condition);
1560
1561                 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1562                         $result->table = $table;
1563                 }
1564
1565                 return $result;
1566         }
1567
1568         /**
1569          * Counts the rows from a table satisfying the provided condition
1570          *
1571          * @param string|array $table     Table name or array [schema => table]
1572          * @param array        $condition Array of fields for condition
1573          * @param array        $params    Array of several parameters
1574          *
1575          * @return int
1576          *
1577          * Example:
1578          * $table = "post";
1579          *
1580          * $condition = ["uid" => 1, "network" => 'dspr'];
1581          * or:
1582          * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1583          *
1584          * $count = DBA::count($table, $condition);
1585          * @throws \Exception
1586          */
1587         public function count($table, array $condition = [], array $params = [])
1588         {
1589                 if (empty($table)) {
1590                         return false;
1591                 }
1592
1593                 $table_string = DBA::buildTableString($table);
1594
1595                 $condition_string = DBA::buildCondition($condition);
1596
1597                 if (empty($params['expression'])) {
1598                         $expression = '*';
1599                 } elseif (!empty($params['distinct'])) {
1600                         $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1601                 } else {
1602                         $expression = DBA::quoteIdentifier($params['expression']);
1603                 }
1604
1605                 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1606
1607                 $row = $this->fetchFirst($sql, $condition);
1608
1609                 // Ensure to always return either a "null" or a numeric value
1610                 return is_numeric($row['count']) ? (int)$row['count'] : $row['count'];
1611         }
1612
1613         /**
1614          * Fills an array with data from a query
1615          *
1616          * @param object $stmt     statement object
1617          * @param bool   $do_close Close database connection after last row
1618          * @param int    $count    maximum number of rows to be fetched
1619          *
1620          * @return array Data array
1621          */
1622         public function toArray($stmt, $do_close = true, int $count = 0)
1623         {
1624                 if (is_bool($stmt)) {
1625                         return [];
1626                 }
1627
1628                 $data = [];
1629                 while ($row = $this->fetch($stmt)) {
1630                         $data[] = $row;
1631                         if (($count != 0) && (count($data) == $count)) {
1632                                 return $data;
1633                         }
1634                 }
1635
1636                 if ($do_close) {
1637                         $this->close($stmt);
1638                 }
1639
1640                 return $data;
1641         }
1642
1643         /**
1644          * Cast field types according to the table definition
1645          *
1646          * @param string $table
1647          * @param array  $fields
1648          * @return array casted fields
1649          */
1650         public function castFields(string $table, array $fields) {
1651                 // When there is no data, we don't need to do something
1652                 if (empty($fields)) {
1653                         return $fields;
1654                 }
1655
1656                 // We only need to cast fields with PDO
1657                 if ($this->driver != self::PDO) {
1658                         return $fields;
1659                 }
1660
1661                 // We only need to cast when emulating the prepares
1662                 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1663                         return $fields;
1664                 }
1665
1666                 $types = [];
1667
1668                 $tables = DBStructure::definition('', false);
1669                 if (empty($tables[$table])) {
1670                         // When a matching table wasn't found we check if it is a view
1671                         $views = View::definition('', false);
1672                         if (empty($views[$table])) {
1673                                 return $fields;
1674                         }
1675
1676                         foreach(array_keys($fields) as $field) {
1677                                 if (!empty($views[$table]['fields'][$field])) {
1678                                         $viewdef = $views[$table]['fields'][$field];
1679                                         if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1680                                                 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1681                                         }
1682                                 }
1683                         }
1684                 } else {
1685                         foreach ($tables[$table]['fields'] as $field => $definition) {
1686                                 $types[$field] = $definition['type'];
1687                         }
1688                 }
1689
1690                 foreach ($fields as $field => $content) {
1691                         if (is_null($content) || empty($types[$field])) {
1692                                 continue;
1693                         }
1694
1695                         if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1696                                 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1697                                 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1698                                 $fields[$field] = (int)$content;
1699                         }
1700                         if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1701                                 $fields[$field] = (float)$content;
1702                         }
1703                 }
1704
1705                 return $fields; 
1706         }
1707         
1708         /**
1709          * Returns the error number of the last query
1710          *
1711          * @return string Error number (0 if no error)
1712          */
1713         public function errorNo()
1714         {
1715                 return $this->errorno;
1716         }
1717
1718         /**
1719          * Returns the error message of the last query
1720          *
1721          * @return string Error message ('' if no error)
1722          */
1723         public function errorMessage()
1724         {
1725                 return $this->error;
1726         }
1727
1728         /**
1729          * Closes the current statement
1730          *
1731          * @param object $stmt statement object
1732          *
1733          * @return boolean was the close successful?
1734          */
1735         public function close($stmt)
1736         {
1737
1738                 $stamp1 = microtime(true);
1739
1740                 if (!is_object($stmt)) {
1741                         return false;
1742                 }
1743
1744                 switch ($this->driver) {
1745                         case self::PDO:
1746                                 $ret = $stmt->closeCursor();
1747                                 break;
1748                         case self::MYSQLI:
1749                                 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1750                                 // We should be careful not to assume the object type of $stmt
1751                                 // because DBA::p() has been able to return both types.
1752                                 if ($stmt instanceof mysqli_stmt) {
1753                                         $stmt->free_result();
1754                                         $ret = $stmt->close();
1755                                 } elseif ($stmt instanceof mysqli_result) {
1756                                         $stmt->free();
1757                                         $ret = true;
1758                                 } else {
1759                                         $ret = false;
1760                                 }
1761                                 break;
1762                 }
1763
1764                 $this->profiler->saveTimestamp($stamp1, 'database');
1765
1766                 return $ret;
1767         }
1768
1769         /**
1770          * Return a list of database processes
1771          *
1772          * @return array
1773          *      'list' => List of processes, separated in their different states
1774          *      'amount' => Number of concurrent database processes
1775          * @throws \Exception
1776          */
1777         public function processlist()
1778         {
1779                 $ret  = $this->p("SHOW PROCESSLIST");
1780                 $data = $this->toArray($ret);
1781
1782                 $processes = 0;
1783                 $states    = [];
1784                 foreach ($data as $process) {
1785                         $state = trim($process["State"]);
1786
1787                         // Filter out all non blocking processes
1788                         if (!in_array($state, ["", "init", "statistics", "updating"])) {
1789                                 ++$states[$state];
1790                                 ++$processes;
1791                         }
1792                 }
1793
1794                 $statelist = "";
1795                 foreach ($states as $state => $usage) {
1796                         if ($statelist != "") {
1797                                 $statelist .= ", ";
1798                         }
1799                         $statelist .= $state . ": " . $usage;
1800                 }
1801                 return (["list" => $statelist, "amount" => $processes]);
1802         }
1803
1804         /**
1805          * Fetch a database variable
1806          *
1807          * @param string $name
1808          * @return string content
1809          */
1810         public function getVariable(string $name)
1811         {
1812                 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1813                 return $result['Value'] ?? null;
1814         }
1815
1816         /**
1817          * Checks if $array is a filled array with at least one entry.
1818          *
1819          * @param mixed $array A filled array with at least one entry
1820          *
1821          * @return boolean Whether $array is a filled array or an object with rows
1822          */
1823         public function isResult($array)
1824         {
1825                 // It could be a return value from an update statement
1826                 if (is_bool($array)) {
1827                         return $array;
1828                 }
1829
1830                 if (is_object($array)) {
1831                         return $this->numRows($array) > 0;
1832                 }
1833
1834                 return (is_array($array) && (count($array) > 0));
1835         }
1836
1837         /**
1838          * Callback function for "esc_array"
1839          *
1840          * @param mixed   $value         Array value
1841          * @param string  $key           Array key
1842          * @param boolean $add_quotation add quotation marks for string values
1843          *
1844          * @return void
1845          */
1846         private function escapeArrayCallback(&$value, $key, $add_quotation)
1847         {
1848                 if (!$add_quotation) {
1849                         if (is_bool($value)) {
1850                                 $value = ($value ? '1' : '0');
1851                         } else {
1852                                 $value = $this->escape($value);
1853                         }
1854                         return;
1855                 }
1856
1857                 if (is_bool($value)) {
1858                         $value = ($value ? 'true' : 'false');
1859                 } elseif (is_float($value) || is_integer($value)) {
1860                         $value = (string)$value;
1861                 } else {
1862                         $value = "'" . $this->escape($value) . "'";
1863                 }
1864         }
1865
1866         /**
1867          * Escapes a whole array
1868          *
1869          * @param mixed   $arr           Array with values to be escaped
1870          * @param boolean $add_quotation add quotation marks for string values
1871          *
1872          * @return void
1873          */
1874         public function escapeArray(&$arr, $add_quotation = false)
1875         {
1876                 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1877         }
1878 }