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