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