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\Logger;
10 use Friendica\Core\System;
11 use Friendica\Util\DateTimeFormat;
20 * @class MySQL database class
22 * This class is for the low level database stuff that does driver specific things.
27 * Lowest possible date value
29 const NULL_DATE = '0001-01-01';
31 * Lowest possible datetime value
33 const NULL_DATETIME = '0001-01-01 00:00:00';
35 public static $connected = false;
37 private static $server_info = '';
38 private static $connection;
39 private static $driver;
40 private static $error = false;
41 private static $errorno = 0;
42 private static $affected_rows = 0;
43 private static $in_transaction = false;
44 private static $in_retrial = false;
45 private static $relation = [];
46 private static $db_serveraddr = '';
47 private static $db_user = '';
48 private static $db_pass = '';
49 private static $db_name = '';
50 private static $db_charset = '';
52 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
54 if (!is_null(self::$connection) && self::connected()) {
58 // We are storing these values for being able to perform a reconnect
59 self::$db_serveraddr = $serveraddr;
60 self::$db_user = $user;
61 self::$db_pass = $pass;
63 self::$db_charset = $charset;
66 $serveraddr = trim($serveraddr);
68 $serverdata = explode(':', $serveraddr);
69 $server = $serverdata[0];
71 if (count($serverdata) > 1) {
72 $port = trim($serverdata[1]);
75 $server = trim($server);
79 $charset = trim($charset);
81 if (!(strlen($server) && strlen($user))) {
85 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
86 self::$driver = 'pdo';
87 $connect = "mysql:host=".$server.";dbname=".$db;
90 $connect .= ";port=".$port;
94 $connect .= ";charset=".$charset;
98 self::$connection = @new PDO($connect, $user, $pass);
99 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
100 self::$connected = true;
101 } catch (PDOException $e) {
102 /// @TODO At least log exception, don't ignore it!
106 if (!self::$connected && class_exists('\mysqli')) {
107 self::$driver = 'mysqli';
110 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
112 self::$connection = @new mysqli($server, $user, $pass, $db);
115 if (!mysqli_connect_errno()) {
116 self::$connected = true;
119 self::$connection->set_charset($charset);
124 // No suitable SQL driver was found.
125 if (!self::$connected) {
126 self::$driver = null;
127 self::$connection = null;
130 return self::$connected;
134 * Disconnects the current database connection
136 public static function disconnect()
138 if (is_null(self::$connection)) {
142 switch (self::$driver) {
144 self::$connection = null;
147 self::$connection->close();
148 self::$connection = null;
154 * Perform a reconnect of an existing database connection
156 public static function reconnect() {
159 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
164 * Return the database object.
167 public static function getConnection()
169 return self::$connection;
173 * @brief Returns the MySQL server version string
175 * This function discriminate between the deprecated mysql API and the current
176 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
180 public static function serverInfo() {
181 if (self::$server_info == '') {
182 switch (self::$driver) {
184 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
187 self::$server_info = self::$connection->server_info;
191 return self::$server_info;
195 * @brief Returns the selected database name
199 public static function databaseName() {
200 $ret = self::p("SELECT DATABASE() AS `db`");
201 $data = self::toArray($ret);
202 return $data[0]['db'];
206 * @brief Analyze a database query and log this if some conditions are met.
208 * @param string $query The database query that will be analyzed
210 private static function logIndex($query) {
213 if (!$a->getConfigVariable('system', 'db_log_index')) {
217 // Don't explain an explain statement
218 if (strtolower(substr($query, 0, 7)) == "explain") {
222 // Only do the explain on "select", "update" and "delete"
223 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
227 $r = self::p("EXPLAIN ".$query);
228 if (!self::isResult($r)) {
232 $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch'));
233 $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist'));
235 while ($row = self::fetch($r)) {
236 if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) {
237 $log = (in_array($row['key'], $watchlist) &&
238 ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index'))));
243 if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) {
247 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
252 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
253 @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
254 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
255 basename($backtrace[1]["file"])."\t".
256 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
257 substr($query, 0, 2000)."\n", FILE_APPEND);
262 public static function escape($str) {
263 if (self::$connected) {
264 switch (self::$driver) {
266 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
269 return @self::$connection->real_escape_string($str);
272 return str_replace("'", "\\'", $str);
276 public static function connected() {
279 if (is_null(self::$connection)) {
283 switch (self::$driver) {
285 $r = self::p("SELECT 1");
286 if (self::isResult($r)) {
287 $row = self::toArray($r);
288 $connected = ($row[0]['1'] == '1');
292 $connected = self::$connection->ping();
299 * @brief Replaces ANY_VALUE() function by MIN() function,
300 * if the database server does not support ANY_VALUE().
302 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
303 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
304 * A standard fall-back is to use MIN().
306 * @param string $sql An SQL string without the values
307 * @return string The input SQL string modified if necessary.
309 public static function anyValueFallback($sql) {
310 $server_info = self::serverInfo();
311 if (version_compare($server_info, '5.7.5', '<') ||
312 (stripos($server_info, 'MariaDB') !== false)) {
313 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
319 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
321 * This is safe when we bind the parameters later.
322 * The parameter values aren't part of the SQL.
324 * @param string $sql An SQL string without the values
325 * @return string The input SQL string modified if necessary.
327 public static function cleanQuery($sql) {
328 $search = ["\t", "\n", "\r", " "];
329 $replace = [' ', ' ', ' ', ' '];
332 $sql = str_replace($search, $replace, $sql);
333 } while ($oldsql != $sql);
340 * @brief Replaces the ? placeholders with the parameters in the $args array
342 * @param string $sql SQL query
343 * @param array $args The parameters that are to replace the ? placeholders
344 * @return string The replaced SQL query
346 private static function replaceParameters($sql, $args) {
348 foreach ($args AS $param => $value) {
349 if (is_int($args[$param]) || is_float($args[$param])) {
350 $replace = intval($args[$param]);
352 $replace = "'".self::escape($args[$param])."'";
355 $pos = strpos($sql, '?', $offset);
356 if ($pos !== false) {
357 $sql = substr_replace($sql, $replace, $pos, 1);
359 $offset = $pos + strlen($replace);
365 * @brief Convert parameter array to an universal form
366 * @param array $args Parameter array
367 * @return array universalized parameter array
369 private static function getParam($args) {
372 // When the second function parameter is an array then use this as the parameter array
373 if ((count($args) > 0) && (is_array($args[1]))) {
381 * @brief Executes a prepared statement that returns data
382 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
384 * Please only use it with complicated queries.
385 * For all regular queries please use DBA::select or DBA::exists
387 * @param string $sql SQL statement
388 * @return bool|object statement object or result object
390 public static function p($sql) {
393 $stamp1 = microtime(true);
395 $params = self::getParam(func_get_args());
397 // Renumber the array keys to be sure that they fit
400 foreach ($params AS $param) {
401 // Avoid problems with some MySQL servers and boolean values. See issue #3645
402 if (is_bool($param)) {
403 $param = (int)$param;
405 $args[++$i] = $param;
408 if (!self::$connected) {
412 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
413 // Question: Should we continue or stop the query here?
414 Logger::log('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), Logger::DEBUG);
417 $sql = self::cleanQuery($sql);
418 $sql = self::anyValueFallback($sql);
422 if ($a->getConfigValue('system', 'db_callstack')) {
423 $sql = "/*".System::callstack()." */ ".$sql;
428 self::$affected_rows = 0;
430 // We have to make some things different if this function is called from "e"
431 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
433 if (isset($trace[1])) {
434 $called_from = $trace[1];
436 // We use just something that is defined to avoid warnings
437 $called_from = $trace[0];
439 // We are having an own error logging in the function "e"
440 $called_from_e = ($called_from['function'] == 'e');
442 switch (self::$driver) {
444 // If there are no arguments we use "query"
445 if (count($args) == 0) {
446 if (!$retval = self::$connection->query($sql)) {
447 $errorInfo = self::$connection->errorInfo();
448 self::$error = $errorInfo[2];
449 self::$errorno = $errorInfo[1];
453 self::$affected_rows = $retval->rowCount();
457 if (!$stmt = self::$connection->prepare($sql)) {
458 $errorInfo = self::$connection->errorInfo();
459 self::$error = $errorInfo[2];
460 self::$errorno = $errorInfo[1];
465 foreach ($args AS $param => $value) {
466 if (is_int($args[$param])) {
467 $data_type = PDO::PARAM_INT;
469 $data_type = PDO::PARAM_STR;
471 $stmt->bindParam($param, $args[$param], $data_type);
474 if (!$stmt->execute()) {
475 $errorInfo = $stmt->errorInfo();
476 self::$error = $errorInfo[2];
477 self::$errorno = $errorInfo[1];
481 self::$affected_rows = $retval->rowCount();
485 // There are SQL statements that cannot be executed with a prepared statement
486 $parts = explode(' ', $orig_sql);
487 $command = strtolower($parts[0]);
488 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
490 // The fallback routine is called as well when there are no arguments
491 if (!$can_be_prepared || (count($args) == 0)) {
492 $retval = self::$connection->query(self::replaceParameters($sql, $args));
493 if (self::$connection->errno) {
494 self::$error = self::$connection->error;
495 self::$errorno = self::$connection->errno;
498 if (isset($retval->num_rows)) {
499 self::$affected_rows = $retval->num_rows;
501 self::$affected_rows = self::$connection->affected_rows;
507 $stmt = self::$connection->stmt_init();
509 if (!$stmt->prepare($sql)) {
510 self::$error = $stmt->error;
511 self::$errorno = $stmt->errno;
518 foreach ($args AS $param => $value) {
519 if (is_int($args[$param])) {
521 } elseif (is_float($args[$param])) {
523 } elseif (is_string($args[$param])) {
528 $values[] = &$args[$param];
531 if (count($values) > 0) {
532 array_unshift($values, $param_types);
533 call_user_func_array([$stmt, 'bind_param'], $values);
536 if (!$stmt->execute()) {
537 self::$error = self::$connection->error;
538 self::$errorno = self::$connection->errno;
541 $stmt->store_result();
543 self::$affected_rows = $retval->affected_rows;
548 // We are having an own error logging in the function "e"
549 if ((self::$errorno != 0) && !$called_from_e) {
550 // We have to preserve the error code, somewhere in the logging it get lost
551 $error = self::$error;
552 $errorno = self::$errorno;
554 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
555 System::callstack(8)."\n".self::replaceParameters($sql, $args));
557 // On a lost connection we try to reconnect - but only once.
558 if ($errorno == 2006) {
559 if (self::$in_retrial || !self::reconnect()) {
560 // It doesn't make sense to continue when the database connection was lost
561 if (self::$in_retrial) {
562 Logger::log('Giving up retrial because of database error '.$errorno.': '.$error);
564 Logger::log("Couldn't reconnect after database error ".$errorno.': '.$error);
569 Logger::log('Reconnected after database error '.$errorno.': '.$error);
570 self::$in_retrial = true;
571 $ret = self::p($sql, $args);
572 self::$in_retrial = false;
577 self::$error = $error;
578 self::$errorno = $errorno;
581 $a->saveTimestamp($stamp1, 'database');
583 if ($a->getConfigValue('system', 'db_log')) {
584 $stamp2 = microtime(true);
585 $duration = (float)($stamp2 - $stamp1);
587 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
588 $duration = round($duration, 3);
589 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
591 @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
592 basename($backtrace[1]["file"])."\t".
593 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
594 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
601 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
603 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
605 * @param string $sql SQL statement
606 * @return boolean Was the query successfull? False is returned only if an error occurred
608 public static function e($sql) {
611 $stamp = microtime(true);
613 $params = self::getParam(func_get_args());
615 // In a case of a deadlock we are repeating the query 20 times
619 $stmt = self::p($sql, $params);
621 if (is_bool($stmt)) {
623 } elseif (is_object($stmt)) {
631 } while ((self::$errorno == 1213) && (--$timeout > 0));
633 if (self::$errorno != 0) {
634 // We have to preserve the error code, somewhere in the logging it get lost
635 $error = self::$error;
636 $errorno = self::$errorno;
638 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
639 System::callstack(8)."\n".self::replaceParameters($sql, $params));
641 // On a lost connection we simply quit.
642 // A reconnect like in self::p could be dangerous with modifications
643 if ($errorno == 2006) {
644 Logger::log('Giving up because of database error '.$errorno.': '.$error);
648 self::$error = $error;
649 self::$errorno = $errorno;
652 $a->saveTimestamp($stamp, "database_write");
658 * @brief Check if data exists
660 * @param string $table Table name
661 * @param array $condition array of fields for condition
663 * @return boolean Are there rows for that condition?
665 public static function exists($table, $condition) {
672 if (empty($condition)) {
673 return DBStructure::existsTable($table);
677 $first_key = key($condition);
678 if (!is_int($first_key)) {
679 $fields = [$first_key];
682 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
684 if (is_bool($stmt)) {
687 $retval = (self::numRows($stmt) > 0);
696 * Fetches the first row
698 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
700 * @brief Fetches the first row
701 * @param string $sql SQL statement
702 * @return array first row of query
704 public static function fetchFirst($sql) {
705 $params = self::getParam(func_get_args());
707 $stmt = self::p($sql, $params);
709 if (is_bool($stmt)) {
712 $retval = self::fetch($stmt);
721 * @brief Returns the number of affected rows of the last statement
723 * @return int Number of rows
725 public static function affectedRows() {
726 return self::$affected_rows;
730 * @brief Returns the number of columns of a statement
732 * @param object Statement object
733 * @return int Number of columns
735 public static function columnCount($stmt) {
736 if (!is_object($stmt)) {
739 switch (self::$driver) {
741 return $stmt->columnCount();
743 return $stmt->field_count;
748 * @brief Returns the number of rows of a statement
750 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
751 * @return int Number of rows
753 public static function numRows($stmt) {
754 if (!is_object($stmt)) {
757 switch (self::$driver) {
759 return $stmt->rowCount();
761 return $stmt->num_rows;
767 * @brief Fetch a single row
769 * @param mixed $stmt statement object
770 * @return array current row
772 public static function fetch($stmt) {
775 $stamp1 = microtime(true);
779 if (!is_object($stmt)) {
783 switch (self::$driver) {
785 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
788 if (get_class($stmt) == 'mysqli_result') {
789 $columns = $stmt->fetch_assoc();
793 // This code works, but is slow
795 // Bind the result to a result array
799 for ($x = 0; $x < $stmt->field_count; $x++) {
800 $cols[] = &$cols_num[$x];
803 call_user_func_array([$stmt, 'bind_result'], $cols);
805 if (!$stmt->fetch()) {
810 // We need to get the field names for the array keys
811 // It seems that there is no better way to do this.
812 $result = $stmt->result_metadata();
813 $fields = $result->fetch_fields();
815 foreach ($cols_num AS $param => $col) {
816 $columns[$fields[$param]->name] = $col;
820 $a->saveTimestamp($stamp1, 'database');
826 * @brief Insert a row into a table
828 * @param string $table Table name
829 * @param array $param parameter array
830 * @param bool $on_duplicate_update Do an update on a duplicate entry
832 * @return boolean was the insert successful?
834 public static function insert($table, $param, $on_duplicate_update = false) {
836 if (empty($table) || empty($param)) {
837 Logger::log('Table and fields have to be set');
841 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
842 substr(str_repeat("?, ", count($param)), 0, -2).")";
844 if ($on_duplicate_update) {
845 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
847 $values = array_values($param);
848 $param = array_merge_recursive($values, $values);
851 return self::e($sql, $param);
855 * @brief Fetch the id of the last insert command
857 * @return integer Last inserted id
859 public static function lastInsertId() {
860 switch (self::$driver) {
862 $id = self::$connection->lastInsertId();
865 $id = self::$connection->insert_id;
872 * @brief Locks a table for exclusive write access
874 * This function can be extended in the future to accept a table array as well.
876 * @param string $table Table name
878 * @return boolean was the lock successful?
880 public static function lock($table) {
881 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
882 if (self::$driver == 'pdo') {
883 self::e("SET autocommit=0");
884 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
886 self::$connection->autocommit(false);
889 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
891 if (self::$driver == 'pdo') {
892 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
896 if (self::$driver == 'pdo') {
897 self::e("SET autocommit=1");
899 self::$connection->autocommit(true);
902 self::$in_transaction = true;
908 * @brief Unlocks all locked tables
910 * @return boolean was the unlock successful?
912 public static function unlock() {
913 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
914 self::performCommit();
916 if (self::$driver == 'pdo') {
917 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
920 $success = self::e("UNLOCK TABLES");
922 if (self::$driver == 'pdo') {
923 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
924 self::e("SET autocommit=1");
926 self::$connection->autocommit(true);
929 self::$in_transaction = false;
934 * @brief Starts a transaction
936 * @return boolean Was the command executed successfully?
938 public static function transaction() {
939 if (!self::performCommit()) {
943 switch (self::$driver) {
945 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
951 if (!self::$connection->begin_transaction()) {
957 self::$in_transaction = true;
961 private static function performCommit()
963 switch (self::$driver) {
965 if (!self::$connection->inTransaction()) {
969 return self::$connection->commit();
972 return self::$connection->commit();
979 * @brief Does a commit
981 * @return boolean Was the command executed successfully?
983 public static function commit() {
984 if (!self::performCommit()) {
987 self::$in_transaction = false;
992 * @brief Does a rollback
994 * @return boolean Was the command executed successfully?
996 public static function rollback() {
999 switch (self::$driver) {
1001 if (!self::$connection->inTransaction()) {
1005 $ret = self::$connection->rollBack();
1009 $ret = self::$connection->rollback();
1012 self::$in_transaction = false;
1017 * @brief Build the array with the table relations
1019 * The array is build from the database definitions in DBStructure.php
1021 * This process must only be started once, since the value is cached.
1023 private static function buildRelationData() {
1024 $definition = DBStructure::definition();
1026 foreach ($definition AS $table => $structure) {
1027 foreach ($structure['fields'] AS $field => $field_struct) {
1028 if (isset($field_struct['relation'])) {
1029 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1030 self::$relation[$rel_table][$rel_field][$table][] = $field;
1038 * @brief Delete a row from a table
1040 * @param string $table Table name
1041 * @param array $conditions Field condition(s)
1042 * @param array $options
1043 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1044 * relations (default: true)
1045 * @param array $callstack Internal use: prevent endless loops
1047 * @return boolean was the delete successful?
1049 public static function delete($table, array $conditions, array $options = [], array &$callstack = [])
1051 if (empty($table) || empty($conditions)) {
1052 Logger::log('Table and conditions have to be set');
1058 // Create a key for the loop prevention
1059 $key = $table . ':' . json_encode($conditions);
1061 // We quit when this key already exists in the callstack.
1062 if (isset($callstack[$key])) {
1066 $callstack[$key] = true;
1068 $table = self::escape($table);
1070 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1072 // Don't use "defaults" here, since it would set "false" to "true"
1073 if (isset($options['cascade'])) {
1074 $cascade = $options['cascade'];
1079 // To speed up the whole process we cache the table relations
1080 if ($cascade && count(self::$relation) == 0) {
1081 self::buildRelationData();
1084 // Is there a relation entry for the table?
1085 if ($cascade && isset(self::$relation[$table])) {
1086 // We only allow a simple "one field" relation.
1087 $field = array_keys(self::$relation[$table])[0];
1088 $rel_def = array_values(self::$relation[$table])[0];
1090 // Create a key for preventing double queries
1091 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1093 // When the search field is the relation field, we don't need to fetch the rows
1094 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1095 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1096 foreach ($rel_def AS $rel_table => $rel_fields) {
1097 foreach ($rel_fields AS $rel_field) {
1098 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1101 // We quit when this key already exists in the callstack.
1102 } elseif (!isset($callstack[$qkey])) {
1103 $callstack[$qkey] = true;
1105 // Fetch all rows that are to be deleted
1106 $data = self::select($table, [$field], $conditions);
1108 while ($row = self::fetch($data)) {
1109 self::delete($table, [$field => $row[$field]], $options, $callstack);
1114 // Since we had split the delete command we don't need the original command anymore
1115 unset($commands[$key]);
1119 // Now we finalize the process
1120 $do_transaction = !self::$in_transaction;
1122 if ($do_transaction) {
1123 self::transaction();
1129 foreach ($commands AS $command) {
1130 $conditions = $command['conditions'];
1132 $first_key = key($conditions);
1134 $condition_string = self::buildCondition($conditions);
1136 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1137 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1138 Logger::log(self::replaceParameters($sql, $conditions), Logger::DATA);
1140 if (!self::e($sql, $conditions)) {
1141 if ($do_transaction) {
1147 $key_table = $command['table'];
1148 $key_condition = array_keys($command['conditions'])[0];
1149 $value = array_values($command['conditions'])[0];
1151 // Split the SQL queries in chunks of 100 values
1152 // We do the $i stuff here to make the code better readable
1153 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1154 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1158 $compacted[$key_table][$key_condition][$i][$value] = $value;
1159 $counter[$key_table][$key_condition] = $i;
1162 foreach ($compacted AS $table => $values) {
1163 foreach ($values AS $field => $field_value_list) {
1164 foreach ($field_value_list AS $field_values) {
1165 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1166 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1168 Logger::log(self::replaceParameters($sql, $field_values), Logger::DATA);
1170 if (!self::e($sql, $field_values)) {
1171 if ($do_transaction) {
1179 if ($do_transaction) {
1186 * @brief Updates rows
1188 * Updates rows in the database. When $old_fields is set to an array,
1189 * the system will only do an update if the fields in that array changed.
1192 * Only the values in $old_fields are compared.
1193 * This is an intentional behaviour.
1196 * We include the timestamp field in $fields but not in $old_fields.
1197 * Then the row will only get the new timestamp when the other fields had changed.
1199 * When $old_fields is set to a boolean value the system will do this compare itself.
1200 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1203 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1204 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1206 * @param string $table Table name
1207 * @param array $fields contains the fields that are updated
1208 * @param array $condition condition array with the key values
1209 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1211 * @return boolean was the update successfull?
1213 public static function update($table, $fields, $condition, $old_fields = []) {
1215 if (empty($table) || empty($fields) || empty($condition)) {
1216 Logger::log('Table, fields and condition have to be set');
1220 $table = self::escape($table);
1222 $condition_string = self::buildCondition($condition);
1224 if (is_bool($old_fields)) {
1225 $do_insert = $old_fields;
1227 $old_fields = self::selectFirst($table, [], $condition);
1229 if (is_bool($old_fields)) {
1231 $values = array_merge($condition, $fields);
1232 return self::insert($table, $values, $do_insert);
1238 $do_update = (count($old_fields) == 0);
1240 foreach ($old_fields AS $fieldname => $content) {
1241 if (isset($fields[$fieldname])) {
1242 if (($fields[$fieldname] == $content) && !is_null($content)) {
1243 unset($fields[$fieldname]);
1250 if (!$do_update || (count($fields) == 0)) {
1254 $sql = "UPDATE `".$table."` SET `".
1255 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1257 $params1 = array_values($fields);
1258 $params2 = array_values($condition);
1259 $params = array_merge_recursive($params1, $params2);
1261 return self::e($sql, $params);
1265 * Retrieve a single record from a table and returns it in an associative array
1267 * @brief Retrieve a single record from a table
1268 * @param string $table
1269 * @param array $fields
1270 * @param array $condition
1271 * @param array $params
1272 * @return bool|array
1275 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1277 $params['limit'] = 1;
1278 $result = self::select($table, $fields, $condition, $params);
1280 if (is_bool($result)) {
1283 $row = self::fetch($result);
1284 self::close($result);
1290 * @brief Select rows from a table
1292 * @param string $table Table name
1293 * @param array $fields Array of selected fields, empty for all
1294 * @param array $condition Array of fields for condition
1295 * @param array $params Array of several parameters
1297 * @return boolean|object
1301 * $fields = array("id", "uri", "uid", "network");
1303 * $condition = array("uid" => 1, "network" => 'dspr');
1305 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1307 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1309 * $data = DBA::select($table, $fields, $condition, $params);
1311 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1317 $table = self::escape($table);
1319 if (count($fields) > 0) {
1320 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1322 $select_fields = "*";
1325 $condition_string = self::buildCondition($condition);
1327 $param_string = self::buildParameter($params);
1329 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1331 $result = self::p($sql, $condition);
1337 * @brief Counts the rows from a table satisfying the provided condition
1339 * @param string $table Table name
1340 * @param array $condition array of fields for condition
1347 * $condition = ["uid" => 1, "network" => 'dspr'];
1349 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1351 * $count = DBA::count($table, $condition);
1353 public static function count($table, array $condition = [])
1359 $condition_string = self::buildCondition($condition);
1361 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1363 $row = self::fetchFirst($sql, $condition);
1365 return $row['count'];
1369 * @brief Returns the SQL condition string built from the provided condition array
1371 * This function operates with two modes.
1372 * - Supplied with a filed/value associative array, it builds simple strict
1373 * equality conditions linked by AND.
1374 * - Supplied with a flat list, the first element is the condition string and
1375 * the following arguments are the values to be interpolated
1377 * $condition = ["uid" => 1, "network" => 'dspr'];
1379 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1381 * In either case, the provided array is left with the parameters only
1383 * @param array $condition
1386 public static function buildCondition(array &$condition = [])
1388 $condition_string = '';
1389 if (count($condition) > 0) {
1391 $first_key = key($condition);
1392 if (is_int($first_key)) {
1393 $condition_string = " WHERE (" . array_shift($condition) . ")";
1396 $condition_string = "";
1397 foreach ($condition as $field => $value) {
1398 if ($condition_string != "") {
1399 $condition_string .= " AND ";
1401 if (is_array($value)) {
1402 /* Workaround for MySQL Bug #64791.
1403 * Never mix data types inside any IN() condition.
1404 * In case of mixed types, cast all as string.
1405 * Logic needs to be consistent with DBA::p() data types.
1409 foreach ($value as $single_value) {
1410 if (is_int($single_value)) {
1417 if ($is_int && $is_alpha) {
1418 foreach ($value as &$ref) {
1420 $ref = (string)$ref;
1423 unset($ref); //Prevent accidental re-use.
1426 $new_values = array_merge($new_values, array_values($value));
1427 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1428 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1430 $new_values[$field] = $value;
1431 $condition_string .= "`" . $field . "` = ?";
1434 $condition_string = " WHERE (" . $condition_string . ")";
1435 $condition = $new_values;
1439 return $condition_string;
1443 * @brief Returns the SQL parameter string built from the provided parameter array
1445 * @param array $params
1448 public static function buildParameter(array $params = [])
1451 if (isset($params['order'])) {
1452 $order_string = " ORDER BY ";
1453 foreach ($params['order'] AS $fields => $order) {
1454 if (!is_int($fields)) {
1455 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1457 $order_string .= "`" . $order . "`, ";
1460 $order_string = substr($order_string, 0, -2);
1464 if (isset($params['limit']) && is_int($params['limit'])) {
1465 $limit_string = " LIMIT " . intval($params['limit']);
1468 if (isset($params['limit']) && is_array($params['limit'])) {
1469 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1472 return $order_string.$limit_string;
1476 * @brief Fills an array with data from a query
1478 * @param object $stmt statement object
1479 * @return array Data array
1481 public static function toArray($stmt, $do_close = true) {
1482 if (is_bool($stmt)) {
1487 while ($row = self::fetch($stmt)) {
1497 * @brief Returns the error number of the last query
1499 * @return string Error number (0 if no error)
1501 public static function errorNo() {
1502 return self::$errorno;
1506 * @brief Returns the error message of the last query
1508 * @return string Error message ('' if no error)
1510 public static function errorMessage() {
1511 return self::$error;
1515 * @brief Closes the current statement
1517 * @param object $stmt statement object
1518 * @return boolean was the close successful?
1520 public static function close($stmt) {
1523 $stamp1 = microtime(true);
1525 if (!is_object($stmt)) {
1529 switch (self::$driver) {
1531 $ret = $stmt->closeCursor();
1534 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1535 // We should be careful not to assume the object type of $stmt
1536 // because DBA::p() has been able to return both types.
1537 if ($stmt instanceof mysqli_stmt) {
1538 $stmt->free_result();
1539 $ret = $stmt->close();
1540 } elseif ($stmt instanceof mysqli_result) {
1549 $a->saveTimestamp($stamp1, 'database');
1555 * @brief Return a list of database processes
1558 * 'list' => List of processes, separated in their different states
1559 * 'amount' => Number of concurrent database processes
1561 public static function processlist()
1563 $ret = self::p("SHOW PROCESSLIST");
1564 $data = self::toArray($ret);
1570 foreach ($data as $process) {
1571 $state = trim($process["State"]);
1573 // Filter out all non blocking processes
1574 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1581 foreach ($states as $state => $usage) {
1582 if ($statelist != "") {
1585 $statelist .= $state.": ".$usage;
1587 return(["list" => $statelist, "amount" => $processes]);
1591 * Checks if $array is a filled array with at least one entry.
1593 * @param mixed $array A filled array with at least one entry
1595 * @return boolean Whether $array is a filled array or an object with rows
1597 public static function isResult($array)
1599 // It could be a return value from an update statement
1600 if (is_bool($array)) {
1604 if (is_object($array)) {
1605 return self::numRows($array) > 0;
1608 return (is_array($array) && (count($array) > 0));
1612 * @brief Callback function for "esc_array"
1614 * @param mixed $value Array value
1615 * @param string $key Array key
1616 * @param boolean $add_quotation add quotation marks for string values
1619 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1621 if (!$add_quotation) {
1622 if (is_bool($value)) {
1623 $value = ($value ? '1' : '0');
1625 $value = self::escape($value);
1630 if (is_bool($value)) {
1631 $value = ($value ? 'true' : 'false');
1632 } elseif (is_float($value) || is_integer($value)) {
1633 $value = (string) $value;
1635 $value = "'" . self::escape($value) . "'";
1640 * @brief Escapes a whole array
1642 * @param mixed $arr Array with values to be escaped
1643 * @param boolean $add_quotation add quotation marks for string values
1646 public static function escapeArray(&$arr, $add_quotation = false)
1648 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);