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