3 namespace Friendica\Database;
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;
9 use Friendica\Core\System;
10 use Friendica\Util\DateTimeFormat;
18 require_once 'include/dba.php';
21 * @class MySQL database class
23 * This class is for the low level database stuff that does driver specific things.
28 * Lowest possible date value
30 const NULL_DATE = '0001-01-01';
32 * Lowest possible datetime value
34 const NULL_DATETIME = '0001-01-01 00:00:00';
36 public static $connected = false;
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 = '';
53 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
55 if (!is_null(self::$connection) && self::connected()) {
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;
64 self::$db_charset = $charset;
67 $serveraddr = trim($serveraddr);
69 $serverdata = explode(':', $serveraddr);
70 $server = $serverdata[0];
72 if (count($serverdata) > 1) {
73 $port = trim($serverdata[1]);
76 $server = trim($server);
80 $charset = trim($charset);
82 if (!(strlen($server) && strlen($user))) {
86 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
87 self::$driver = 'pdo';
88 $connect = "mysql:host=".$server.";dbname=".$db;
91 $connect .= ";port=".$port;
95 $connect .= ";charset=".$charset;
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!
107 if (!self::$connected && class_exists('\mysqli')) {
108 self::$driver = 'mysqli';
111 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
113 self::$connection = @new mysqli($server, $user, $pass, $db);
116 if (!mysqli_connect_errno()) {
117 self::$connected = true;
120 self::$connection->set_charset($charset);
125 // No suitable SQL driver was found.
126 if (!self::$connected) {
127 self::$driver = null;
128 self::$connection = null;
131 return self::$connected;
135 * Disconnects the current database connection
137 public static function disconnect()
139 if (is_null(self::$connection)) {
143 switch (self::$driver) {
145 self::$connection = null;
148 self::$connection->close();
149 self::$connection = null;
155 * Perform a reconnect of an existing database connection
157 public static function reconnect() {
160 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
165 * Return the database object.
168 public static function getConnection()
170 return self::$connection;
174 * @brief Returns the MySQL server version string
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
181 public static function serverInfo() {
182 if (self::$server_info == '') {
183 switch (self::$driver) {
185 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
188 self::$server_info = self::$connection->server_info;
192 return self::$server_info;
196 * @brief Returns the selected database name
200 public static function databaseName() {
201 $ret = self::p("SELECT DATABASE() AS `db`");
202 $data = self::toArray($ret);
203 return $data[0]['db'];
207 * @brief Analyze a database query and log this if some conditions are met.
209 * @param string $query The database query that will be analyzed
211 private static function logIndex($query) {
214 if (!$a->getConfigVariable('system', 'db_log_index')) {
218 // Don't explain an explain statement
219 if (strtolower(substr($query, 0, 7)) == "explain") {
223 // Only do the explain on "select", "update" and "delete"
224 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
228 $r = self::p("EXPLAIN ".$query);
229 if (!self::isResult($r)) {
233 $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch'));
234 $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist'));
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'))));
244 if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) {
248 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
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);
263 public static function escape($str) {
264 if (self::$connected) {
265 switch (self::$driver) {
267 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
270 return @self::$connection->real_escape_string($str);
273 return str_replace("'", "\\'", $str);
277 public static function connected() {
280 if (is_null(self::$connection)) {
284 switch (self::$driver) {
286 $r = self::p("SELECT 1");
287 if (self::isResult($r)) {
288 $row = self::toArray($r);
289 $connected = ($row[0]['1'] == '1');
293 $connected = self::$connection->ping();
300 * @brief Replaces ANY_VALUE() function by MIN() function,
301 * if the database server does not support ANY_VALUE().
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().
307 * @param string $sql An SQL string without the values
308 * @return string The input SQL string modified if necessary.
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);
320 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
322 * This is safe when we bind the parameters later.
323 * The parameter values aren't part of the SQL.
325 * @param string $sql An SQL string without the values
326 * @return string The input SQL string modified if necessary.
328 public static function cleanQuery($sql) {
329 $search = ["\t", "\n", "\r", " "];
330 $replace = [' ', ' ', ' ', ' '];
333 $sql = str_replace($search, $replace, $sql);
334 } while ($oldsql != $sql);
341 * @brief Replaces the ? placeholders with the parameters in the $args array
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
347 private static function replaceParameters($sql, $args) {
349 foreach ($args AS $param => $value) {
350 if (is_int($args[$param]) || is_float($args[$param])) {
351 $replace = intval($args[$param]);
353 $replace = "'".self::escape($args[$param])."'";
356 $pos = strpos($sql, '?', $offset);
357 if ($pos !== false) {
358 $sql = substr_replace($sql, $replace, $pos, 1);
360 $offset = $pos + strlen($replace);
366 * @brief Convert parameter array to an universal form
367 * @param array $args Parameter array
368 * @return array universalized parameter array
370 private static function getParam($args) {
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]))) {
382 * @brief Executes a prepared statement that returns data
383 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
385 * Please only use it with complicated queries.
386 * For all regular queries please use DBA::select or DBA::exists
388 * @param string $sql SQL statement
389 * @return bool|object statement object or result object
391 public static function p($sql) {
394 $stamp1 = microtime(true);
396 $params = self::getParam(func_get_args());
398 // Renumber the array keys to be sure that they fit
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;
406 $args[++$i] = $param;
409 if (!self::$connected) {
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);
418 $sql = self::cleanQuery($sql);
419 $sql = self::anyValueFallback($sql);
423 if ($a->getConfigValue('system', 'db_callstack')) {
424 $sql = "/*".System::callstack()." */ ".$sql;
429 self::$affected_rows = 0;
431 // We have to make some things different if this function is called from "e"
432 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
434 if (isset($trace[1])) {
435 $called_from = $trace[1];
437 // We use just something that is defined to avoid warnings
438 $called_from = $trace[0];
440 // We are having an own error logging in the function "e"
441 $called_from_e = ($called_from['function'] == 'e');
443 switch (self::$driver) {
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];
454 self::$affected_rows = $retval->rowCount();
458 if (!$stmt = self::$connection->prepare($sql)) {
459 $errorInfo = self::$connection->errorInfo();
460 self::$error = $errorInfo[2];
461 self::$errorno = $errorInfo[1];
466 foreach ($args AS $param => $value) {
467 if (is_int($args[$param])) {
468 $data_type = PDO::PARAM_INT;
470 $data_type = PDO::PARAM_STR;
472 $stmt->bindParam($param, $args[$param], $data_type);
475 if (!$stmt->execute()) {
476 $errorInfo = $stmt->errorInfo();
477 self::$error = $errorInfo[2];
478 self::$errorno = $errorInfo[1];
482 self::$affected_rows = $retval->rowCount();
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']);
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;
499 if (isset($retval->num_rows)) {
500 self::$affected_rows = $retval->num_rows;
502 self::$affected_rows = self::$connection->affected_rows;
508 $stmt = self::$connection->stmt_init();
510 if (!$stmt->prepare($sql)) {
511 self::$error = $stmt->error;
512 self::$errorno = $stmt->errno;
519 foreach ($args AS $param => $value) {
520 if (is_int($args[$param])) {
522 } elseif (is_float($args[$param])) {
524 } elseif (is_string($args[$param])) {
529 $values[] = &$args[$param];
532 if (count($values) > 0) {
533 array_unshift($values, $param_types);
534 call_user_func_array([$stmt, 'bind_param'], $values);
537 if (!$stmt->execute()) {
538 self::$error = self::$connection->error;
539 self::$errorno = self::$connection->errno;
542 $stmt->store_result();
544 self::$affected_rows = $retval->affected_rows;
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;
555 logger('DB Error '.self::$errorno.': '.self::$error."\n".
556 System::callstack(8)."\n".self::replaceParameters($sql, $args));
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);
565 logger("Couldn't reconnect after database error ".$errorno.': '.$error);
570 logger('Reconnected after database error '.$errorno.': '.$error);
571 self::$in_retrial = true;
572 $ret = self::p($sql, $args);
573 self::$in_retrial = false;
578 self::$error = $error;
579 self::$errorno = $errorno;
582 $a->saveTimestamp($stamp1, 'database');
584 if ($a->getConfigValue('system', 'db_log')) {
585 $stamp2 = microtime(true);
586 $duration = (float)($stamp2 - $stamp1);
588 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
589 $duration = round($duration, 3);
590 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
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);
602 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
604 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
606 * @param string $sql SQL statement
607 * @return boolean Was the query successfull? False is returned only if an error occurred
609 public static function e($sql) {
612 $stamp = microtime(true);
614 $params = self::getParam(func_get_args());
616 // In a case of a deadlock we are repeating the query 20 times
620 $stmt = self::p($sql, $params);
622 if (is_bool($stmt)) {
624 } elseif (is_object($stmt)) {
632 } while ((self::$errorno == 1213) && (--$timeout > 0));
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;
639 logger('DB Error '.self::$errorno.': '.self::$error."\n".
640 System::callstack(8)."\n".self::replaceParameters($sql, $params));
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);
649 self::$error = $error;
650 self::$errorno = $errorno;
653 $a->saveTimestamp($stamp, "database_write");
659 * @brief Check if data exists
661 * @param string $table Table name
662 * @param array $condition array of fields for condition
664 * @return boolean Are there rows for that condition?
666 public static function exists($table, $condition) {
673 if (empty($condition)) {
674 return DBStructure::existsTable($table);
678 $first_key = key($condition);
679 if (!is_int($first_key)) {
680 $fields = [$first_key];
683 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
685 if (is_bool($stmt)) {
688 $retval = (self::numRows($stmt) > 0);
697 * Fetches the first row
699 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
701 * @brief Fetches the first row
702 * @param string $sql SQL statement
703 * @return array first row of query
705 public static function fetchFirst($sql) {
706 $params = self::getParam(func_get_args());
708 $stmt = self::p($sql, $params);
710 if (is_bool($stmt)) {
713 $retval = self::fetch($stmt);
722 * @brief Returns the number of affected rows of the last statement
724 * @return int Number of rows
726 public static function affectedRows() {
727 return self::$affected_rows;
731 * @brief Returns the number of columns of a statement
733 * @param object Statement object
734 * @return int Number of columns
736 public static function columnCount($stmt) {
737 if (!is_object($stmt)) {
740 switch (self::$driver) {
742 return $stmt->columnCount();
744 return $stmt->field_count;
749 * @brief Returns the number of rows of a statement
751 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
752 * @return int Number of rows
754 public static function numRows($stmt) {
755 if (!is_object($stmt)) {
758 switch (self::$driver) {
760 return $stmt->rowCount();
762 return $stmt->num_rows;
768 * @brief Fetch a single row
770 * @param mixed $stmt statement object
771 * @return array current row
773 public static function fetch($stmt) {
776 $stamp1 = microtime(true);
780 if (!is_object($stmt)) {
784 switch (self::$driver) {
786 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
789 if (get_class($stmt) == 'mysqli_result') {
790 $columns = $stmt->fetch_assoc();
794 // This code works, but is slow
796 // Bind the result to a result array
800 for ($x = 0; $x < $stmt->field_count; $x++) {
801 $cols[] = &$cols_num[$x];
804 call_user_func_array([$stmt, 'bind_result'], $cols);
806 if (!$stmt->fetch()) {
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();
816 foreach ($cols_num AS $param => $col) {
817 $columns[$fields[$param]->name] = $col;
821 $a->saveTimestamp($stamp1, 'database');
827 * @brief Insert a row into a table
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
833 * @return boolean was the insert successful?
835 public static function insert($table, $param, $on_duplicate_update = false) {
837 if (empty($table) || empty($param)) {
838 logger('Table and fields have to be set');
842 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
843 substr(str_repeat("?, ", count($param)), 0, -2).")";
845 if ($on_duplicate_update) {
846 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
848 $values = array_values($param);
849 $param = array_merge_recursive($values, $values);
852 return self::e($sql, $param);
856 * @brief Fetch the id of the last insert command
858 * @return integer Last inserted id
860 public static function lastInsertId() {
861 switch (self::$driver) {
863 $id = self::$connection->lastInsertId();
866 $id = self::$connection->insert_id;
873 * @brief Locks a table for exclusive write access
875 * This function can be extended in the future to accept a table array as well.
877 * @param string $table Table name
879 * @return boolean was the lock successful?
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);
887 self::$connection->autocommit(false);
890 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
892 if (self::$driver == 'pdo') {
893 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
897 if (self::$driver == 'pdo') {
898 self::e("SET autocommit=1");
900 self::$connection->autocommit(true);
903 self::$in_transaction = true;
909 * @brief Unlocks all locked tables
911 * @return boolean was the unlock successful?
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();
917 if (self::$driver == 'pdo') {
918 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
921 $success = self::e("UNLOCK TABLES");
923 if (self::$driver == 'pdo') {
924 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
925 self::e("SET autocommit=1");
927 self::$connection->autocommit(true);
930 self::$in_transaction = false;
935 * @brief Starts a transaction
937 * @return boolean Was the command executed successfully?
939 public static function transaction() {
940 if (!self::performCommit()) {
944 switch (self::$driver) {
946 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
952 if (!self::$connection->begin_transaction()) {
958 self::$in_transaction = true;
962 private static function performCommit()
964 switch (self::$driver) {
966 if (!self::$connection->inTransaction()) {
970 return self::$connection->commit();
973 return self::$connection->commit();
980 * @brief Does a commit
982 * @return boolean Was the command executed successfully?
984 public static function commit() {
985 if (!self::performCommit()) {
988 self::$in_transaction = false;
993 * @brief Does a rollback
995 * @return boolean Was the command executed successfully?
997 public static function rollback() {
1000 switch (self::$driver) {
1002 if (!self::$connection->inTransaction()) {
1006 $ret = self::$connection->rollBack();
1010 $ret = self::$connection->rollback();
1013 self::$in_transaction = false;
1018 * @brief Build the array with the table relations
1020 * The array is build from the database definitions in DBStructure.php
1022 * This process must only be started once, since the value is cached.
1024 private static function buildRelationData() {
1025 $definition = DBStructure::definition();
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;
1039 * @brief Delete a row from a table
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
1049 * @return boolean|array was the delete successful? When $in_process is set: deletion data
1051 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
1053 if (empty($table) || empty($conditions)) {
1054 logger('Table and conditions have to be set');
1060 // Create a key for the loop prevention
1061 $key = $table . ':' . json_encode($conditions);
1063 // We quit when this key already exists in the callstack.
1064 if (isset($callstack[$key])) {
1068 $callstack[$key] = true;
1070 $table = self::escape($table);
1072 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1074 // Don't use "defaults" here, since it would set "false" to "true"
1075 if (isset($options['cascade'])) {
1076 $cascade = $options['cascade'];
1081 // To speed up the whole process we cache the table relations
1082 if ($cascade && count(self::$relation) == 0) {
1083 self::buildRelationData();
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];
1092 // Create a key for preventing double queries
1093 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
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);
1104 // We quit when this key already exists in the callstack.
1105 } elseif (!isset($callstack[$qkey])) {
1107 $callstack[$qkey] = true;
1109 // Fetch all rows that are to be deleted
1110 $data = self::select($table, [$field], $conditions);
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);
1120 // Since we had split the delete command we don't need the original command anymore
1121 unset($commands[$key]);
1126 // Now we finalize the process
1127 $do_transaction = !self::$in_transaction;
1129 if ($do_transaction) {
1130 self::transaction();
1136 foreach ($commands AS $command) {
1137 $conditions = $command['conditions'];
1139 $first_key = key($conditions);
1141 $condition_string = self::buildCondition($conditions);
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);
1147 if (!self::e($sql, $conditions)) {
1148 if ($do_transaction) {
1154 $key_table = $command['table'];
1155 $key_condition = array_keys($command['conditions'])[0];
1156 $value = array_values($command['conditions'])[0];
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) {
1165 $compacted[$key_table][$key_condition][$i][$value] = $value;
1166 $counter[$key_table][$key_condition] = $i;
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) . ");";
1175 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1177 if (!self::e($sql, $field_values)) {
1178 if ($do_transaction) {
1186 if ($do_transaction) {
1196 * @brief Updates rows
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.
1202 * Only the values in $old_fields are compared.
1203 * This is an intentional behaviour.
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.
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.
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!
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)
1221 * @return boolean was the update successfull?
1223 public static function update($table, $fields, $condition, $old_fields = []) {
1225 if (empty($table) || empty($fields) || empty($condition)) {
1226 logger('Table, fields and condition have to be set');
1230 $table = self::escape($table);
1232 $condition_string = self::buildCondition($condition);
1234 if (is_bool($old_fields)) {
1235 $do_insert = $old_fields;
1237 $old_fields = self::selectFirst($table, [], $condition);
1239 if (is_bool($old_fields)) {
1241 $values = array_merge($condition, $fields);
1242 return self::insert($table, $values, $do_insert);
1248 $do_update = (count($old_fields) == 0);
1250 foreach ($old_fields AS $fieldname => $content) {
1251 if (isset($fields[$fieldname])) {
1252 if ($fields[$fieldname] == $content) {
1253 unset($fields[$fieldname]);
1260 if (!$do_update || (count($fields) == 0)) {
1264 $sql = "UPDATE `".$table."` SET `".
1265 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1267 $params1 = array_values($fields);
1268 $params2 = array_values($condition);
1269 $params = array_merge_recursive($params1, $params2);
1271 return self::e($sql, $params);
1275 * Retrieve a single record from a table and returns it in an associative array
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
1285 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1287 $params['limit'] = 1;
1288 $result = self::select($table, $fields, $condition, $params);
1290 if (is_bool($result)) {
1293 $row = self::fetch($result);
1294 self::close($result);
1300 * @brief Select rows from a table
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
1307 * @return boolean|object
1311 * $fields = array("id", "uri", "uid", "network");
1313 * $condition = array("uid" => 1, "network" => 'dspr');
1315 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1317 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1319 * $data = DBA::select($table, $fields, $condition, $params);
1321 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1327 $table = self::escape($table);
1329 if (count($fields) > 0) {
1330 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1332 $select_fields = "*";
1335 $condition_string = self::buildCondition($condition);
1337 $param_string = self::buildParameter($params);
1339 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1341 $result = self::p($sql, $condition);
1347 * @brief Counts the rows from a table satisfying the provided condition
1349 * @param string $table Table name
1350 * @param array $condition array of fields for condition
1357 * $condition = ["uid" => 1, "network" => 'dspr'];
1359 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1361 * $count = DBA::count($table, $condition);
1363 public static function count($table, array $condition = [])
1369 $condition_string = self::buildCondition($condition);
1371 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1373 $row = self::fetchFirst($sql, $condition);
1375 return $row['count'];
1379 * @brief Returns the SQL condition string built from the provided condition array
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
1387 * $condition = ["uid" => 1, "network" => 'dspr'];
1389 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1391 * In either case, the provided array is left with the parameters only
1393 * @param array $condition
1396 public static function buildCondition(array &$condition = [])
1398 $condition_string = '';
1399 if (count($condition) > 0) {
1401 $first_key = key($condition);
1402 if (is_int($first_key)) {
1403 $condition_string = " WHERE (" . array_shift($condition) . ")";
1406 $condition_string = "";
1407 foreach ($condition as $field => $value) {
1408 if ($condition_string != "") {
1409 $condition_string .= " AND ";
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.
1419 foreach ($value as $single_value) {
1420 if (is_int($single_value)) {
1427 if ($is_int && $is_alpha) {
1428 foreach ($value as &$ref) {
1430 $ref = (string)$ref;
1433 unset($ref); //Prevent accidental re-use.
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 . ")";
1440 $new_values[$field] = $value;
1441 $condition_string .= "`" . $field . "` = ?";
1444 $condition_string = " WHERE (" . $condition_string . ")";
1445 $condition = $new_values;
1449 return $condition_string;
1453 * @brief Returns the SQL parameter string built from the provided parameter array
1455 * @param array $params
1458 public static function buildParameter(array $params = [])
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") . ", ";
1467 $order_string .= "`" . $order . "`, ";
1470 $order_string = substr($order_string, 0, -2);
1474 if (isset($params['limit']) && is_int($params['limit'])) {
1475 $limit_string = " LIMIT " . intval($params['limit']);
1478 if (isset($params['limit']) && is_array($params['limit'])) {
1479 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1482 return $order_string.$limit_string;
1486 * @brief Fills an array with data from a query
1488 * @param object $stmt statement object
1489 * @return array Data array
1491 public static function toArray($stmt, $do_close = true) {
1492 if (is_bool($stmt)) {
1497 while ($row = self::fetch($stmt)) {
1507 * @brief Returns the error number of the last query
1509 * @return string Error number (0 if no error)
1511 public static function errorNo() {
1512 return self::$errorno;
1516 * @brief Returns the error message of the last query
1518 * @return string Error message ('' if no error)
1520 public static function errorMessage() {
1521 return self::$error;
1525 * @brief Closes the current statement
1527 * @param object $stmt statement object
1528 * @return boolean was the close successful?
1530 public static function close($stmt) {
1533 $stamp1 = microtime(true);
1535 if (!is_object($stmt)) {
1539 switch (self::$driver) {
1541 $ret = $stmt->closeCursor();
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) {
1559 $a->saveTimestamp($stamp1, 'database');
1565 * @brief Return a list of database processes
1568 * 'list' => List of processes, separated in their different states
1569 * 'amount' => Number of concurrent database processes
1571 public static function processlist()
1573 $ret = self::p("SHOW PROCESSLIST");
1574 $data = self::toArray($ret);
1580 foreach ($data as $process) {
1581 $state = trim($process["State"]);
1583 // Filter out all non blocking processes
1584 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1591 foreach ($states as $state => $usage) {
1592 if ($statelist != "") {
1595 $statelist .= $state.": ".$usage;
1597 return(["list" => $statelist, "amount" => $processes]);
1601 * Checks if $array is a filled array with at least one entry.
1603 * @param mixed $array A filled array with at least one entry
1605 * @return boolean Whether $array is a filled array or an object with rows
1607 public static function isResult($array)
1609 // It could be a return value from an update statement
1610 if (is_bool($array)) {
1614 if (is_object($array)) {
1615 return self::numRows($array) > 0;
1618 return (is_array($array) && (count($array) > 0));
1622 * @brief Callback function for "esc_array"
1624 * @param mixed $value Array value
1625 * @param string $key Array key
1626 * @param boolean $add_quotation add quotation marks for string values
1629 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1631 if (!$add_quotation) {
1632 if (is_bool($value)) {
1633 $value = ($value ? '1' : '0');
1635 $value = self::escape($value);
1640 if (is_bool($value)) {
1641 $value = ($value ? 'true' : 'false');
1642 } elseif (is_float($value) || is_integer($value)) {
1643 $value = (string) $value;
1645 $value = "'" . self::escape($value) . "'";
1650 * @brief Escapes a whole array
1652 * @param mixed $arr Array with values to be escaped
1653 * @param boolean $add_quotation add quotation marks for string values
1656 public static function escapeArray(&$arr, $add_quotation = false)
1658 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);