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