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