]> git.mxchange.org Git - friendica.git/blob - src/Database/Database.php
Activate test mode for database
[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                 $this->error         = '';
508                 $this->errorno       = 0;
509                 $this->affected_rows = 0;
510
511                 // We have to make some things different if this function is called from "e"
512                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
513
514                 if (isset($trace[1])) {
515                         $called_from = $trace[1];
516                 } else {
517                         // We use just something that is defined to avoid warnings
518                         $called_from = $trace[0];
519                 }
520                 // We are having an own error logging in the function "e"
521                 $called_from_e = ($called_from['function'] == 'e');
522
523                 if (!isset($this->connection)) {
524                         throw new InternalServerErrorException('The Connection is empty, although connected is set true.');
525                 }
526
527                 switch ($this->driver) {
528                         case 'pdo':
529                                 // If there are no arguments we use "query"
530                                 if ($this->emulate_prepares || count($args) == 0) {
531                                         if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
532                                                 $errorInfo     = $this->connection->errorInfo();
533                                                 $this->error   = $errorInfo[2];
534                                                 $this->errorno = $errorInfo[1];
535                                                 $retval        = false;
536                                                 break;
537                                         }
538                                         $this->affected_rows = $retval->rowCount();
539                                         break;
540                                 }
541
542                                 /** @var $stmt mysqli_stmt|PDOStatement */
543                                 if (!$stmt = $this->connection->prepare($sql)) {
544                                         $errorInfo     = $this->connection->errorInfo();
545                                         $this->error   = $errorInfo[2];
546                                         $this->errorno = $errorInfo[1];
547                                         $retval        = false;
548                                         break;
549                                 }
550
551                                 foreach ($args AS $param => $value) {
552                                         if (is_int($args[$param])) {
553                                                 $data_type = PDO::PARAM_INT;
554                                         } else {
555                                                 $data_type = PDO::PARAM_STR;
556                                         }
557                                         $stmt->bindParam($param, $args[$param], $data_type);
558                                 }
559
560                                 if (!$stmt->execute()) {
561                                         $errorInfo     = $stmt->errorInfo();
562                                         $this->error   = $errorInfo[2];
563                                         $this->errorno = $errorInfo[1];
564                                         $retval        = false;
565                                 } else {
566                                         $retval              = $stmt;
567                                         $this->affected_rows = $retval->rowCount();
568                                 }
569                                 break;
570                         case 'mysqli':
571                                 // There are SQL statements that cannot be executed with a prepared statement
572                                 $parts           = explode(' ', $orig_sql);
573                                 $command         = strtolower($parts[0]);
574                                 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
575
576                                 // The fallback routine is called as well when there are no arguments
577                                 if ($this->emulate_prepares || !$can_be_prepared || (count($args) == 0)) {
578                                         $retval = $this->connection->query($this->replaceParameters($sql, $args));
579                                         if ($this->connection->errno) {
580                                                 $this->error   = $this->connection->error;
581                                                 $this->errorno = $this->connection->errno;
582                                                 $retval        = false;
583                                         } else {
584                                                 if (isset($retval->num_rows)) {
585                                                         $this->affected_rows = $retval->num_rows;
586                                                 } else {
587                                                         $this->affected_rows = $this->connection->affected_rows;
588                                                 }
589                                         }
590                                         break;
591                                 }
592
593                                 $stmt = $this->connection->stmt_init();
594
595                                 if (!$stmt->prepare($sql)) {
596                                         $this->error   = $stmt->error;
597                                         $this->errorno = $stmt->errno;
598                                         $retval        = false;
599                                         break;
600                                 }
601
602                                 $param_types = '';
603                                 $values      = [];
604                                 foreach ($args AS $param => $value) {
605                                         if (is_int($args[$param])) {
606                                                 $param_types .= 'i';
607                                         } elseif (is_float($args[$param])) {
608                                                 $param_types .= 'd';
609                                         } elseif (is_string($args[$param])) {
610                                                 $param_types .= 's';
611                                         } else {
612                                                 $param_types .= 'b';
613                                         }
614                                         $values[] = &$args[$param];
615                                 }
616
617                                 if (count($values) > 0) {
618                                         array_unshift($values, $param_types);
619                                         call_user_func_array([$stmt, 'bind_param'], $values);
620                                 }
621
622                                 if (!$stmt->execute()) {
623                                         $this->error   = $this->connection->error;
624                                         $this->errorno = $this->connection->errno;
625                                         $retval        = false;
626                                 } else {
627                                         $stmt->store_result();
628                                         $retval              = $stmt;
629                                         $this->affected_rows = $retval->affected_rows;
630                                 }
631                                 break;
632                 }
633
634                 // We are having an own error logging in the function "e"
635                 if (($this->errorno != 0) && !$called_from_e) {
636                         // We have to preserve the error code, somewhere in the logging it get lost
637                         $error   = $this->error;
638                         $errorno = $this->errorno;
639
640                         if ($this->testmode) {
641                                 throw new Exception(DI::l10n()->t('Database error %d "%s" at "%s"', $errorno, $error, $this->replaceParameters($sql, $args)));
642                         }
643
644                         $this->logger->error('DB Error', [
645                                 'code'      => $this->errorno,
646                                 'error'     => $this->error,
647                                 'callstack' => System::callstack(8),
648                                 'params'    => $this->replaceParameters($sql, $args),
649                         ]);
650
651                         // On a lost connection we try to reconnect - but only once.
652                         if ($errorno == 2006) {
653                                 if ($this->in_retrial || !$this->reconnect()) {
654                                         // It doesn't make sense to continue when the database connection was lost
655                                         if ($this->in_retrial) {
656                                                 $this->logger->notice('Giving up retrial because of database error', [
657                                                         'code'  => $this->errorno,
658                                                         'error' => $this->error,
659                                                 ]);
660                                         } else {
661                                                 $this->logger->notice('Couldn\'t reconnect after database error', [
662                                                         'code'  => $this->errorno,
663                                                         'error' => $this->error,
664                                                 ]);
665                                         }
666                                         exit(1);
667                                 } else {
668                                         // We try it again
669                                         $this->logger->notice('Reconnected after database error', [
670                                                 'code'  => $this->errorno,
671                                                 'error' => $this->error,
672                                         ]);
673                                         $this->in_retrial = true;
674                                         $ret              = $this->p($sql, $args);
675                                         $this->in_retrial = false;
676                                         return $ret;
677                                 }
678                         }
679
680                         $this->error   = $error;
681                         $this->errorno = $errorno;
682                 }
683
684                 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
685
686                 if ($this->configCache->get('system', 'db_log')) {
687                         $stamp2   = microtime(true);
688                         $duration = (float)($stamp2 - $stamp1);
689
690                         if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
691                                 $duration  = round($duration, 3);
692                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
693
694                                 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
695                                                                                                 basename($backtrace[1]["file"]) . "\t" .
696                                                                                                 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
697                                                                                                 substr($this->replaceParameters($sql, $args), 0, 2000) . "\n", FILE_APPEND);
698                         }
699                 }
700                 return $retval;
701         }
702
703         /**
704          * Executes a prepared statement like UPDATE or INSERT that doesn't return data
705          *
706          * Please use DBA::delete, DBA::insert, DBA::update, ... instead
707          *
708          * @param string $sql SQL statement
709          *
710          * @return boolean Was the query successfull? False is returned only if an error occurred
711          * @throws \Exception
712          */
713         public function e($sql)
714         {
715
716                 $stamp = microtime(true);
717
718                 $params = DBA::getParam(func_get_args());
719
720                 // In a case of a deadlock we are repeating the query 20 times
721                 $timeout = 20;
722
723                 do {
724                         $stmt = $this->p($sql, $params);
725
726                         if (is_bool($stmt)) {
727                                 $retval = $stmt;
728                         } elseif (is_object($stmt)) {
729                                 $retval = true;
730                         } else {
731                                 $retval = false;
732                         }
733
734                         $this->close($stmt);
735
736                 } while (($this->errorno == 1213) && (--$timeout > 0));
737
738                 if ($this->errorno != 0) {
739                         // We have to preserve the error code, somewhere in the logging it get lost
740                         $error   = $this->error;
741                         $errorno = $this->errorno;
742
743                         $this->logger->error('DB Error', [
744                                 'code'      => $this->errorno,
745                                 'error'     => $this->error,
746                                 'callstack' => System::callstack(8),
747                                 'params'    => $this->replaceParameters($sql, $params),
748                         ]);
749
750                         // On a lost connection we simply quit.
751                         // A reconnect like in $this->p could be dangerous with modifications
752                         if ($errorno == 2006) {
753                                 $this->logger->notice('Giving up because of database error', [
754                                         'code'  => $this->errorno,
755                                         'error' => $this->error,
756                                 ]);
757                                 exit(1);
758                         }
759
760                         $this->error   = $error;
761                         $this->errorno = $errorno;
762                 }
763
764                 $this->profiler->saveTimestamp($stamp, "database_write", System::callstack());
765
766                 return $retval;
767         }
768
769         /**
770          * Check if data exists
771          *
772          * @param string|array $table     Table name or array [schema => table]
773          * @param array        $condition array of fields for condition
774          *
775          * @return boolean Are there rows for that condition?
776          * @throws \Exception
777          */
778         public function exists($table, $condition)
779         {
780                 if (empty($table)) {
781                         return false;
782                 }
783
784                 $fields = [];
785
786                 if (empty($condition)) {
787                         return DBStructure::existsTable($table);
788                 }
789
790                 reset($condition);
791                 $first_key = key($condition);
792                 if (!is_int($first_key)) {
793                         $fields = [$first_key];
794                 }
795
796                 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
797
798                 if (is_bool($stmt)) {
799                         $retval = $stmt;
800                 } else {
801                         $retval = ($this->numRows($stmt) > 0);
802                 }
803
804                 $this->close($stmt);
805
806                 return $retval;
807         }
808
809         /**
810          * Fetches the first row
811          *
812          * Please use DBA::selectFirst or DBA::exists whenever this is possible.
813          *
814          * Fetches the first row
815          *
816          * @param string $sql SQL statement
817          *
818          * @return array first row of query
819          * @throws \Exception
820          */
821         public function fetchFirst($sql)
822         {
823                 $params = DBA::getParam(func_get_args());
824
825                 $stmt = $this->p($sql, $params);
826
827                 if (is_bool($stmt)) {
828                         $retval = $stmt;
829                 } else {
830                         $retval = $this->fetch($stmt);
831                 }
832
833                 $this->close($stmt);
834
835                 return $retval;
836         }
837
838         /**
839          * Returns the number of affected rows of the last statement
840          *
841          * @return int Number of rows
842          */
843         public function affectedRows()
844         {
845                 return $this->affected_rows;
846         }
847
848         /**
849          * Returns the number of columns of a statement
850          *
851          * @param object Statement object
852          *
853          * @return int Number of columns
854          */
855         public function columnCount($stmt)
856         {
857                 if (!is_object($stmt)) {
858                         return 0;
859                 }
860                 switch ($this->driver) {
861                         case 'pdo':
862                                 return $stmt->columnCount();
863                         case 'mysqli':
864                                 return $stmt->field_count;
865                 }
866                 return 0;
867         }
868
869         /**
870          * Returns the number of rows of a statement
871          *
872          * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
873          *
874          * @return int Number of rows
875          */
876         public function numRows($stmt)
877         {
878                 if (!is_object($stmt)) {
879                         return 0;
880                 }
881                 switch ($this->driver) {
882                         case 'pdo':
883                                 return $stmt->rowCount();
884                         case 'mysqli':
885                                 return $stmt->num_rows;
886                 }
887                 return 0;
888         }
889
890         /**
891          * Fetch a single row
892          *
893          * @param mixed $stmt statement object
894          *
895          * @return array current row
896          */
897         public function fetch($stmt)
898         {
899
900                 $stamp1 = microtime(true);
901
902                 $columns = [];
903
904                 if (!is_object($stmt)) {
905                         return false;
906                 }
907
908                 switch ($this->driver) {
909                         case 'pdo':
910                                 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
911                                 break;
912                         case 'mysqli':
913                                 if (get_class($stmt) == 'mysqli_result') {
914                                         $columns = $stmt->fetch_assoc();
915                                         break;
916                                 }
917
918                                 // This code works, but is slow
919
920                                 // Bind the result to a result array
921                                 $cols = [];
922
923                                 $cols_num = [];
924                                 for ($x = 0; $x < $stmt->field_count; $x++) {
925                                         $cols[] = &$cols_num[$x];
926                                 }
927
928                                 call_user_func_array([$stmt, 'bind_result'], $cols);
929
930                                 if (!$stmt->fetch()) {
931                                         return false;
932                                 }
933
934                                 // The slow part:
935                                 // We need to get the field names for the array keys
936                                 // It seems that there is no better way to do this.
937                                 $result = $stmt->result_metadata();
938                                 $fields = $result->fetch_fields();
939
940                                 foreach ($cols_num AS $param => $col) {
941                                         $columns[$fields[$param]->name] = $col;
942                                 }
943                 }
944
945                 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
946
947                 return $columns;
948         }
949
950         /**
951          * Insert a row into a table
952          *
953          * @param string|array $table               Table name or array [schema => table]
954          * @param array        $param               parameter array
955          * @param bool         $on_duplicate_update Do an update on a duplicate entry
956          *
957          * @return boolean was the insert successful?
958          * @throws \Exception
959          */
960         public function insert($table, $param, $on_duplicate_update = false)
961         {
962                 if (empty($table) || empty($param)) {
963                         $this->logger->info('Table and fields have to be set');
964                         return false;
965                 }
966
967                 $table_string = DBA::buildTableString($table);
968
969                 $fields_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
970
971                 $values_string = substr(str_repeat("?, ", count($param)), 0, -2);
972
973                 $sql = "INSERT INTO " . $table_string . " (" . $fields_string . ") VALUES (" . $values_string . ")";
974
975                 if ($on_duplicate_update) {
976                         $fields_string = implode(' = ?, ', array_map([DBA::class, 'quoteIdentifier'], array_keys($param)));
977
978                         $sql .= " ON DUPLICATE KEY UPDATE " . $fields_string . " = ?";
979
980                         $values = array_values($param);
981                         $param  = array_merge_recursive($values, $values);
982                 }
983
984                 return $this->e($sql, $param);
985         }
986
987         /**
988          * Fetch the id of the last insert command
989          *
990          * @return integer Last inserted id
991          */
992         public function lastInsertId()
993         {
994                 switch ($this->driver) {
995                         case 'pdo':
996                                 $id = $this->connection->lastInsertId();
997                                 break;
998                         case 'mysqli':
999                                 $id = $this->connection->insert_id;
1000                                 break;
1001                 }
1002                 return $id;
1003         }
1004
1005         /**
1006          * Locks a table for exclusive write access
1007          *
1008          * This function can be extended in the future to accept a table array as well.
1009          *
1010          * @param string|array $table Table name or array [schema => table]
1011          *
1012          * @return boolean was the lock successful?
1013          * @throws \Exception
1014          */
1015         public function lock($table)
1016         {
1017                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1018                 if ($this->driver == 'pdo') {
1019                         $this->e("SET autocommit=0");
1020                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1021                 } else {
1022                         $this->connection->autocommit(false);
1023                 }
1024
1025                 $success = $this->e("LOCK TABLES " . DBA::buildTableString($table) . " WRITE");
1026
1027                 if ($this->driver == 'pdo') {
1028                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
1029                 }
1030
1031                 if (!$success) {
1032                         if ($this->driver == 'pdo') {
1033                                 $this->e("SET autocommit=1");
1034                         } else {
1035                                 $this->connection->autocommit(true);
1036                         }
1037                 } else {
1038                         $this->in_transaction = true;
1039                 }
1040                 return $success;
1041         }
1042
1043         /**
1044          * Unlocks all locked tables
1045          *
1046          * @return boolean was the unlock successful?
1047          * @throws \Exception
1048          */
1049         public function unlock()
1050         {
1051                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1052                 $this->performCommit();
1053
1054                 if ($this->driver == 'pdo') {
1055                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1056                 }
1057
1058                 $success = $this->e("UNLOCK TABLES");
1059
1060                 if ($this->driver == 'pdo') {
1061                         $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
1062                         $this->e("SET autocommit=1");
1063                 } else {
1064                         $this->connection->autocommit(true);
1065                 }
1066
1067                 $this->in_transaction = false;
1068                 return $success;
1069         }
1070
1071         /**
1072          * Starts a transaction
1073          *
1074          * @return boolean Was the command executed successfully?
1075          */
1076         public function transaction()
1077         {
1078                 if (!$this->performCommit()) {
1079                         return false;
1080                 }
1081
1082                 switch ($this->driver) {
1083                         case 'pdo':
1084                                 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1085                                         return false;
1086                                 }
1087                                 break;
1088
1089                         case 'mysqli':
1090                                 if (!$this->connection->begin_transaction()) {
1091                                         return false;
1092                                 }
1093                                 break;
1094                 }
1095
1096                 $this->in_transaction = true;
1097                 return true;
1098         }
1099
1100         protected function performCommit()
1101         {
1102                 switch ($this->driver) {
1103                         case 'pdo':
1104                                 if (!$this->connection->inTransaction()) {
1105                                         return true;
1106                                 }
1107
1108                                 return $this->connection->commit();
1109
1110                         case 'mysqli':
1111                                 return $this->connection->commit();
1112                 }
1113
1114                 return true;
1115         }
1116
1117         /**
1118          * Does a commit
1119          *
1120          * @return boolean Was the command executed successfully?
1121          */
1122         public function commit()
1123         {
1124                 if (!$this->performCommit()) {
1125                         return false;
1126                 }
1127                 $this->in_transaction = false;
1128                 return true;
1129         }
1130
1131         /**
1132          * Does a rollback
1133          *
1134          * @return boolean Was the command executed successfully?
1135          */
1136         public function rollback()
1137         {
1138                 $ret = false;
1139
1140                 switch ($this->driver) {
1141                         case 'pdo':
1142                                 if (!$this->connection->inTransaction()) {
1143                                         $ret = true;
1144                                         break;
1145                                 }
1146                                 $ret = $this->connection->rollBack();
1147                                 break;
1148
1149                         case 'mysqli':
1150                                 $ret = $this->connection->rollback();
1151                                 break;
1152                 }
1153                 $this->in_transaction = false;
1154                 return $ret;
1155         }
1156
1157         /**
1158          * Build the array with the table relations
1159          *
1160          * The array is build from the database definitions in DBStructure.php
1161          *
1162          * This process must only be started once, since the value is cached.
1163          */
1164         private function buildRelationData()
1165         {
1166                 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1167
1168                 foreach ($definition AS $table => $structure) {
1169                         foreach ($structure['fields'] AS $field => $field_struct) {
1170                                 if (isset($field_struct['relation'])) {
1171                                         foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1172                                                 $this->relation[$rel_table][$rel_field][$table][] = $field;
1173                                         }
1174                                 }
1175                         }
1176                 }
1177         }
1178
1179         /**
1180          * Delete a row from a table
1181          *
1182          * Note: this methods does NOT accept schema => table arrays because of the complex relation stuff.
1183          *
1184          * @param string $table      Table name
1185          * @param array  $conditions Field condition(s)
1186          * @param array  $options
1187          *                           - cascade: If true we delete records in other tables that depend on the one we're deleting through
1188          *                           relations (default: true)
1189          * @param array  $callstack  Internal use: prevent endless loops
1190          *
1191          * @return boolean was the delete successful?
1192          * @throws \Exception
1193          */
1194         public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1195         {
1196                 if (empty($table) || empty($conditions)) {
1197                         $this->logger->info('Table and conditions have to be set');
1198                         return false;
1199                 }
1200
1201                 $commands = [];
1202
1203                 // Create a key for the loop prevention
1204                 $key = $table . ':' . json_encode($conditions);
1205
1206                 // We quit when this key already exists in the callstack.
1207                 if (isset($callstack[$key])) {
1208                         return true;
1209                 }
1210
1211                 $callstack[$key] = true;
1212
1213                 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1214
1215                 // Don't use "defaults" here, since it would set "false" to "true"
1216                 if (isset($options['cascade'])) {
1217                         $cascade = $options['cascade'];
1218                 } else {
1219                         $cascade = true;
1220                 }
1221
1222                 // To speed up the whole process we cache the table relations
1223                 if ($cascade && count($this->relation) == 0) {
1224                         $this->buildRelationData();
1225                 }
1226
1227                 // Is there a relation entry for the table?
1228                 if ($cascade && isset($this->relation[$table])) {
1229                         // We only allow a simple "one field" relation.
1230                         $field   = array_keys($this->relation[$table])[0];
1231                         $rel_def = array_values($this->relation[$table])[0];
1232
1233                         // Create a key for preventing double queries
1234                         $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1235
1236                         // When the search field is the relation field, we don't need to fetch the rows
1237                         // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1238                         if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1239                                 foreach ($rel_def AS $rel_table => $rel_fields) {
1240                                         foreach ($rel_fields AS $rel_field) {
1241                                                 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1242                                         }
1243                                 }
1244                                 // We quit when this key already exists in the callstack.
1245                         } elseif (!isset($callstack[$qkey])) {
1246                                 $callstack[$qkey] = true;
1247
1248                                 // Fetch all rows that are to be deleted
1249                                 $data = $this->select($table, [$field], $conditions);
1250
1251                                 while ($row = $this->fetch($data)) {
1252                                         $this->delete($table, [$field => $row[$field]], $options, $callstack);
1253                                 }
1254
1255                                 $this->close($data);
1256
1257                                 // Since we had split the delete command we don't need the original command anymore
1258                                 unset($commands[$key]);
1259                         }
1260                 }
1261
1262                 // Now we finalize the process
1263                 $do_transaction = !$this->in_transaction;
1264
1265                 if ($do_transaction) {
1266                         $this->transaction();
1267                 }
1268
1269                 $compacted = [];
1270                 $counter   = [];
1271
1272                 foreach ($commands AS $command) {
1273                         $conditions = $command['conditions'];
1274                         reset($conditions);
1275                         $first_key = key($conditions);
1276
1277                         $condition_string = DBA::buildCondition($conditions);
1278
1279                         if ((count($command['conditions']) > 1) || is_int($first_key)) {
1280                                 $sql = "DELETE FROM " . DBA::quoteIdentifier($command['table']) . " " . $condition_string;
1281                                 $this->logger->info($this->replaceParameters($sql, $conditions), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1282
1283                                 if (!$this->e($sql, $conditions)) {
1284                                         if ($do_transaction) {
1285                                                 $this->rollback();
1286                                         }
1287                                         return false;
1288                                 }
1289                         } else {
1290                                 $key_table     = $command['table'];
1291                                 $key_condition = array_keys($command['conditions'])[0];
1292                                 $value         = array_values($command['conditions'])[0];
1293
1294                                 // Split the SQL queries in chunks of 100 values
1295                                 // We do the $i stuff here to make the code better readable
1296                                 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1297                                 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1298                                         ++$i;
1299                                 }
1300
1301                                 $compacted[$key_table][$key_condition][$i][$value] = $value;
1302                                 $counter[$key_table][$key_condition]               = $i;
1303                         }
1304                 }
1305                 foreach ($compacted AS $table => $values) {
1306                         foreach ($values AS $field => $field_value_list) {
1307                                 foreach ($field_value_list AS $field_values) {
1308                                         $sql = "DELETE FROM " . DBA::quoteIdentifier($table) . " WHERE " . DBA::quoteIdentifier($field) . " IN (" .
1309                                                substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1310
1311                                         $this->logger->info($this->replaceParameters($sql, $field_values), ['callstack' => System::callstack(6), 'internal_callstack' => $callstack]);
1312
1313                                         if (!$this->e($sql, $field_values)) {
1314                                                 if ($do_transaction) {
1315                                                         $this->rollback();
1316                                                 }
1317                                                 return false;
1318                                         }
1319                                 }
1320                         }
1321                 }
1322                 if ($do_transaction) {
1323                         $this->commit();
1324                 }
1325                 return true;
1326         }
1327
1328         /**
1329          * Updates rows
1330          *
1331          * Updates rows in the database. When $old_fields is set to an array,
1332          * the system will only do an update if the fields in that array changed.
1333          *
1334          * Attention:
1335          * Only the values in $old_fields are compared.
1336          * This is an intentional behaviour.
1337          *
1338          * Example:
1339          * We include the timestamp field in $fields but not in $old_fields.
1340          * Then the row will only get the new timestamp when the other fields had changed.
1341          *
1342          * When $old_fields is set to a boolean value the system will do this compare itself.
1343          * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1344          *
1345          * Attention:
1346          * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1347          * When you set $old_fields to "true" then $fields must contain all relevant fields!
1348          *
1349          * @param string|array  $table      Table name or array [schema => table]
1350          * @param array         $fields     contains the fields that are updated
1351          * @param array         $condition  condition array with the key values
1352          * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1353          *
1354          * @return boolean was the update successfull?
1355          * @throws \Exception
1356          */
1357         public function update($table, $fields, $condition, $old_fields = [])
1358         {
1359                 if (empty($table) || empty($fields) || empty($condition)) {
1360                         $this->logger->info('Table, fields and condition have to be set');
1361                         return false;
1362                 }
1363
1364                 if (is_bool($old_fields)) {
1365                         $do_insert = $old_fields;
1366
1367                         $old_fields = $this->selectFirst($table, [], $condition);
1368
1369                         if (is_bool($old_fields)) {
1370                                 if ($do_insert) {
1371                                         $values = array_merge($condition, $fields);
1372                                         return $this->insert($table, $values, $do_insert);
1373                                 }
1374                                 $old_fields = [];
1375                         }
1376                 }
1377
1378                 foreach ($old_fields AS $fieldname => $content) {
1379                         if (isset($fields[$fieldname]) && !is_null($content) && ($fields[$fieldname] == $content)) {
1380                                 unset($fields[$fieldname]);
1381                         }
1382                 }
1383
1384                 if (count($fields) == 0) {
1385                         return true;
1386                 }
1387
1388                 $table_string = DBA::buildTableString($table);
1389
1390                 $condition_string = DBA::buildCondition($condition);
1391
1392                 $sql = "UPDATE " . $table_string . " SET "
1393                         . implode(" = ?, ", array_map([DBA::class, 'quoteIdentifier'], array_keys($fields))) . " = ?"
1394                         . $condition_string;
1395
1396                 // Combines the updated fields parameter values with the condition parameter values
1397                 $params  = array_merge(array_values($fields), $condition);
1398
1399                 return $this->e($sql, $params);
1400         }
1401
1402         /**
1403          * Retrieve a single record from a table and returns it in an associative array
1404          *
1405          * @param string|array $table
1406          * @param array        $fields
1407          * @param array        $condition
1408          * @param array        $params
1409          *
1410          * @return bool|array
1411          * @throws \Exception
1412          * @see   $this->select
1413          */
1414         public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1415         {
1416                 $params['limit'] = 1;
1417                 $result          = $this->select($table, $fields, $condition, $params);
1418
1419                 if (is_bool($result)) {
1420                         return $result;
1421                 } else {
1422                         $row = $this->fetch($result);
1423                         $this->close($result);
1424                         return $row;
1425                 }
1426         }
1427
1428         /**
1429          * Select rows from a table and fills an array with the data
1430          *
1431          * @param string|array $table     Table name or array [schema => table]
1432          * @param array        $fields    Array of selected fields, empty for all
1433          * @param array        $condition Array of fields for condition
1434          * @param array        $params    Array of several parameters
1435          *
1436          * @return array Data array
1437          * @throws \Exception
1438          * @see   self::select
1439          */
1440         public function selectToArray($table, array $fields = [], array $condition = [], array $params = [])
1441         {
1442                 return $this->toArray($this->select($table, $fields, $condition, $params));
1443         }
1444
1445         /**
1446          * Select rows from a table
1447          *
1448          * @param string|array $table     Table name or array [schema => table]
1449          * @param array        $fields    Array of selected fields, empty for all
1450          * @param array        $condition Array of fields for condition
1451          * @param array        $params    Array of several parameters
1452          *
1453          * @return boolean|object
1454          *
1455          * Example:
1456          * $table = "item";
1457          * $fields = array("id", "uri", "uid", "network");
1458          *
1459          * $condition = array("uid" => 1, "network" => 'dspr');
1460          * or:
1461          * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1462          *
1463          * $params = array("order" => array("id", "received" => true), "limit" => 10);
1464          *
1465          * $data = DBA::select($table, $fields, $condition, $params);
1466          * @throws \Exception
1467          */
1468         public function select($table, array $fields = [], array $condition = [], array $params = [])
1469         {
1470                 if (empty($table)) {
1471                         return false;
1472                 }
1473
1474                 if (count($fields) > 0) {
1475                         $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $fields));
1476                 } else {
1477                         $select_string = '*';
1478                 }
1479
1480                 $table_string = DBA::buildTableString($table);
1481
1482                 $condition_string = DBA::buildCondition($condition);
1483
1484                 $param_string = DBA::buildParameter($params);
1485
1486                 $sql = "SELECT " . $select_string . " FROM " . $table_string . $condition_string . $param_string;
1487
1488                 $result = $this->p($sql, $condition);
1489
1490                 return $result;
1491         }
1492
1493         /**
1494          * Counts the rows from a table satisfying the provided condition
1495          *
1496          * @param string|array $table     Table name or array [schema => table]
1497          * @param array        $condition Array of fields for condition
1498          * @param array        $params    Array of several parameters
1499          *
1500          * @return int
1501          *
1502          * Example:
1503          * $table = "item";
1504          *
1505          * $condition = ["uid" => 1, "network" => 'dspr'];
1506          * or:
1507          * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1508          *
1509          * $count = DBA::count($table, $condition);
1510          * @throws \Exception
1511          */
1512         public function count($table, array $condition = [], array $params = [])
1513         {
1514                 if (empty($table)) {
1515                         return false;
1516                 }
1517
1518                 $table_string = DBA::buildTableString($table);
1519
1520                 $condition_string = DBA::buildCondition($condition);
1521
1522                 if (empty($params['expression'])) {
1523                         $expression = '*';
1524                 } elseif (!empty($params['distinct'])) {
1525                         $expression = "DISTINCT " . DBA::quoteIdentifier($params['expression']);
1526                 } else {
1527                         $expression = DBA::quoteIdentifier($params['expression']);
1528                 }
1529
1530                 $sql = "SELECT COUNT(" . $expression . ") AS `count` FROM " . $table_string . $condition_string;
1531
1532                 $row = $this->fetchFirst($sql, $condition);
1533
1534                 return $row['count'];
1535         }
1536
1537         /**
1538          * Fills an array with data from a query
1539          *
1540          * @param object $stmt statement object
1541          * @param bool   $do_close
1542          *
1543          * @return array Data array
1544          */
1545         public function toArray($stmt, $do_close = true)
1546         {
1547                 if (is_bool($stmt)) {
1548                         return [];
1549                 }
1550
1551                 $data = [];
1552                 while ($row = $this->fetch($stmt)) {
1553                         $data[] = $row;
1554                 }
1555
1556                 if ($do_close) {
1557                         $this->close($stmt);
1558                 }
1559
1560                 return $data;
1561         }
1562
1563         /**
1564          * Returns the error number of the last query
1565          *
1566          * @return string Error number (0 if no error)
1567          */
1568         public function errorNo()
1569         {
1570                 return $this->errorno;
1571         }
1572
1573         /**
1574          * Returns the error message of the last query
1575          *
1576          * @return string Error message ('' if no error)
1577          */
1578         public function errorMessage()
1579         {
1580                 return $this->error;
1581         }
1582
1583         /**
1584          * Closes the current statement
1585          *
1586          * @param object $stmt statement object
1587          *
1588          * @return boolean was the close successful?
1589          */
1590         public function close($stmt)
1591         {
1592
1593                 $stamp1 = microtime(true);
1594
1595                 if (!is_object($stmt)) {
1596                         return false;
1597                 }
1598
1599                 switch ($this->driver) {
1600                         case 'pdo':
1601                                 $ret = $stmt->closeCursor();
1602                                 break;
1603                         case 'mysqli':
1604                                 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1605                                 // We should be careful not to assume the object type of $stmt
1606                                 // because DBA::p() has been able to return both types.
1607                                 if ($stmt instanceof mysqli_stmt) {
1608                                         $stmt->free_result();
1609                                         $ret = $stmt->close();
1610                                 } elseif ($stmt instanceof mysqli_result) {
1611                                         $stmt->free();
1612                                         $ret = true;
1613                                 } else {
1614                                         $ret = false;
1615                                 }
1616                                 break;
1617                 }
1618
1619                 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
1620
1621                 return $ret;
1622         }
1623
1624         /**
1625          * Return a list of database processes
1626          *
1627          * @return array
1628          *      'list' => List of processes, separated in their different states
1629          *      'amount' => Number of concurrent database processes
1630          * @throws \Exception
1631          */
1632         public function processlist()
1633         {
1634                 $ret  = $this->p("SHOW PROCESSLIST");
1635                 $data = $this->toArray($ret);
1636
1637                 $processes = 0;
1638                 $states    = [];
1639                 foreach ($data as $process) {
1640                         $state = trim($process["State"]);
1641
1642                         // Filter out all non blocking processes
1643                         if (!in_array($state, ["", "init", "statistics", "updating"])) {
1644                                 ++$states[$state];
1645                                 ++$processes;
1646                         }
1647                 }
1648
1649                 $statelist = "";
1650                 foreach ($states as $state => $usage) {
1651                         if ($statelist != "") {
1652                                 $statelist .= ", ";
1653                         }
1654                         $statelist .= $state . ": " . $usage;
1655                 }
1656                 return (["list" => $statelist, "amount" => $processes]);
1657         }
1658
1659         /**
1660          * Fetch a database variable
1661          *
1662          * @param string $name
1663          * @return string content
1664          */
1665         public function getVariable(string $name)
1666         {
1667                 $result = $this->fetchFirst("SHOW GLOBAL VARIABLES WHERE `Variable_name` = ?", $name);
1668                 return $result['Value'] ?? null;
1669         }
1670
1671         /**
1672          * Checks if $array is a filled array with at least one entry.
1673          *
1674          * @param mixed $array A filled array with at least one entry
1675          *
1676          * @return boolean Whether $array is a filled array or an object with rows
1677          */
1678         public function isResult($array)
1679         {
1680                 // It could be a return value from an update statement
1681                 if (is_bool($array)) {
1682                         return $array;
1683                 }
1684
1685                 if (is_object($array)) {
1686                         return $this->numRows($array) > 0;
1687                 }
1688
1689                 return (is_array($array) && (count($array) > 0));
1690         }
1691
1692         /**
1693          * Callback function for "esc_array"
1694          *
1695          * @param mixed   $value         Array value
1696          * @param string  $key           Array key
1697          * @param boolean $add_quotation add quotation marks for string values
1698          *
1699          * @return void
1700          */
1701         private function escapeArrayCallback(&$value, $key, $add_quotation)
1702         {
1703                 if (!$add_quotation) {
1704                         if (is_bool($value)) {
1705                                 $value = ($value ? '1' : '0');
1706                         } else {
1707                                 $value = $this->escape($value);
1708                         }
1709                         return;
1710                 }
1711
1712                 if (is_bool($value)) {
1713                         $value = ($value ? 'true' : 'false');
1714                 } elseif (is_float($value) || is_integer($value)) {
1715                         $value = (string)$value;
1716                 } else {
1717                         $value = "'" . $this->escape($value) . "'";
1718                 }
1719         }
1720
1721         /**
1722          * Escapes a whole array
1723          *
1724          * @param mixed   $arr           Array with values to be escaped
1725          * @param boolean $add_quotation add quotation marks for string values
1726          *
1727          * @return void
1728          */
1729         public function escapeArray(&$arr, $add_quotation = false)
1730         {
1731                 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);
1732         }
1733 }