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