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.
27 public static $connected = false;
29 private static $server_info = '';
30 private static $connection;
31 private static $driver;
32 private static $error = false;
33 private static $errorno = 0;
34 private static $affected_rows = 0;
35 private static $in_transaction = false;
36 private static $in_retrial = false;
37 private static $relation = [];
38 private static $db_serveraddr = '';
39 private static $db_user = '';
40 private static $db_pass = '';
41 private static $db_name = '';
42 private static $db_charset = '';
44 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
46 if (!is_null(self::$connection) && self::connected()) {
50 // We are storing these values for being able to perform a reconnect
51 self::$db_serveraddr = $serveraddr;
52 self::$db_user = $user;
53 self::$db_pass = $pass;
55 self::$db_charset = $charset;
58 $serveraddr = trim($serveraddr);
60 $serverdata = explode(':', $serveraddr);
61 $server = $serverdata[0];
63 if (count($serverdata) > 1) {
64 $port = trim($serverdata[1]);
67 $server = trim($server);
71 $charset = trim($charset);
73 if (!(strlen($server) && strlen($user))) {
77 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
78 self::$driver = 'pdo';
79 $connect = "mysql:host=".$server.";dbname=".$db;
82 $connect .= ";port=".$port;
86 $connect .= ";charset=".$charset;
90 self::$connection = @new PDO($connect, $user, $pass);
91 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
92 self::$connected = true;
93 } catch (PDOException $e) {
97 if (!self::$connected && class_exists('\mysqli')) {
98 self::$driver = 'mysqli';
101 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
103 self::$connection = @new mysqli($server, $user, $pass, $db);
106 if (!mysqli_connect_errno()) {
107 self::$connected = true;
110 self::$connection->set_charset($charset);
115 // No suitable SQL driver was found.
116 if (!self::$connected) {
117 self::$driver = null;
118 self::$connection = null;
121 return self::$connected;
125 * Disconnects the current database connection
127 public static function disconnect()
129 if (is_null(self::$connection)) {
133 switch (self::$driver) {
135 self::$connection = null;
138 self::$connection->close();
139 self::$connection = null;
145 * Perform a reconnect of an existing database connection
147 public static function reconnect() {
150 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
155 * Return the database object.
158 public static function getConnection()
160 return self::$connection;
164 * @brief Returns the MySQL server version string
166 * This function discriminate between the deprecated mysql API and the current
167 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
171 public static function serverInfo() {
172 if (self::$server_info == '') {
173 switch (self::$driver) {
175 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
178 self::$server_info = self::$connection->server_info;
182 return self::$server_info;
186 * @brief Returns the selected database name
190 public static function databaseName() {
191 $ret = self::p("SELECT DATABASE() AS `db`");
192 $data = self::toArray($ret);
193 return $data[0]['db'];
197 * @brief Analyze a database query and log this if some conditions are met.
199 * @param string $query The database query that will be analyzed
201 private static function logIndex($query) {
204 if (!$a->getConfigVariable('system', 'db_log_index')) {
208 // Don't explain an explain statement
209 if (strtolower(substr($query, 0, 7)) == "explain") {
213 // Only do the explain on "select", "update" and "delete"
214 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
218 $r = self::p("EXPLAIN ".$query);
219 if (!self::isResult($r)) {
223 $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch'));
224 $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist'));
226 while ($row = self::fetch($r)) {
227 if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) {
228 $log = (in_array($row['key'], $watchlist) &&
229 ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index'))));
234 if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) {
238 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
243 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
244 @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
245 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
246 basename($backtrace[1]["file"])."\t".
247 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
248 substr($query, 0, 2000)."\n", FILE_APPEND);
253 public static function escape($str) {
254 switch (self::$driver) {
256 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
258 return @self::$connection->real_escape_string($str);
262 public static function connected() {
265 if (is_null(self::$connection)) {
269 switch (self::$driver) {
271 $r = self::p("SELECT 1");
272 if (self::isResult($r)) {
273 $row = self::toArray($r);
274 $connected = ($row[0]['1'] == '1');
278 $connected = self::$connection->ping();
285 * @brief Replaces ANY_VALUE() function by MIN() function,
286 * if the database server does not support ANY_VALUE().
288 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
289 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
290 * A standard fall-back is to use MIN().
292 * @param string $sql An SQL string without the values
293 * @return string The input SQL string modified if necessary.
295 public static function anyValueFallback($sql) {
296 $server_info = self::serverInfo();
297 if (version_compare($server_info, '5.7.5', '<') ||
298 (stripos($server_info, 'MariaDB') !== false)) {
299 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
305 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
307 * This is safe when we bind the parameters later.
308 * The parameter values aren't part of the SQL.
310 * @param string $sql An SQL string without the values
311 * @return string The input SQL string modified if necessary.
313 public static function cleanQuery($sql) {
314 $search = ["\t", "\n", "\r", " "];
315 $replace = [' ', ' ', ' ', ' '];
318 $sql = str_replace($search, $replace, $sql);
319 } while ($oldsql != $sql);
326 * @brief Replaces the ? placeholders with the parameters in the $args array
328 * @param string $sql SQL query
329 * @param array $args The parameters that are to replace the ? placeholders
330 * @return string The replaced SQL query
332 private static function replaceParameters($sql, $args) {
334 foreach ($args AS $param => $value) {
335 if (is_int($args[$param]) || is_float($args[$param])) {
336 $replace = intval($args[$param]);
338 $replace = "'".self::escape($args[$param])."'";
341 $pos = strpos($sql, '?', $offset);
342 if ($pos !== false) {
343 $sql = substr_replace($sql, $replace, $pos, 1);
345 $offset = $pos + strlen($replace);
351 * @brief Convert parameter array to an universal form
352 * @param array $args Parameter array
353 * @return array universalized parameter array
355 private static function getParam($args) {
358 // When the second function parameter is an array then use this as the parameter array
359 if ((count($args) > 0) && (is_array($args[1]))) {
367 * @brief Executes a prepared statement that returns data
368 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
370 * Please only use it with complicated queries.
371 * For all regular queries please use dba::select or dba::exists
373 * @param string $sql SQL statement
374 * @return bool|object statement object or result object
376 public static function p($sql) {
379 $stamp1 = microtime(true);
381 $params = self::getParam(func_get_args());
383 // Renumber the array keys to be sure that they fit
386 foreach ($params AS $param) {
387 // Avoid problems with some MySQL servers and boolean values. See issue #3645
388 if (is_bool($param)) {
389 $param = (int)$param;
391 $args[++$i] = $param;
394 if (!self::$connected) {
398 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
399 // Question: Should we continue or stop the query here?
400 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
403 $sql = self::cleanQuery($sql);
404 $sql = self::anyValueFallback($sql);
408 if ($a->getConfigValue('system', 'db_callstack')) {
409 $sql = "/*".System::callstack()." */ ".$sql;
414 self::$affected_rows = 0;
416 // We have to make some things different if this function is called from "e"
417 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
419 if (isset($trace[1])) {
420 $called_from = $trace[1];
422 // We use just something that is defined to avoid warnings
423 $called_from = $trace[0];
425 // We are having an own error logging in the function "e"
426 $called_from_e = ($called_from['function'] == 'e');
428 switch (self::$driver) {
430 // If there are no arguments we use "query"
431 if (count($args) == 0) {
432 if (!$retval = self::$connection->query($sql)) {
433 $errorInfo = self::$connection->errorInfo();
434 self::$error = $errorInfo[2];
435 self::$errorno = $errorInfo[1];
439 self::$affected_rows = $retval->rowCount();
443 if (!$stmt = self::$connection->prepare($sql)) {
444 $errorInfo = self::$connection->errorInfo();
445 self::$error = $errorInfo[2];
446 self::$errorno = $errorInfo[1];
451 foreach ($args AS $param => $value) {
452 if (is_int($args[$param])) {
453 $data_type = PDO::PARAM_INT;
455 $data_type = PDO::PARAM_STR;
457 $stmt->bindParam($param, $args[$param], $data_type);
460 if (!$stmt->execute()) {
461 $errorInfo = $stmt->errorInfo();
462 self::$error = $errorInfo[2];
463 self::$errorno = $errorInfo[1];
467 self::$affected_rows = $retval->rowCount();
471 // There are SQL statements that cannot be executed with a prepared statement
472 $parts = explode(' ', $orig_sql);
473 $command = strtolower($parts[0]);
474 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
476 // The fallback routine is called as well when there are no arguments
477 if (!$can_be_prepared || (count($args) == 0)) {
478 $retval = self::$connection->query(self::replaceParameters($sql, $args));
479 if (self::$connection->errno) {
480 self::$error = self::$connection->error;
481 self::$errorno = self::$connection->errno;
484 if (isset($retval->num_rows)) {
485 self::$affected_rows = $retval->num_rows;
487 self::$affected_rows = self::$connection->affected_rows;
493 $stmt = self::$connection->stmt_init();
495 if (!$stmt->prepare($sql)) {
496 self::$error = $stmt->error;
497 self::$errorno = $stmt->errno;
504 foreach ($args AS $param => $value) {
505 if (is_int($args[$param])) {
507 } elseif (is_float($args[$param])) {
509 } elseif (is_string($args[$param])) {
514 $values[] = &$args[$param];
517 if (count($values) > 0) {
518 array_unshift($values, $param_types);
519 call_user_func_array([$stmt, 'bind_param'], $values);
522 if (!$stmt->execute()) {
523 self::$error = self::$connection->error;
524 self::$errorno = self::$connection->errno;
527 $stmt->store_result();
529 self::$affected_rows = $retval->affected_rows;
534 // We are having an own error logging in the function "e"
535 if ((self::$errorno != 0) && !$called_from_e) {
536 // We have to preserve the error code, somewhere in the logging it get lost
537 $error = self::$error;
538 $errorno = self::$errorno;
540 logger('DB Error '.self::$errorno.': '.self::$error."\n".
541 System::callstack(8)."\n".self::replaceParameters($sql, $args));
543 // On a lost connection we try to reconnect - but only once.
544 if ($errorno == 2006) {
545 if (self::$in_retrial || !self::reconnect()) {
546 // It doesn't make sense to continue when the database connection was lost
547 if (self::$in_retrial) {
548 logger('Giving up retrial because of database error '.$errorno.': '.$error);
550 logger("Couldn't reconnect after database error ".$errorno.': '.$error);
555 logger('Reconnected after database error '.$errorno.': '.$error);
556 self::$in_retrial = true;
557 $ret = self::p($sql, $args);
558 self::$in_retrial = false;
563 self::$error = $error;
564 self::$errorno = $errorno;
567 $a->save_timestamp($stamp1, 'database');
569 if ($a->getConfigValue('system', 'db_log')) {
570 $stamp2 = microtime(true);
571 $duration = (float)($stamp2 - $stamp1);
573 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
574 $duration = round($duration, 3);
575 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
577 @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
578 basename($backtrace[1]["file"])."\t".
579 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
580 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
587 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
589 * Please use dba::delete, dba::insert, dba::update, ... instead
591 * @param string $sql SQL statement
592 * @return boolean Was the query successfull? False is returned only if an error occurred
594 public static function e($sql) {
597 $stamp = microtime(true);
599 $params = self::getParam(func_get_args());
601 // In a case of a deadlock we are repeating the query 20 times
605 $stmt = self::p($sql, $params);
607 if (is_bool($stmt)) {
609 } elseif (is_object($stmt)) {
617 } while ((self::$errorno == 1213) && (--$timeout > 0));
619 if (self::$errorno != 0) {
620 // We have to preserve the error code, somewhere in the logging it get lost
621 $error = self::$error;
622 $errorno = self::$errorno;
624 logger('DB Error '.self::$errorno.': '.self::$error."\n".
625 System::callstack(8)."\n".self::replaceParameters($sql, $params));
627 // On a lost connection we simply quit.
628 // A reconnect like in self::p could be dangerous with modifications
629 if ($errorno == 2006) {
630 logger('Giving up because of database error '.$errorno.': '.$error);
634 self::$error = $error;
635 self::$errorno = $errorno;
638 $a->save_timestamp($stamp, "database_write");
644 * @brief Check if data exists
646 * @param string $table Table name
647 * @param array $condition array of fields for condition
649 * @return boolean Are there rows for that condition?
651 public static function exists($table, $condition) {
658 if (empty($condition)) {
659 return DBStructure::existsTable($table);
663 $first_key = key($condition);
664 if (!is_int($first_key)) {
665 $fields = [$first_key];
668 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
670 if (is_bool($stmt)) {
673 $retval = (self::numRows($stmt) > 0);
682 * Fetches the first row
684 * Please use dba::selectFirst or dba::exists whenever this is possible.
686 * @brief Fetches the first row
687 * @param string $sql SQL statement
688 * @return array first row of query
690 public static function fetchFirst($sql) {
691 $params = self::getParam(func_get_args());
693 $stmt = self::p($sql, $params);
695 if (is_bool($stmt)) {
698 $retval = self::fetch($stmt);
707 * @brief Returns the number of affected rows of the last statement
709 * @return int Number of rows
711 public static function affectedRows() {
712 return self::$affected_rows;
716 * @brief Returns the number of columns of a statement
718 * @param object Statement object
719 * @return int Number of columns
721 public static function columnCount($stmt) {
722 if (!is_object($stmt)) {
725 switch (self::$driver) {
727 return $stmt->columnCount();
729 return $stmt->field_count;
734 * @brief Returns the number of rows of a statement
736 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
737 * @return int Number of rows
739 public static function numRows($stmt) {
740 if (!is_object($stmt)) {
743 switch (self::$driver) {
745 return $stmt->rowCount();
747 return $stmt->num_rows;
753 * @brief Fetch a single row
755 * @param mixed $stmt statement object
756 * @return array current row
758 public static function fetch($stmt) {
761 $stamp1 = microtime(true);
765 if (!is_object($stmt)) {
769 switch (self::$driver) {
771 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
774 if (get_class($stmt) == 'mysqli_result') {
775 $columns = $stmt->fetch_assoc();
779 // This code works, but is slow
781 // Bind the result to a result array
785 for ($x = 0; $x < $stmt->field_count; $x++) {
786 $cols[] = &$cols_num[$x];
789 call_user_func_array([$stmt, 'bind_result'], $cols);
791 if (!$stmt->fetch()) {
796 // We need to get the field names for the array keys
797 // It seems that there is no better way to do this.
798 $result = $stmt->result_metadata();
799 $fields = $result->fetch_fields();
801 foreach ($cols_num AS $param => $col) {
802 $columns[$fields[$param]->name] = $col;
806 $a->save_timestamp($stamp1, 'database');
812 * @brief Insert a row into a table
814 * @param string $table Table name
815 * @param array $param parameter array
816 * @param bool $on_duplicate_update Do an update on a duplicate entry
818 * @return boolean was the insert successfull?
820 public static function insert($table, $param, $on_duplicate_update = false) {
822 if (empty($table) || empty($param)) {
823 logger('Table and fields have to be set');
827 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
828 substr(str_repeat("?, ", count($param)), 0, -2).")";
830 if ($on_duplicate_update) {
831 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
833 $values = array_values($param);
834 $param = array_merge_recursive($values, $values);
837 return self::e($sql, $param);
841 * @brief Fetch the id of the last insert command
843 * @return integer Last inserted id
845 public static function lastInsertId() {
846 switch (self::$driver) {
848 $id = self::$connection->lastInsertId();
851 $id = self::$connection->insert_id;
858 * @brief Locks a table for exclusive write access
860 * This function can be extended in the future to accept a table array as well.
862 * @param string $table Table name
864 * @return boolean was the lock successful?
866 public static function lock($table) {
867 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
868 if (self::$driver == 'pdo') {
869 self::e("SET autocommit=0");
870 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
872 self::$connection->autocommit(false);
875 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
877 if (self::$driver == 'pdo') {
878 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
882 if (self::$driver == 'pdo') {
883 self::e("SET autocommit=1");
885 self::$connection->autocommit(true);
888 self::$in_transaction = true;
894 * @brief Unlocks all locked tables
896 * @return boolean was the unlock successful?
898 public static function unlock() {
899 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
900 self::performCommit();
902 if (self::$driver == 'pdo') {
903 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
906 $success = self::e("UNLOCK TABLES");
908 if (self::$driver == 'pdo') {
909 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
910 self::e("SET autocommit=1");
912 self::$connection->autocommit(true);
915 self::$in_transaction = false;
920 * @brief Starts a transaction
922 * @return boolean Was the command executed successfully?
924 public static function transaction() {
925 if (!self::performCommit()) {
929 switch (self::$driver) {
931 if (self::$connection->inTransaction()) {
934 if (!self::$connection->beginTransaction()) {
939 if (!self::$connection->begin_transaction()) {
945 self::$in_transaction = true;
949 private static function performCommit()
951 switch (self::$driver) {
953 if (!self::$connection->inTransaction()) {
956 return self::$connection->commit();
958 return self::$connection->commit();
964 * @brief Does a commit
966 * @return boolean Was the command executed successfully?
968 public static function commit() {
969 if (!self::performCommit()) {
972 self::$in_transaction = false;
977 * @brief Does a rollback
979 * @return boolean Was the command executed successfully?
981 public static function rollback() {
984 switch (self::$driver) {
986 if (!self::$connection->inTransaction()) {
990 $ret = self::$connection->rollBack();
993 $ret = self::$connection->rollback();
996 self::$in_transaction = false;
1001 * @brief Build the array with the table relations
1003 * The array is build from the database definitions in DBStructure.php
1005 * This process must only be started once, since the value is cached.
1007 private static function buildRelationData() {
1008 $definition = DBStructure::definition();
1010 foreach ($definition AS $table => $structure) {
1011 foreach ($structure['fields'] AS $field => $field_struct) {
1012 if (isset($field_struct['relation'])) {
1013 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1014 self::$relation[$rel_table][$rel_field][$table][] = $field;
1022 * @brief Delete a row from a table
1024 * @param string $table Table name
1025 * @param array $conditions Field condition(s)
1026 * @param array $options
1027 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1028 * relations (default: true)
1029 * @param boolean $in_process Internal use: Only do a commit after the last delete
1030 * @param array $callstack Internal use: prevent endless loops
1032 * @return boolean|array was the delete successful? When $in_process is set: deletion data
1034 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
1036 if (empty($table) || empty($conditions)) {
1037 logger('Table and conditions have to be set');
1043 // Create a key for the loop prevention
1044 $key = $table . ':' . json_encode($conditions);
1046 // We quit when this key already exists in the callstack.
1047 if (isset($callstack[$key])) {
1051 $callstack[$key] = true;
1053 $table = self::escape($table);
1055 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1057 $cascade = defaults($options, 'cascade', true);
1059 // To speed up the whole process we cache the table relations
1060 if ($cascade && count(self::$relation) == 0) {
1061 self::buildRelationData();
1064 // Is there a relation entry for the table?
1065 if ($cascade && isset(self::$relation[$table])) {
1066 // We only allow a simple "one field" relation.
1067 $field = array_keys(self::$relation[$table])[0];
1068 $rel_def = array_values(self::$relation[$table])[0];
1070 // Create a key for preventing double queries
1071 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1073 // When the search field is the relation field, we don't need to fetch the rows
1074 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1075 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1076 foreach ($rel_def AS $rel_table => $rel_fields) {
1077 foreach ($rel_fields AS $rel_field) {
1078 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
1079 $commands = array_merge($commands, $retval);
1082 // We quit when this key already exists in the callstack.
1083 } elseif (!isset($callstack[$qkey])) {
1085 $callstack[$qkey] = true;
1087 // Fetch all rows that are to be deleted
1088 $data = self::select($table, [$field], $conditions);
1090 while ($row = self::fetch($data)) {
1091 // Now we accumulate the delete commands
1092 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
1093 $commands = array_merge($commands, $retval);
1098 // Since we had split the delete command we don't need the original command anymore
1099 unset($commands[$key]);
1104 // Now we finalize the process
1105 $do_transaction = !self::$in_transaction;
1107 if ($do_transaction) {
1108 self::transaction();
1114 foreach ($commands AS $command) {
1115 $conditions = $command['conditions'];
1117 $first_key = key($conditions);
1119 $condition_string = self::buildCondition($conditions);
1121 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1122 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1123 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
1125 if (!self::e($sql, $conditions)) {
1126 if ($do_transaction) {
1132 $key_table = $command['table'];
1133 $key_condition = array_keys($command['conditions'])[0];
1134 $value = array_values($command['conditions'])[0];
1136 // Split the SQL queries in chunks of 100 values
1137 // We do the $i stuff here to make the code better readable
1138 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1139 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1143 $compacted[$key_table][$key_condition][$i][$value] = $value;
1144 $counter[$key_table][$key_condition] = $i;
1147 foreach ($compacted AS $table => $values) {
1148 foreach ($values AS $field => $field_value_list) {
1149 foreach ($field_value_list AS $field_values) {
1150 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1151 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1153 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1155 if (!self::e($sql, $field_values)) {
1156 if ($do_transaction) {
1164 if ($do_transaction) {
1174 * @brief Updates rows
1176 * Updates rows in the database. When $old_fields is set to an array,
1177 * the system will only do an update if the fields in that array changed.
1180 * Only the values in $old_fields are compared.
1181 * This is an intentional behaviour.
1184 * We include the timestamp field in $fields but not in $old_fields.
1185 * Then the row will only get the new timestamp when the other fields had changed.
1187 * When $old_fields is set to a boolean value the system will do this compare itself.
1188 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1191 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1192 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1194 * @param string $table Table name
1195 * @param array $fields contains the fields that are updated
1196 * @param array $condition condition array with the key values
1197 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1199 * @return boolean was the update successfull?
1201 public static function update($table, $fields, $condition, $old_fields = []) {
1203 if (empty($table) || empty($fields) || empty($condition)) {
1204 logger('Table, fields and condition have to be set');
1208 $table = self::escape($table);
1210 $condition_string = self::buildCondition($condition);
1212 if (is_bool($old_fields)) {
1213 $do_insert = $old_fields;
1215 $old_fields = self::selectFirst($table, [], $condition);
1217 if (is_bool($old_fields)) {
1219 $values = array_merge($condition, $fields);
1220 return self::insert($table, $values, $do_insert);
1226 $do_update = (count($old_fields) == 0);
1228 foreach ($old_fields AS $fieldname => $content) {
1229 if (isset($fields[$fieldname])) {
1230 if ($fields[$fieldname] == $content) {
1231 unset($fields[$fieldname]);
1238 if (!$do_update || (count($fields) == 0)) {
1242 $sql = "UPDATE `".$table."` SET `".
1243 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1245 $params1 = array_values($fields);
1246 $params2 = array_values($condition);
1247 $params = array_merge_recursive($params1, $params2);
1249 return self::e($sql, $params);
1253 * Retrieve a single record from a table and returns it in an associative array
1255 * @brief Retrieve a single record from a table
1256 * @param string $table
1257 * @param array $fields
1258 * @param array $condition
1259 * @param array $params
1260 * @return bool|array
1263 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1265 $params['limit'] = 1;
1266 $result = self::select($table, $fields, $condition, $params);
1268 if (is_bool($result)) {
1271 $row = self::fetch($result);
1272 self::close($result);
1278 * @brief Select rows from a table
1280 * @param string $table Table name
1281 * @param array $fields Array of selected fields, empty for all
1282 * @param array $condition Array of fields for condition
1283 * @param array $params Array of several parameters
1285 * @return boolean|object
1289 * $fields = array("id", "uri", "uid", "network");
1291 * $condition = array("uid" => 1, "network" => 'dspr');
1293 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1295 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1297 * $data = dba::select($table, $fields, $condition, $params);
1299 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1305 $table = self::escape($table);
1307 if (count($fields) > 0) {
1308 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1310 $select_fields = "*";
1313 $condition_string = self::buildCondition($condition);
1315 $param_string = self::buildParameter($params);
1317 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1319 $result = self::p($sql, $condition);
1325 * @brief Counts the rows from a table satisfying the provided condition
1327 * @param string $table Table name
1328 * @param array $condition array of fields for condition
1335 * $condition = ["uid" => 1, "network" => 'dspr'];
1337 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1339 * $count = dba::count($table, $condition);
1341 public static function count($table, array $condition = [])
1347 $condition_string = self::buildCondition($condition);
1349 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1351 $row = self::fetchFirst($sql, $condition);
1353 return $row['count'];
1357 * @brief Returns the SQL condition string built from the provided condition array
1359 * This function operates with two modes.
1360 * - Supplied with a filed/value associative array, it builds simple strict
1361 * equality conditions linked by AND.
1362 * - Supplied with a flat list, the first element is the condition string and
1363 * the following arguments are the values to be interpolated
1365 * $condition = ["uid" => 1, "network" => 'dspr'];
1367 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1369 * In either case, the provided array is left with the parameters only
1371 * @param array $condition
1374 public static function buildCondition(array &$condition = [])
1376 $condition_string = '';
1377 if (count($condition) > 0) {
1379 $first_key = key($condition);
1380 if (is_int($first_key)) {
1381 $condition_string = " WHERE (" . array_shift($condition) . ")";
1384 $condition_string = "";
1385 foreach ($condition as $field => $value) {
1386 if ($condition_string != "") {
1387 $condition_string .= " AND ";
1389 if (is_array($value)) {
1390 /* Workaround for MySQL Bug #64791.
1391 * Never mix data types inside any IN() condition.
1392 * In case of mixed types, cast all as string.
1393 * Logic needs to be consistent with dba::p() data types.
1397 foreach ($value as $single_value) {
1398 if (is_int($single_value)) {
1405 if ($is_int && $is_alpha) {
1406 foreach ($value as &$ref) {
1408 $ref = (string)$ref;
1411 unset($ref); //Prevent accidental re-use.
1414 $new_values = array_merge($new_values, array_values($value));
1415 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1416 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1418 $new_values[$field] = $value;
1419 $condition_string .= "`" . $field . "` = ?";
1422 $condition_string = " WHERE (" . $condition_string . ")";
1423 $condition = $new_values;
1427 return $condition_string;
1431 * @brief Returns the SQL parameter string built from the provided parameter array
1433 * @param array $params
1436 public static function buildParameter(array $params = [])
1439 if (isset($params['order'])) {
1440 $order_string = " ORDER BY ";
1441 foreach ($params['order'] AS $fields => $order) {
1442 if (!is_int($fields)) {
1443 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1445 $order_string .= "`" . $order . "`, ";
1448 $order_string = substr($order_string, 0, -2);
1452 if (isset($params['limit']) && is_int($params['limit'])) {
1453 $limit_string = " LIMIT " . $params['limit'];
1456 if (isset($params['limit']) && is_array($params['limit'])) {
1457 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1460 return $order_string.$limit_string;
1464 * @brief Fills an array with data from a query
1466 * @param object $stmt statement object
1467 * @return array Data array
1469 public static function toArray($stmt, $do_close = true) {
1470 if (is_bool($stmt)) {
1475 while ($row = self::fetch($stmt)) {
1485 * @brief Returns the error number of the last query
1487 * @return string Error number (0 if no error)
1489 public static function errorNo() {
1490 return self::$errorno;
1494 * @brief Returns the error message of the last query
1496 * @return string Error message ('' if no error)
1498 public static function errorMessage() {
1499 return self::$error;
1503 * @brief Closes the current statement
1505 * @param object $stmt statement object
1506 * @return boolean was the close successful?
1508 public static function close($stmt) {
1511 $stamp1 = microtime(true);
1513 if (!is_object($stmt)) {
1517 switch (self::$driver) {
1519 $ret = $stmt->closeCursor();
1522 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1523 // We should be careful not to assume the object type of $stmt
1524 // because dba::p() has been able to return both types.
1525 if ($stmt instanceof mysqli_stmt) {
1526 $stmt->free_result();
1527 $ret = $stmt->close();
1528 } elseif ($stmt instanceof mysqli_result) {
1537 $a->save_timestamp($stamp1, 'database');
1543 * @brief Return a list of database processes
1546 * 'list' => List of processes, separated in their different states
1547 * 'amount' => Number of concurrent database processes
1549 public static function processlist()
1551 $ret = self::p("SHOW PROCESSLIST");
1552 $data = self::toArray($ret);
1558 foreach ($data as $process) {
1559 $state = trim($process["State"]);
1561 // Filter out all non blocking processes
1562 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1569 foreach ($states as $state => $usage) {
1570 if ($statelist != "") {
1573 $statelist .= $state.": ".$usage;
1575 return(["list" => $statelist, "amount" => $processes]);
1579 * Checks if $array is a filled array with at least one entry.
1581 * @param mixed $array A filled array with at least one entry
1583 * @return boolean Whether $array is a filled array or an object with rows
1585 public static function isResult($array)
1587 // It could be a return value from an update statement
1588 if (is_bool($array)) {
1592 if (is_object($array)) {
1593 return self::numRows($array) > 0;
1596 return (is_array($array) && (count($array) > 0));
1600 * @brief Callback function for "esc_array"
1602 * @param mixed $value Array value
1603 * @param string $key Array key
1604 * @param boolean $add_quotation add quotation marks for string values
1607 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1609 if (!$add_quotation) {
1610 if (is_bool($value)) {
1611 $value = ($value ? '1' : '0');
1613 $value = dbesc($value);
1618 if (is_bool($value)) {
1619 $value = ($value ? 'true' : 'false');
1620 } elseif (is_float($value) || is_integer($value)) {
1621 $value = (string) $value;
1623 $value = "'" . dbesc($value) . "'";
1628 * @brief Escapes a whole array
1630 * @param mixed $arr Array with values to be escaped
1631 * @param boolean $add_quotation add quotation marks for string values
1634 public static function escapeArray(&$arr, $add_quotation = false)
1636 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);