]> git.mxchange.org Git - friendica.git/blob - src/Database/Database.php
Merge pull request #11689 from Quix0r/rewrites/double-quotes-single
[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          * @todo Please unwrap the DBStructure::existsTable() call so this method has one behavior only: checking existence on records
829          */
830         public function exists(string $table, array $condition): bool
831         {
832                 if (empty($table)) {
833                         return false;
834                 }
835
836                 $fields = [];
837
838                 if (empty($condition)) {
839                         return DBStructure::existsTable($table);
840                 }
841
842                 reset($condition);
843                 $first_key = key($condition);
844                 if (!is_int($first_key)) {
845                         $fields = [$first_key];
846                 }
847
848                 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
849
850                 if (is_bool($stmt)) {
851                         $retval = $stmt;
852                 } else {
853                         $retval = ($this->numRows($stmt) > 0);
854                 }
855
856                 $this->close($stmt);
857
858                 return $retval;
859         }
860
861         /**
862          * Fetches the first row
863          *
864          * Please use DBA::selectFirst or DBA::exists whenever this is possible.
865          *
866          * Fetches the first row
867          *
868          * @param string $sql SQL statement
869          *
870          * @return array|bool first row of query or false on failure
871          * @throws \Exception
872          */
873         public function fetchFirst(string $sql)
874         {
875                 $params = DBA::getParam(func_get_args());
876
877                 $stmt = $this->p($sql, $params);
878
879                 if (is_bool($stmt)) {
880                         $retval = $stmt;
881                 } else {
882                         $retval = $this->fetch($stmt);
883                 }
884
885                 $this->close($stmt);
886
887                 return $retval;
888         }
889
890         /**
891          * Returns the number of affected rows of the last statement
892          *
893          * @return int Number of rows
894          */
895         public function affectedRows(): int
896         {
897                 return $this->affected_rows;
898         }
899
900         /**
901          * Returns the number of columns of a statement
902          *
903          * @param object Statement object
904          *
905          * @return int Number of columns
906          */
907         public function columnCount($stmt): int
908         {
909                 if (!is_object($stmt)) {
910                         return 0;
911                 }
912                 switch ($this->driver) {
913                         case self::PDO:
914                                 return $stmt->columnCount();
915                         case self::MYSQLI:
916                                 return $stmt->field_count;
917                 }
918                 return 0;
919         }
920
921         /**
922          * Returns the number of rows of a statement
923          *
924          * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
925          *
926          * @return int Number of rows
927          */
928         public function numRows($stmt): int
929         {
930                 if (!is_object($stmt)) {
931                         return 0;
932                 }
933                 switch ($this->driver) {
934                         case self::PDO:
935                                 return $stmt->rowCount();
936                         case self::MYSQLI:
937                                 return $stmt->num_rows;
938                 }
939                 return 0;
940         }
941
942         /**
943          * Fetch a single row
944          *
945          * @param bool|PDOStatement|mysqli_stmt $stmt statement object
946          *
947          * @return array|bool Current row or false on failure
948          */
949         public function fetch($stmt)
950         {
951                 $this->profiler->startRecording('database');
952
953                 $columns = [];
954
955                 if (!is_object($stmt)) {
956                         return false;
957                 }
958
959                 switch ($this->driver) {
960                         case self::PDO:
961                                 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
962                                 if (!empty($stmt->table) && is_array($columns)) {
963                                         $columns = $this->castFields($stmt->table, $columns);
964                                 }
965                                 break;
966                         case self::MYSQLI:
967                                 if (get_class($stmt) == 'mysqli_result') {
968                                         $columns = $stmt->fetch_assoc() ?? false;
969                                         break;
970                                 }
971
972                                 // This code works, but is slow
973
974                                 // Bind the result to a result array
975                                 $cols = [];
976
977                                 $cols_num = [];
978                                 for ($x = 0; $x < $stmt->field_count; $x++) {
979                                         $cols[] = &$cols_num[$x];
980                                 }
981
982                                 call_user_func_array([$stmt, 'bind_result'], $cols);
983
984                                 if (!$stmt->fetch()) {
985                                         return false;
986                                 }
987
988                                 // The slow part:
989                                 // We need to get the field names for the array keys
990                                 // It seems that there is no better way to do this.
991                                 $result = $stmt->result_metadata();
992                                 $fields = $result->fetch_fields();
993
994                                 foreach ($cols_num as $param => $col) {
995                                         $columns[$fields[$param]->name] = $col;
996                                 }
997                 }
998
999                 $this->profiler->stopRecording();
1000
1001                 return $columns;
1002         }
1003
1004         /**
1005          * Insert a row into a table. Field value objects will be cast as string.
1006          *
1007          * @param string $table          Table name in format schema.table (while scheme is optiona)
1008          * @param array  $param          parameter array
1009          * @param int    $duplicate_mode What to do on a duplicated entry
1010          *
1011          * @return boolean was the insert successful?
1012          * @throws \Exception
1013          */
1014         public function insert(string $table, array $param, int $duplicate_mode = self::INSERT_DEFAULT): bool
1015         {
1016                 if (empty($table) || empty($param)) {
1017                         $this->logger->info('Table and fields have to be set');
1018                         return false;
1019                 }
1020
1021                 $param = $this->castFields($table, $param);
1022
1023                 $table_string = DBA::buildTableString([$table]);
1024
1025                 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1026
1027                 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1028
1029                 $sql = "INSERT ";
1030
1031                 if ($duplicate_mode == self::INSERT_IGNORE) {
1032                         $sql .= "IGNORE ";
1033                 }
1034
1035                 $sql .= "INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1036
1037                 if ($duplicate_mode == self::INSERT_UPDATE) {
1038                         $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1039
1040                         $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
1041
1042                         $values = array_values($param);
1043                         $param  = array_merge_recursive($values, $values);
1044                 }
1045
1046                 $result = $this->e($sql, $param);
1047                 if (!$result || ($duplicate_mode != self::INSERT_IGNORE)) {
1048                         return $result;
1049                 }
1050
1051                 return $this->affectedRows() != 0;
1052         }
1053
1054         /**
1055          * Inserts a row with the provided data in the provided table.
1056          * If the data corresponds to an existing row through a UNIQUE or PRIMARY index constraints, it updates the row instead.
1057          *
1058          * @param string $table Table name in format schema.table (while scheme is optiona)
1059          * @param array  $param parameter array
1060          * @return boolean was the insert successful?
1061          * @throws \Exception
1062          */
1063         public function replace(string $table, array $param): bool
1064         {
1065                 if (empty($table) || empty($param)) {
1066                         $this->logger->info('Table and fields have to be set');
1067                         return false;
1068                 }
1069
1070                 $param = $this->castFields($table, $param);
1071
1072                 $table_string = DBA::buildTableString([$table]);
1073
1074                 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
1075
1076                 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
1077
1078                 $sql = "REPLACE " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
1079
1080                 return $this->e($sql, $param);
1081         }
1082
1083         /**
1084          * Fetch the id of the last insert command
1085          *
1086          * @return integer Last inserted id
1087          */
1088         public function lastInsertId(): int
1089         {
1090                 switch ($this->driver) {
1091                         case self::PDO:
1092                                 $id = $this->connection->lastInsertId();
1093                                 break;
1094                         case self::MYSQLI:
1095                                 $id = $this->connection->insert_id;
1096                                 break;
1097                 }
1098                 return (int)$id;
1099         }
1100
1101         /**
1102          * Locks a table for exclusive write access
1103          *
1104          * This function can be extended in the future to accept a table array as well.
1105          *
1106          * @param string $table Table name in format schema.table (while scheme is optiona)
1107          * @return boolean was the lock successful?
1108          * @throws \Exception
1109          */
1110         public function lock(string $table): bool
1111         {
1112                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1113                 if ($this->driver == self::PDO) {
1114                         $this->e("SET autocommit=0");
1115                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1116                 } else {
1117                         $this->connection->autocommit(false);
1118                 }
1119
1120                 $success = $this->e("LOCK TABLES " . DBA::buildTableString([$table]) . " WRITE");
1121
1122                 if ($this->driver == self::PDO) {
1123                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1124                 }
1125
1126                 if (!$success) {
1127                         if ($this->driver == self::PDO) {
1128                                 $this->e("SET autocommit=1");
1129                         } else {
1130                                 $this->connection->autocommit(true);
1131                         }
1132                 } else {
1133                         $this->in_transaction = true;
1134                 }
1135                 return $success;
1136         }
1137
1138         /**
1139          * Unlocks all locked tables
1140          *
1141          * @return boolean was the unlock successful?
1142          * @throws \Exception
1143          */
1144         public function unlock(): bool
1145         {
1146                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1147                 $this->performCommit();
1148
1149                 if ($this->driver == self::PDO) {
1150                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1151                 }
1152
1153                 $success = $this->e("UNLOCK TABLES");
1154
1155                 if ($this->driver == self::PDO) {
1156                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->pdo_emulate_prepares);
1157                         $this->e("SET autocommit=1");
1158                 } else {
1159                         $this->connection->autocommit(true);
1160                 }
1161
1162                 $this->in_transaction = false;
1163                 return $success;
1164         }
1165
1166         /**
1167          * Starts a transaction
1168          *
1169          * @return boolean Was the command executed successfully?
1170          */
1171         public function transaction(): bool
1172         {
1173                 if (!$this->performCommit()) {
1174                         return false;
1175                 }
1176
1177                 switch ($this->driver) {
1178                         case self::PDO:
1179                                 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1180                                         return false;
1181                                 }
1182                                 break;
1183
1184                         case self::MYSQLI:
1185                                 if (!$this->connection->begin_transaction()) {
1186                                         return false;
1187                                 }
1188                                 break;
1189                 }
1190
1191                 $this->in_transaction = true;
1192                 return true;
1193         }
1194
1195         /**
1196          * Performs the commit
1197          *
1198          * @return boolean Was the command executed successfully?
1199          */
1200         protected function performCommit(): bool
1201         {
1202                 switch ($this->driver) {
1203                         case self::PDO:
1204                                 if (!$this->connection->inTransaction()) {
1205                                         return true;
1206                                 }
1207
1208                                 return $this->connection->commit();
1209
1210                         case self::MYSQLI:
1211                                 return $this->connection->commit();
1212                 }
1213
1214                 return true;
1215         }
1216
1217         /**
1218          * Does a commit
1219          *
1220          * @return boolean Was the command executed successfully?
1221          */
1222         public function commit(): bool
1223         {
1224                 if (!$this->performCommit()) {
1225                         return false;
1226                 }
1227                 $this->in_transaction = false;
1228                 return true;
1229         }
1230
1231         /**
1232          * Does a rollback
1233          *
1234          * @return boolean Was the command executed successfully?
1235          */
1236         public function rollback(): bool
1237         {
1238                 $ret = false;
1239
1240                 switch ($this->driver) {
1241                         case self::PDO:
1242                                 if (!$this->connection->inTransaction()) {
1243                                         $ret = true;
1244                                         break;
1245                                 }
1246                                 $ret = $this->connection->rollBack();
1247                                 break;
1248
1249                         case self::MYSQLI:
1250                                 $ret = $this->connection->rollback();
1251                                 break;
1252                 }
1253
1254                 $this->in_transaction = false;
1255                 return $ret;
1256         }
1257
1258         /**
1259          * Delete a row from a table
1260          *
1261          * @param string $table      Table name
1262          * @param array  $conditions Field condition(s)
1263          *
1264          * @return boolean was the delete successful?
1265          * @throws \Exception
1266          */
1267         public function delete(string $table, array $conditions): bool
1268         {
1269                 if (empty($table) || empty($conditions)) {
1270                         $this->logger->info('Table and conditions have to be set');
1271                         return false;
1272                 }
1273
1274                 $table_string = DBA::buildTableString([$table]);
1275
1276                 $condition_string = DBA::buildCondition($conditions);
1277
1278                 $sql = "DELETE FROM " . $table_string . " " . $condition_string;
1279                 $this->logger->debug($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6)]);
1280                 return $this->e($sql, $conditions);
1281         }
1282
1283         /**
1284          * Updates rows in the database. Field value objects will be cast as string.
1285          *
1286          * When $old_fields is set to an array,
1287          * the system will only do an update if the fields in that array changed.
1288          *
1289          * Attention:
1290          * Only the values in $old_fields are compared.
1291          * This is an intentional behaviour.
1292          *
1293          * Example:
1294          * We include the timestamp field in $fields but not in $old_fields.
1295          * Then the row will only get the new timestamp when the other fields had changed.
1296          *
1297          * When $old_fields is set to a boolean value the system will do this compare itself.
1298          * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1299          *
1300          * Attention:
1301          * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1302          * When you set $old_fields to "true" then $fields must contain all relevant fields!
1303          *
1304          * @param string        $table      Table name in format schema.table (while scheme is optiona)
1305          * @param array         $fields     contains the fields that are updated
1306          * @param array         $condition  condition array with the key values
1307          * @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)
1308          * @param array         $params     Parameters: "ignore" If set to "true" then the update is done with the ignore parameter
1309          *
1310          * @return boolean was the update successfull?
1311          * @throws \Exception
1312          * @todo Implement "bool $update_on_duplicate" to avoid mixed type for $old_fields
1313          */
1314         public function update(string $table, array $fields, array $condition, $old_fields = [], array $params = [])
1315         {
1316                 if (empty($table) || empty($fields) || empty($condition)) {
1317                         $this->logger->info('Table, fields and condition have to be set');
1318                         return false;
1319                 }
1320
1321                 if (is_bool($old_fields)) {
1322                         $do_insert = $old_fields;
1323
1324                         $old_fields = $this->selectFirst($table, [], $condition);
1325
1326                         if (is_bool($old_fields)) {
1327                                 if ($do_insert) {
1328                                         $values = array_merge($condition, $fields);
1329                                         return $this->replace($table, $values);
1330                                 }
1331                                 $old_fields = [];
1332                         }
1333                 }
1334
1335                 foreach ($old_fields as $fieldname => $content) {
1336                         if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1337                                 unset($fields[$fieldname]);
1338                         }
1339                 }
1340
1341                 if (count($fields) == 0) {
1342                         return true;
1343                 }
1344
1345                 $fields = $this->castFields($table, $fields);
1346
1347                 $table_string = DBA::buildTableString([$table]);
1348
1349                 $condition_string = DBA::buildCondition($condition);
1350
1351                 if (!empty($params['ignore'])) {
1352                         $ignore = 'IGNORE ';
1353                 } else {
1354                         $ignore = '';
1355                 }
1356
1357                 $sql = "UPDATE " . $ignore . $table_string . " SET "
1358                         . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1359                         . $condition_string;
1360
1361                 // Combines the updated fields parameter values with the condition parameter values
1362                 $params  = array_merge(array_values($fields), $condition);
1363
1364                 return $this->e($sql, $params);
1365         }
1366
1367         /**
1368          * Retrieve a single record from a table and returns it in an associative array
1369          *
1370          * @param string $table     Table name in format schema.table (while scheme is optiona)
1371          * @param array  $fields    Array of selected fields, empty for all
1372          * @param array  $condition Array of fields for condition
1373          * @param array  $params    Array of several parameters
1374          *
1375          * @return bool|array
1376          * @throws \Exception
1377          * @see   $this->select
1378          */
1379         public function selectFirst(string $table, array $fields = [], array $condition = [], array $params = [])
1380         {
1381                 $params['limit'] = 1;
1382                 $result          = $this->select($table, $fields, $condition, $params);
1383
1384                 if (is_bool($result)) {
1385                         return $result;
1386                 } else {
1387                         $row = $this->fetch($result);
1388                         $this->close($result);
1389                         return $row;
1390                 }
1391         }
1392
1393         /**
1394          * Select rows from a table and fills an array with the data
1395          *
1396          * @param string $table     Table name in format schema.table (while scheme is optiona)
1397          * @param array  $fields    Array of selected fields, empty for all
1398          * @param array  $condition Array of fields for condition
1399          * @param array  $params    Array of several parameters
1400          * @return array Data array
1401          * @throws \Exception
1402          * @see   self::select
1403          */
1404         public function selectToArray(string $table, array $fields = [], array $condition = [], array $params = [])
1405         {
1406                 return $this->toArray($this->select($table, $fields, $condition, $params));
1407         }
1408
1409         /**
1410          * Escape fields, adding special treatment for "group by" handling
1411          *
1412          * @param array $fields 
1413          * @param array $options 
1414          * @return array Escaped fields
1415          */
1416         private function escapeFields(array $fields, array $options): array
1417         {
1418                 // In the case of a "GROUP BY" we have to add all the ORDER fields to the fieldlist.
1419                 // This needs to done to apply the "ANY_VALUE(...)" treatment from below to them.
1420                 // Otherwise MySQL would report errors.
1421                 if (!empty($options['group_by']) && !empty($options['order'])) {
1422                         foreach ($options['order'] as $key => $field) {
1423                                 if (!is_int($key)) {
1424                                         if (!in_array($key, $fields)) {
1425                                                 $fields[] = $key;
1426                                         }
1427                                 } else {
1428                                         if (!in_array($field, $fields)) {
1429                                                 $fields[] = $field;
1430                                         }
1431                                 }
1432                         }
1433                 }
1434
1435                 array_walk($fields, function(&$value, $key) use ($options)
1436                 {
1437                         $field = $value;
1438                         $value = '`' . str_replace('`', '``', $value) . '`';
1439
1440                         if (!empty($options['group_by']) && !in_array($field, $options['group_by'])) {
1441                                 $value = 'ANY_VALUE(' . $value . ') AS ' . $value;
1442                         }
1443                 });
1444
1445                 return $fields;
1446         }
1447
1448         /**
1449          * Select rows from a table
1450          *
1451          *
1452          * Example:
1453          * $table = 'post';
1454          * or:
1455          * $table = ['schema' => 'table'];
1456          * @see DBA::buildTableString()
1457          *
1458          * $fields = ['id', 'uri', 'uid', 'network'];
1459          *
1460          * $condition = ['uid' => 1, 'network' => 'dspr', 'blocked' => true];
1461          * or:
1462          * $condition = ['`uid` = ? AND `network` IN (?, ?)', 1, 'dfrn', 'dspr'];
1463          * @see DBA::buildCondition()
1464          *
1465          * $params = ['order' => ['id', 'received' => true, 'created' => 'ASC'), 'limit' => 10];
1466          * @see DBA::buildParameter()
1467          *
1468          * $data = DBA::select($table, $fields, $condition, $params);
1469          *
1470          * @param string $table     Table name in format schema.table (while scheme is optiona)
1471          * @param array  $fields    Array of selected fields, empty for all
1472          * @param array  $condition Array of fields for condition
1473          * @param array  $params    Array of several parameters
1474          * @return boolean|object
1475          * @throws \Exception
1476          */
1477         public function select(string $table, array $fields = [], array $condition = [], array $params = [])
1478         {
1479                 if (empty($table)) {
1480                         return false;
1481                 }
1482
1483                 if (count($fields) > 0) {
1484                         $fields = $this->escapeFields($fields, $params);
1485                         $select_string = implode(', ', $fields);
1486                 } else {
1487                         $select_string = '*';
1488                 }
1489
1490                 $table_string = DBA::buildTableString([$table]);
1491
1492                 $condition_string = DBA::buildCondition($condition);
1493
1494                 $param_string = DBA::buildParameter($params);
1495
1496                 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1497
1498                 $result = $this->p($sql, $condition);
1499
1500                 if (($this->driver == self::PDO) && !empty($result) && is_string($table)) {
1501                         $result->table = $table;
1502                 }
1503
1504                 return $result;
1505         }
1506
1507         /**
1508          * Counts the rows from a table satisfying the provided condition
1509          *
1510          * @param string $table     Table name in format schema.table (while scheme is optiona)
1511          * @param array  $condition Array of fields for condition
1512          * @param array  $params    Array of several parameters
1513          *
1514          * @return int Count of rows
1515          *
1516          * Example:
1517          * $table = "post";
1518          *
1519          * $condition = ["uid" => 1, "network" => 'dspr'];
1520          * or:
1521          * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1522          *
1523          * $count = DBA::count($table, $condition);
1524          * @throws \Exception
1525          */
1526         public function count(string $table, array $condition = [], array $params = []): int
1527         {
1528                 if (empty($table)) {
1529                         throw new InvalidArgumentException('Parameter "table" cannot be empty.');
1530                 }
1531
1532                 $table_string = DBA::buildTableString([$table]);
1533
1534                 $condition_string = DBA::buildCondition($condition);
1535
1536                 if (empty($params['expression'])) {
1537                         $expression = '*';
1538                 } elseif (!empty($params['distinct'])) {
1539                         $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1540                 } else {
1541                         $expression = DBA::quoteIdentifier($params['expression']);
1542                 }
1543
1544                 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1545
1546                 $row = $this->fetchFirst($sql, $condition);
1547
1548                 if (!isset($row['count'])) {
1549                         $this->logger->notice('Invalid count.', ['table' => $table, 'row' => $row, 'expression' => $expression, 'condition' => $condition_string, 'callstack' => System::callstack()]);
1550                         return 0;
1551                 } else {
1552                         return (int)$row['count'];
1553                 }
1554         }
1555
1556         /**
1557          * Fills an array with data from a query
1558          *
1559          * @param object $stmt     statement object
1560          * @param bool   $do_close Close database connection after last row
1561          * @param int    $count    maximum number of rows to be fetched
1562          *
1563          * @return array Data array
1564          */
1565         public function toArray($stmt, bool $do_close = true, int $count = 0): array
1566         {
1567                 if (is_bool($stmt)) {
1568                         return [];
1569                 }
1570
1571                 $data = [];
1572                 while ($row = $this->fetch($stmt)) {
1573                         $data[] = $row;
1574                         if (($count != 0) && (count($data) == $count)) {
1575                                 return $data;
1576                         }
1577                 }
1578
1579                 if ($do_close) {
1580                         $this->close($stmt);
1581                 }
1582
1583                 return $data;
1584         }
1585
1586         /**
1587          * Cast field types according to the table definition
1588          *
1589          * @param string $table
1590          * @param array  $fields
1591          * @return array casted fields
1592          */
1593         public function castFields(string $table, array $fields): array
1594         {
1595                 // When there is no data, we don't need to do something
1596                 if (empty($fields)) {
1597                         return $fields;
1598                 }
1599
1600                 // We only need to cast fields with PDO
1601                 if ($this->driver != self::PDO) {
1602                         return $fields;
1603                 }
1604
1605                 // We only need to cast when emulating the prepares
1606                 if (!$this->connection->getAttribute(PDO::ATTR_EMULATE_PREPARES)) {
1607                         return $fields;
1608                 }
1609
1610                 $types = [];
1611
1612                 $tables = DBStructure::definition('', false);
1613                 if (empty($tables[$table])) {
1614                         // When a matching table wasn't found we check if it is a view
1615                         $views = View::definition('', false);
1616                         if (empty($views[$table])) {
1617                                 return $fields;
1618                         }
1619
1620                         foreach (array_keys($fields) as $field) {
1621                                 if (!empty($views[$table]['fields'][$field])) {
1622                                         $viewdef = $views[$table]['fields'][$field];
1623                                         if (!empty($tables[$viewdef[0]]['fields'][$viewdef[1]]['type'])) {
1624                                                 $types[$field] = $tables[$viewdef[0]]['fields'][$viewdef[1]]['type'];
1625                                         }
1626                                 }
1627                         }
1628                 } else {
1629                         foreach ($tables[$table]['fields'] as $field => $definition) {
1630                                 $types[$field] = $definition['type'];
1631                         }
1632                 }
1633
1634                 foreach ($fields as $field => $content) {
1635                         if (is_null($content) || empty($types[$field])) {
1636                                 continue;
1637                         }
1638
1639                         if ((substr($types[$field], 0, 7) == 'tinyint') || (substr($types[$field], 0, 8) == 'smallint') ||
1640                                 (substr($types[$field], 0, 9) == 'mediumint') || (substr($types[$field], 0, 3) == 'int') ||
1641                                 (substr($types[$field], 0, 6) == 'bigint') || (substr($types[$field], 0, 7) == 'boolean')) {
1642                                 $fields[$field] = (int)$content;
1643                         }
1644                         if ((substr($types[$field], 0, 5) == 'float') || (substr($types[$field], 0, 6) == 'double')) {
1645                                 $fields[$field] = (float)$content;
1646                         }
1647                 }
1648
1649                 return $fields;
1650         }
1651
1652         /**
1653          * Returns the error number of the last query
1654          *
1655          * @return string Error number (0 if no error)
1656          */
1657         public function errorNo(): int
1658         {
1659                 return $this->errorno;
1660         }
1661
1662         /**
1663          * Returns the error message of the last query
1664          *
1665          * @return string Error message ('' if no error)
1666          */
1667         public function errorMessage(): string
1668         {
1669                 return $this->error;
1670         }
1671
1672         /**
1673          * Closes the current statement
1674          *
1675          * @param object $stmt statement object
1676          *
1677          * @return boolean was the close successful?
1678          */
1679         public function close($stmt): bool
1680         {
1681
1682                 $this->profiler->startRecording('database');
1683
1684                 if (!is_object($stmt)) {
1685                         return false;
1686                 }
1687
1688                 switch ($this->driver) {
1689                         case self::PDO:
1690                                 $ret = $stmt->closeCursor();
1691                                 break;
1692                         case self::MYSQLI:
1693                                 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1694                                 // We should be careful not to assume the object type of $stmt
1695                                 // because DBA::p() has been able to return both types.
1696                                 if ($stmt instanceof mysqli_stmt) {
1697                                         $stmt->free_result();
1698                                         $ret = $stmt->close();
1699                                 } elseif ($stmt instanceof mysqli_result) {
1700                                         $stmt->free();
1701                                         $ret = true;
1702                                 } else {
1703                                         $ret = false;
1704                                 }
1705                                 break;
1706                 }
1707
1708                 $this->profiler->stopRecording();
1709
1710                 return $ret;
1711         }
1712
1713         /**
1714          * Return a list of database processes
1715          *
1716          * @return array
1717          *      'list' => List of processes, separated in their different states
1718          *      'amount' => Number of concurrent database processes
1719          * @throws \Exception
1720          */
1721         public function processlist(): array
1722         {
1723                 $ret  = $this->p('SHOW PROCESSLIST');
1724                 $data = $this->toArray($ret);
1725
1726                 $processes = 0;
1727                 $states    = [];
1728                 foreach ($data as $process) {
1729                         $state = trim($process['State']);
1730
1731                         // Filter out all non blocking processes
1732                         if (!in_array($state, ['', 'init', 'statistics', 'updating'])) {
1733                                 ++$states[$state];
1734                                 ++$processes;
1735                         }
1736                 }
1737
1738                 $statelist = '';
1739                 foreach ($states as $state => $usage) {
1740                         if ($statelist != '') {
1741                                 $statelist .= ', ';
1742                         }
1743                         $statelist .= $state . ': ' . $usage;
1744                 }
1745                 return (['list' => $statelist, 'amount' => $processes]);
1746         }
1747
1748         /**
1749          * Fetch a database variable
1750          *
1751          * @param string $name
1752          * @return string|null content or null if inexistent
1753          * @throws \Exception
1754          */
1755         public function getVariable(string $name)
1756         {
1757                 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1758                 return $result['Value'] ?? null;
1759         }
1760
1761         /**
1762          * Checks if $array is a filled array with at least one entry.
1763          *
1764          * @param mixed $array A filled array with at least one entry
1765          * @return boolean Whether $array is a filled array or an object with rows
1766          */
1767         public function isResult($array): bool
1768         {
1769                 // It could be a return value from an update statement
1770                 if (is_bool($array)) {
1771                         return $array;
1772                 }
1773
1774                 if (is_object($array)) {
1775                         return $this->numRows($array) > 0;
1776                 }
1777
1778                 return (is_array($array) && (count($array) > 0));
1779         }
1780
1781         /**
1782          * Callback function for "esc_array"
1783          *
1784          * @param mixed   $value         Array value
1785          * @param string  $key           Array key
1786          * @param boolean $add_quotation add quotation marks for string values
1787          * @return void
1788          */
1789         private function escapeArrayCallback(&$value, string $key, bool $add_quotation)
1790         {
1791                 if (!$add_quotation) {
1792                         if (is_bool($value)) {
1793                                 $value = ($value ? '1' : '0');
1794                         } else {
1795                                 $value = $this->escape($value);
1796                         }
1797                         return;
1798                 }
1799
1800                 if (is_bool($value)) {
1801                         $value = ($value ? 'true' : 'false');
1802                 } elseif (is_float($value) || is_integer($value)) {
1803                         $value = (string)$value;
1804                 } else {
1805                         $value = "'" . $this->escape($value) . "'";
1806                 }
1807         }
1808
1809         /**
1810          * Escapes a whole array
1811          *
1812          * @param mixed   $arr           Array with values to be escaped
1813          * @param boolean $add_quotation add quotation marks for string values
1814          * @return void
1815          */
1816         public function escapeArray(&$arr, bool $add_quotation = false)
1817         {
1818                 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1819         }
1820
1821         /**
1822          * Replaces a string in the provided fields of the provided table
1823          *
1824          * @param string $table  Table name
1825          * @param array  $fields List of field names in the provided table
1826          * @param string $search String to search for
1827          * @param string $replace String to replace with
1828          * @return void
1829          * @throws \Exception
1830          */
1831         public function replaceInTableFields(string $table, array $fields, string $search, string $replace)
1832         {
1833                 $search = $this->escape($search);
1834                 $replace = $this->escape($replace);
1835
1836                 $upd = [];
1837                 foreach ($fields as $field) {
1838                         $field = DBA::quoteIdentifier($field);
1839                         $upd[] = "$field = REPLACE($field, '$search', '$replace')";
1840                 }
1841
1842                 $upds = implode(', ', $upd);
1843
1844                 $r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds));
1845
1846                 if (!$this->isResult($r)) {
1847                         throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage());
1848                 }
1849         }
1850 }