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