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