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