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