3 // Do not use Core\Config in this class at risk of infinite loop.
4 // Please use App->getConfigVariable() instead.
5 //use Friendica\Core\Config;
7 use Friendica\Core\System;
8 use Friendica\Database\DBM;
9 use Friendica\Database\DBStructure;
10 use Friendica\Util\DateTimeFormat;
13 * @class MySQL database class
15 * This class is for the low level database stuff that does driver specific things.
19 public static $connected = false;
21 private static $_server_info = '';
23 private static $driver;
24 private static $error = false;
25 private static $errorno = 0;
26 private static $affected_rows = 0;
27 private static $in_transaction = false;
28 private static $in_retrial = false;
29 private static $relation = [];
30 private static $db_serveraddr = '';
31 private static $db_user = '';
32 private static $db_pass = '';
33 private static $db_name = '';
34 private static $db_charset = '';
36 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
38 if (!is_null(self::$db) && self::connected()) {
42 // We are storing these values for being able to perform a reconnect
43 self::$db_serveraddr = $serveraddr;
44 self::$db_user = $user;
45 self::$db_pass = $pass;
47 self::$db_charset = $charset;
49 $serveraddr = trim($serveraddr);
51 $serverdata = explode(':', $serveraddr);
52 $server = $serverdata[0];
54 if (count($serverdata) > 1) {
55 $port = trim($serverdata[1]);
58 $server = trim($server);
62 $charset = trim($charset);
64 if (!(strlen($server) && strlen($user))) {
68 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
69 self::$driver = 'pdo';
70 $connect = "mysql:host=".$server.";dbname=".$db;
73 $connect .= ";port=".$port;
77 $connect .= ";charset=".$charset;
81 self::$db = @new PDO($connect, $user, $pass);
82 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
83 self::$connected = true;
84 } catch (PDOException $e) {
88 if (!self::$connected && class_exists('mysqli')) {
89 self::$driver = 'mysqli';
90 self::$db = @new mysqli($server, $user, $pass, $db, $port);
91 if (!mysqli_connect_errno()) {
92 self::$connected = true;
95 self::$db->set_charset($charset);
100 // No suitable SQL driver was found.
101 if (!self::$connected) {
102 self::$driver = null;
106 return self::$connected;
110 * Disconnects the current database connection
112 public static function disconnect()
114 if (is_null(self::$db)) {
118 switch (self::$driver) {
130 * Perform a reconnect of an existing database connection
132 public static function reconnect() {
135 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
140 * Return the database object.
143 public static function get_db()
149 * @brief Returns the MySQL server version string
151 * This function discriminate between the deprecated mysql API and the current
152 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
156 public static function server_info() {
157 if (self::$_server_info == '') {
158 switch (self::$driver) {
160 self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
163 self::$_server_info = self::$db->server_info;
167 return self::$_server_info;
171 * @brief Returns the selected database name
175 public static function database_name() {
176 $ret = self::p("SELECT DATABASE() AS `db`");
177 $data = self::inArray($ret);
178 return $data[0]['db'];
182 * @brief Analyze a database query and log this if some conditions are met.
184 * @param string $query The database query that will be analyzed
186 private static function logIndex($query) {
189 if (empty(Config::get('system', 'db_log_index'))) {
193 // Don't explain an explain statement
194 if (strtolower(substr($query, 0, 7)) == "explain") {
198 // Only do the explain on "select", "update" and "delete"
199 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
203 $r = self::p("EXPLAIN ".$query);
204 if (!DBM::is_result($r)) {
208 $watchlist = explode(',', Config::get('system', 'db_log_index_watch'));
209 $blacklist = explode(',', Config::get('system', 'db_log_index_blacklist'));
211 while ($row = dba::fetch($r)) {
212 if ((intval(Config::get('system', 'db_loglimit_index')) > 0)) {
213 $log = (in_array($row['key'], $watchlist) &&
214 ($row['rows'] >= intval(Config::get('system', 'db_loglimit_index'))));
219 if ((intval(Config::get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval(Config::get('system', 'db_loglimit_index_high')))) {
223 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
228 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
229 @file_put_contents(Config::get('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
230 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
231 basename($backtrace[1]["file"])."\t".
232 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
233 substr($query, 0, 2000)."\n", FILE_APPEND);
238 public static function escape($str) {
239 switch (self::$driver) {
241 return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
243 return @self::$db->real_escape_string($str);
247 public static function connected() {
250 switch (self::$driver) {
252 $r = dba::p("SELECT 1");
253 if (DBM::is_result($r)) {
254 $row = dba::inArray($r);
255 $connected = ($row[0]['1'] == '1');
259 $connected = self::$db->ping();
266 * @brief Replaces ANY_VALUE() function by MIN() function,
267 * if the database server does not support ANY_VALUE().
269 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
270 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
271 * A standard fall-back is to use MIN().
273 * @param string $sql An SQL string without the values
274 * @return string The input SQL string modified if necessary.
276 public static function any_value_fallback($sql) {
277 $server_info = self::server_info();
278 if (version_compare($server_info, '5.7.5', '<') ||
279 (stripos($server_info, 'MariaDB') !== false)) {
280 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
286 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
288 * This is safe when we bind the parameters later.
289 * The parameter values aren't part of the SQL.
291 * @param string $sql An SQL string without the values
292 * @return string The input SQL string modified if necessary.
294 public static function clean_query($sql) {
295 $search = ["\t", "\n", "\r", " "];
296 $replace = [' ', ' ', ' ', ' '];
299 $sql = str_replace($search, $replace, $sql);
300 } while ($oldsql != $sql);
307 * @brief Replaces the ? placeholders with the parameters in the $args array
309 * @param string $sql SQL query
310 * @param array $args The parameters that are to replace the ? placeholders
311 * @return string The replaced SQL query
313 private static function replaceParameters($sql, $args) {
315 foreach ($args AS $param => $value) {
316 if (is_int($args[$param]) || is_float($args[$param])) {
317 $replace = intval($args[$param]);
319 $replace = "'".self::escape($args[$param])."'";
322 $pos = strpos($sql, '?', $offset);
323 if ($pos !== false) {
324 $sql = substr_replace($sql, $replace, $pos, 1);
326 $offset = $pos + strlen($replace);
332 * @brief Convert parameter array to an universal form
333 * @param array $args Parameter array
334 * @return array universalized parameter array
336 private static function getParam($args) {
339 // When the second function parameter is an array then use this as the parameter array
340 if ((count($args) > 0) && (is_array($args[1]))) {
348 * @brief Executes a prepared statement that returns data
349 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
351 * Please only use it with complicated queries.
352 * For all regular queries please use dba::select or dba::exists
354 * @param string $sql SQL statement
355 * @return bool|object statement object or result object
357 public static function p($sql) {
360 $stamp1 = microtime(true);
362 $params = self::getParam(func_get_args());
364 // Renumber the array keys to be sure that they fit
367 foreach ($params AS $param) {
368 // Avoid problems with some MySQL servers and boolean values. See issue #3645
369 if (is_bool($param)) {
370 $param = (int)$param;
372 $args[++$i] = $param;
375 if (!self::$connected) {
379 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
380 // Question: Should we continue or stop the query here?
381 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
384 $sql = self::clean_query($sql);
385 $sql = self::any_value_fallback($sql);
389 if ($a->getConfigValue('system', 'db_callstack')) {
390 $sql = "/*".System::callstack()." */ ".$sql;
395 self::$affected_rows = 0;
397 // We have to make some things different if this function is called from "e"
398 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
400 if (isset($trace[1])) {
401 $called_from = $trace[1];
403 // We use just something that is defined to avoid warnings
404 $called_from = $trace[0];
406 // We are having an own error logging in the function "e"
407 $called_from_e = ($called_from['function'] == 'e');
409 switch (self::$driver) {
411 // If there are no arguments we use "query"
412 if (count($args) == 0) {
413 if (!$retval = self::$db->query($sql)) {
414 $errorInfo = self::$db->errorInfo();
415 self::$error = $errorInfo[2];
416 self::$errorno = $errorInfo[1];
420 self::$affected_rows = $retval->rowCount();
424 if (!$stmt = self::$db->prepare($sql)) {
425 $errorInfo = self::$db->errorInfo();
426 self::$error = $errorInfo[2];
427 self::$errorno = $errorInfo[1];
432 foreach ($args AS $param => $value) {
433 if (is_int($args[$param])) {
434 $data_type = PDO::PARAM_INT;
436 $data_type = PDO::PARAM_STR;
438 $stmt->bindParam($param, $args[$param], $data_type);
441 if (!$stmt->execute()) {
442 $errorInfo = $stmt->errorInfo();
443 self::$error = $errorInfo[2];
444 self::$errorno = $errorInfo[1];
448 self::$affected_rows = $retval->rowCount();
452 // There are SQL statements that cannot be executed with a prepared statement
453 $parts = explode(' ', $orig_sql);
454 $command = strtolower($parts[0]);
455 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
457 // The fallback routine is called as well when there are no arguments
458 if (!$can_be_prepared || (count($args) == 0)) {
459 $retval = self::$db->query(self::replaceParameters($sql, $args));
460 if (self::$db->errno) {
461 self::$error = self::$db->error;
462 self::$errorno = self::$db->errno;
465 if (isset($retval->num_rows)) {
466 self::$affected_rows = $retval->num_rows;
468 self::$affected_rows = self::$db->affected_rows;
474 $stmt = self::$db->stmt_init();
476 if (!$stmt->prepare($sql)) {
477 self::$error = $stmt->error;
478 self::$errorno = $stmt->errno;
485 foreach ($args AS $param => $value) {
486 if (is_int($args[$param])) {
488 } elseif (is_float($args[$param])) {
490 } elseif (is_string($args[$param])) {
495 $values[] = &$args[$param];
498 if (count($values) > 0) {
499 array_unshift($values, $param_types);
500 call_user_func_array([$stmt, 'bind_param'], $values);
503 if (!$stmt->execute()) {
504 self::$error = self::$db->error;
505 self::$errorno = self::$db->errno;
508 $stmt->store_result();
510 self::$affected_rows = $retval->affected_rows;
515 // We are having an own error logging in the function "e"
516 if ((self::$errorno != 0) && !$called_from_e) {
517 // We have to preserve the error code, somewhere in the logging it get lost
518 $error = self::$error;
519 $errorno = self::$errorno;
521 logger('DB Error '.self::$errorno.': '.self::$error."\n".
522 System::callstack(8)."\n".self::replaceParameters($sql, $args));
524 // On a lost connection we try to reconnect - but only once.
525 if ($errorno == 2006) {
526 if (self::$in_retrial || !self::reconnect()) {
527 // It doesn't make sense to continue when the database connection was lost
528 if (self::$in_retrial) {
529 logger('Giving up retrial because of database error '.$errorno.': '.$error);
531 logger("Couldn't reconnect after database error ".$errorno.': '.$error);
536 logger('Reconnected after database error '.$errorno.': '.$error);
537 self::$in_retrial = true;
538 $ret = self::p($sql, $args);
539 self::$in_retrial = false;
544 self::$error = $error;
545 self::$errorno = $errorno;
548 $a->save_timestamp($stamp1, 'database');
550 if ($a->getConfigValue('system', 'db_log')) {
551 $stamp2 = microtime(true);
552 $duration = (float)($stamp2 - $stamp1);
554 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
555 $duration = round($duration, 3);
556 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
558 @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
559 basename($backtrace[1]["file"])."\t".
560 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
561 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
568 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
570 * Please use dba::delete, dba::insert, dba::update, ... instead
572 * @param string $sql SQL statement
573 * @return boolean Was the query successfull? False is returned only if an error occurred
575 public static function e($sql) {
578 $stamp = microtime(true);
580 $params = self::getParam(func_get_args());
582 // In a case of a deadlock we are repeating the query 20 times
586 $stmt = self::p($sql, $params);
588 if (is_bool($stmt)) {
590 } elseif (is_object($stmt)) {
598 } while ((self::$errorno == 1213) && (--$timeout > 0));
600 if (self::$errorno != 0) {
601 // We have to preserve the error code, somewhere in the logging it get lost
602 $error = self::$error;
603 $errorno = self::$errorno;
605 logger('DB Error '.self::$errorno.': '.self::$error."\n".
606 System::callstack(8)."\n".self::replaceParameters($sql, $params));
608 // On a lost connection we simply quit.
609 // A reconnect like in self::p could be dangerous with modifications
610 if ($errorno == 2006) {
611 logger('Giving up because of database error '.$errorno.': '.$error);
615 self::$error = $error;
616 self::$errorno = $errorno;
619 $a->save_timestamp($stamp, "database_write");
625 * @brief Check if data exists
627 * @param string $table Table name
628 * @param array $condition array of fields for condition
630 * @return boolean Are there rows for that condition?
632 public static function exists($table, $condition) {
640 $first_key = key($condition);
641 if (!is_int($first_key)) {
642 $fields = [$first_key];
645 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
647 if (is_bool($stmt)) {
650 $retval = (self::num_rows($stmt) > 0);
659 * Fetches the first row
661 * Please use dba::selectFirst or dba::exists whenever this is possible.
663 * @brief Fetches the first row
664 * @param string $sql SQL statement
665 * @return array first row of query
667 public static function fetch_first($sql) {
668 $params = self::getParam(func_get_args());
670 $stmt = self::p($sql, $params);
672 if (is_bool($stmt)) {
675 $retval = self::fetch($stmt);
684 * @brief Returns the number of affected rows of the last statement
686 * @return int Number of rows
688 public static function affected_rows() {
689 return self::$affected_rows;
693 * @brief Returns the number of columns of a statement
695 * @param object Statement object
696 * @return int Number of columns
698 public static function columnCount($stmt) {
699 if (!is_object($stmt)) {
702 switch (self::$driver) {
704 return $stmt->columnCount();
706 return $stmt->field_count;
711 * @brief Returns the number of rows of a statement
713 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
714 * @return int Number of rows
716 public static function num_rows($stmt) {
717 if (!is_object($stmt)) {
720 switch (self::$driver) {
722 return $stmt->rowCount();
724 return $stmt->num_rows;
730 * @brief Fetch a single row
732 * @param mixed $stmt statement object
733 * @return array current row
735 public static function fetch($stmt) {
738 $stamp1 = microtime(true);
742 if (!is_object($stmt)) {
746 switch (self::$driver) {
748 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
751 if (get_class($stmt) == 'mysqli_result') {
752 $columns = $stmt->fetch_assoc();
756 // This code works, but is slow
758 // Bind the result to a result array
762 for ($x = 0; $x < $stmt->field_count; $x++) {
763 $cols[] = &$cols_num[$x];
766 call_user_func_array([$stmt, 'bind_result'], $cols);
768 if (!$stmt->fetch()) {
773 // We need to get the field names for the array keys
774 // It seems that there is no better way to do this.
775 $result = $stmt->result_metadata();
776 $fields = $result->fetch_fields();
778 foreach ($cols_num AS $param => $col) {
779 $columns[$fields[$param]->name] = $col;
783 $a->save_timestamp($stamp1, 'database');
789 * @brief Insert a row into a table
791 * @param string $table Table name
792 * @param array $param parameter array
793 * @param bool $on_duplicate_update Do an update on a duplicate entry
795 * @return boolean was the insert successfull?
797 public static function insert($table, $param, $on_duplicate_update = false) {
799 if (empty($table) || empty($param)) {
800 logger('Table and fields have to be set');
804 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
805 substr(str_repeat("?, ", count($param)), 0, -2).")";
807 if ($on_duplicate_update) {
808 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
810 $values = array_values($param);
811 $param = array_merge_recursive($values, $values);
814 return self::e($sql, $param);
818 * @brief Fetch the id of the last insert command
820 * @return integer Last inserted id
822 public static function lastInsertId() {
823 switch (self::$driver) {
825 $id = self::$db->lastInsertId();
828 $id = self::$db->insert_id;
835 * @brief Locks a table for exclusive write access
837 * This function can be extended in the future to accept a table array as well.
839 * @param string $table Table name
841 * @return boolean was the lock successful?
843 public static function lock($table) {
844 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
845 if (self::$driver == 'pdo') {
846 self::e("SET autocommit=0");
847 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
849 self::$db->autocommit(false);
852 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
854 if (self::$driver == 'pdo') {
855 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
859 if (self::$driver == 'pdo') {
860 self::e("SET autocommit=1");
862 self::$db->autocommit(true);
865 self::$in_transaction = true;
871 * @brief Unlocks all locked tables
873 * @return boolean was the unlock successful?
875 public static function unlock() {
876 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
877 self::performCommit();
879 if (self::$driver == 'pdo') {
880 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
883 $success = self::e("UNLOCK TABLES");
885 if (self::$driver == 'pdo') {
886 self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
887 self::e("SET autocommit=1");
889 self::$db->autocommit(true);
892 self::$in_transaction = false;
897 * @brief Starts a transaction
899 * @return boolean Was the command executed successfully?
901 public static function transaction() {
902 if (!self::performCommit()) {
906 switch (self::$driver) {
908 if (self::$db->inTransaction()) {
911 if (!self::$db->beginTransaction()) {
916 if (!self::$db->begin_transaction()) {
922 self::$in_transaction = true;
926 private static function performCommit()
928 switch (self::$driver) {
930 if (!self::$db->inTransaction()) {
933 return self::$db->commit();
935 return self::$db->commit();
941 * @brief Does a commit
943 * @return boolean Was the command executed successfully?
945 public static function commit() {
946 if (!self::performCommit()) {
949 self::$in_transaction = false;
954 * @brief Does a rollback
956 * @return boolean Was the command executed successfully?
958 public static function rollback() {
961 switch (self::$driver) {
963 if (!self::$db->inTransaction()) {
967 $ret = self::$db->rollBack();
970 $ret = self::$db->rollback();
973 self::$in_transaction = false;
978 * @brief Build the array with the table relations
980 * The array is build from the database definitions in DBStructure.php
982 * This process must only be started once, since the value is cached.
984 private static function buildRelationData() {
985 $definition = DBStructure::definition();
987 foreach ($definition AS $table => $structure) {
988 foreach ($structure['fields'] AS $field => $field_struct) {
989 if (isset($field_struct['relation'])) {
990 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
991 self::$relation[$rel_table][$rel_field][$table][] = $field;
999 * @brief Delete a row from a table
1001 * @param string $table Table name
1002 * @param array $conditions Field condition(s)
1003 * @param array $options
1004 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1005 * relations (default: true)
1006 * @param boolean $in_process Internal use: Only do a commit after the last delete
1007 * @param array $callstack Internal use: prevent endless loops
1009 * @return boolean|array was the delete successful? When $in_process is set: deletion data
1011 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
1013 if (empty($table) || empty($conditions)) {
1014 logger('Table and conditions have to be set');
1020 // Create a key for the loop prevention
1021 $key = $table . ':' . json_encode($conditions);
1023 // We quit when this key already exists in the callstack.
1024 if (isset($callstack[$key])) {
1028 $callstack[$key] = true;
1030 $table = self::escape($table);
1032 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1034 $cascade = defaults($options, 'cascade', true);
1036 // To speed up the whole process we cache the table relations
1037 if ($cascade && count(self::$relation) == 0) {
1038 self::buildRelationData();
1041 // Is there a relation entry for the table?
1042 if ($cascade && isset(self::$relation[$table])) {
1043 // We only allow a simple "one field" relation.
1044 $field = array_keys(self::$relation[$table])[0];
1045 $rel_def = array_values(self::$relation[$table])[0];
1047 // Create a key for preventing double queries
1048 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1050 // When the search field is the relation field, we don't need to fetch the rows
1051 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1052 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1053 foreach ($rel_def AS $rel_table => $rel_fields) {
1054 foreach ($rel_fields AS $rel_field) {
1055 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
1056 $commands = array_merge($commands, $retval);
1059 // We quit when this key already exists in the callstack.
1060 } elseif (!isset($callstack[$qkey])) {
1062 $callstack[$qkey] = true;
1064 // Fetch all rows that are to be deleted
1065 $data = self::select($table, [$field], $conditions);
1067 while ($row = self::fetch($data)) {
1068 // Now we accumulate the delete commands
1069 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
1070 $commands = array_merge($commands, $retval);
1075 // Since we had split the delete command we don't need the original command anymore
1076 unset($commands[$key]);
1081 // Now we finalize the process
1082 $do_transaction = !self::$in_transaction;
1084 if ($do_transaction) {
1085 self::transaction();
1091 foreach ($commands AS $command) {
1092 $conditions = $command['conditions'];
1094 $first_key = key($conditions);
1096 $condition_string = self::buildCondition($conditions);
1098 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1099 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1100 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
1102 if (!self::e($sql, $conditions)) {
1103 if ($do_transaction) {
1109 $key_table = $command['table'];
1110 $key_condition = array_keys($command['conditions'])[0];
1111 $value = array_values($command['conditions'])[0];
1113 // Split the SQL queries in chunks of 100 values
1114 // We do the $i stuff here to make the code better readable
1115 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1116 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1120 $compacted[$key_table][$key_condition][$i][$value] = $value;
1121 $counter[$key_table][$key_condition] = $i;
1124 foreach ($compacted AS $table => $values) {
1125 foreach ($values AS $field => $field_value_list) {
1126 foreach ($field_value_list AS $field_values) {
1127 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1128 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1130 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1132 if (!self::e($sql, $field_values)) {
1133 if ($do_transaction) {
1141 if ($do_transaction) {
1151 * @brief Updates rows
1153 * Updates rows in the database. When $old_fields is set to an array,
1154 * the system will only do an update if the fields in that array changed.
1157 * Only the values in $old_fields are compared.
1158 * This is an intentional behaviour.
1161 * We include the timestamp field in $fields but not in $old_fields.
1162 * Then the row will only get the new timestamp when the other fields had changed.
1164 * When $old_fields is set to a boolean value the system will do this compare itself.
1165 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1168 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1169 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1171 * @param string $table Table name
1172 * @param array $fields contains the fields that are updated
1173 * @param array $condition condition array with the key values
1174 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1176 * @return boolean was the update successfull?
1178 public static function update($table, $fields, $condition, $old_fields = []) {
1180 if (empty($table) || empty($fields) || empty($condition)) {
1181 logger('Table, fields and condition have to be set');
1185 $table = self::escape($table);
1187 $condition_string = self::buildCondition($condition);
1189 if (is_bool($old_fields)) {
1190 $do_insert = $old_fields;
1192 $old_fields = self::selectFirst($table, [], $condition);
1194 if (is_bool($old_fields)) {
1196 $values = array_merge($condition, $fields);
1197 return self::insert($table, $values, $do_insert);
1203 $do_update = (count($old_fields) == 0);
1205 foreach ($old_fields AS $fieldname => $content) {
1206 if (isset($fields[$fieldname])) {
1207 if ($fields[$fieldname] == $content) {
1208 unset($fields[$fieldname]);
1215 if (!$do_update || (count($fields) == 0)) {
1219 $sql = "UPDATE `".$table."` SET `".
1220 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1222 $params1 = array_values($fields);
1223 $params2 = array_values($condition);
1224 $params = array_merge_recursive($params1, $params2);
1226 return self::e($sql, $params);
1230 * Retrieve a single record from a table and returns it in an associative array
1232 * @brief Retrieve a single record from a table
1233 * @param string $table
1234 * @param array $fields
1235 * @param array $condition
1236 * @param array $params
1237 * @return bool|array
1240 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1242 $params['limit'] = 1;
1243 $result = self::select($table, $fields, $condition, $params);
1245 if (is_bool($result)) {
1248 $row = self::fetch($result);
1249 self::close($result);
1255 * @brief Select rows from a table
1257 * @param string $table Table name
1258 * @param array $fields Array of selected fields, empty for all
1259 * @param array $condition Array of fields for condition
1260 * @param array $params Array of several parameters
1262 * @return boolean|object
1266 * $fields = array("id", "uri", "uid", "network");
1268 * $condition = array("uid" => 1, "network" => 'dspr');
1270 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1272 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1274 * $data = dba::select($table, $fields, $condition, $params);
1276 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1282 $table = self::escape($table);
1284 if (count($fields) > 0) {
1285 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1287 $select_fields = "*";
1290 $condition_string = self::buildCondition($condition);
1292 $param_string = self::buildParameter($params);
1294 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1296 $result = self::p($sql, $condition);
1302 * @brief Counts the rows from a table satisfying the provided condition
1304 * @param string $table Table name
1305 * @param array $condition array of fields for condition
1312 * $condition = ["uid" => 1, "network" => 'dspr'];
1314 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1316 * $count = dba::count($table, $condition);
1318 public static function count($table, array $condition = [])
1324 $condition_string = self::buildCondition($condition);
1326 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1328 $row = self::fetch_first($sql, $condition);
1330 return $row['count'];
1334 * @brief Returns the SQL condition string built from the provided condition array
1336 * This function operates with two modes.
1337 * - Supplied with a filed/value associative array, it builds simple strict
1338 * equality conditions linked by AND.
1339 * - Supplied with a flat list, the first element is the condition string and
1340 * the following arguments are the values to be interpolated
1342 * $condition = ["uid" => 1, "network" => 'dspr'];
1344 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1346 * In either case, the provided array is left with the parameters only
1348 * @param array $condition
1351 public static function buildCondition(array &$condition = [])
1353 $condition_string = '';
1354 if (count($condition) > 0) {
1356 $first_key = key($condition);
1357 if (is_int($first_key)) {
1358 $condition_string = " WHERE (" . array_shift($condition) . ")";
1361 $condition_string = "";
1362 foreach ($condition as $field => $value) {
1363 if ($condition_string != "") {
1364 $condition_string .= " AND ";
1366 if (is_array($value)) {
1367 /* Workaround for MySQL Bug #64791.
1368 * Never mix data types inside any IN() condition.
1369 * In case of mixed types, cast all as string.
1370 * Logic needs to be consistent with dba::p() data types.
1374 foreach ($value as $single_value) {
1375 if (is_int($single_value)) {
1382 if ($is_int && $is_alpha) {
1383 foreach ($value as &$ref) {
1385 $ref = (string)$ref;
1388 unset($ref); //Prevent accidental re-use.
1391 $new_values = array_merge($new_values, array_values($value));
1392 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1393 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1395 $new_values[$field] = $value;
1396 $condition_string .= "`" . $field . "` = ?";
1399 $condition_string = " WHERE (" . $condition_string . ")";
1400 $condition = $new_values;
1404 return $condition_string;
1408 * @brief Returns the SQL parameter string built from the provided parameter array
1410 * @param array $params
1413 public static function buildParameter(array $params = [])
1416 if (isset($params['order'])) {
1417 $order_string = " ORDER BY ";
1418 foreach ($params['order'] AS $fields => $order) {
1419 if (!is_int($fields)) {
1420 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1422 $order_string .= "`" . $order . "`, ";
1425 $order_string = substr($order_string, 0, -2);
1429 if (isset($params['limit']) && is_int($params['limit'])) {
1430 $limit_string = " LIMIT " . $params['limit'];
1433 if (isset($params['limit']) && is_array($params['limit'])) {
1434 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1437 return $order_string.$limit_string;
1441 * @brief Fills an array with data from a query
1443 * @param object $stmt statement object
1444 * @return array Data array
1446 public static function inArray($stmt, $do_close = true) {
1447 if (is_bool($stmt)) {
1452 while ($row = self::fetch($stmt)) {
1462 * @brief Returns the error number of the last query
1464 * @return string Error number (0 if no error)
1466 public static function errorNo() {
1467 return self::$errorno;
1471 * @brief Returns the error message of the last query
1473 * @return string Error message ('' if no error)
1475 public static function errorMessage() {
1476 return self::$error;
1480 * @brief Closes the current statement
1482 * @param object $stmt statement object
1483 * @return boolean was the close successful?
1485 public static function close($stmt) {
1488 $stamp1 = microtime(true);
1490 if (!is_object($stmt)) {
1494 switch (self::$driver) {
1496 $ret = $stmt->closeCursor();
1499 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1500 // We should be careful not to assume the object type of $stmt
1501 // because dba::p() has been able to return both types.
1502 if ($stmt instanceof mysqli_stmt) {
1503 $stmt->free_result();
1504 $ret = $stmt->close();
1505 } elseif ($stmt instanceof mysqli_result) {
1514 $a->save_timestamp($stamp1, 'database');
1520 function dbesc($str) {
1521 if (dba::$connected) {
1522 return(dba::escape($str));
1524 return(str_replace("'","\\'",$str));
1529 * @brief execute SQL query with printf style args - deprecated
1531 * Please use the dba:: functions instead:
1532 * dba::select, dba::exists, dba::insert
1533 * dba::delete, dba::update, dba::p, dba::e
1535 * @param $args Query parameters (1 to N parameters of different types)
1536 * @return array|bool Query array
1539 $args = func_get_args();
1542 if (!dba::$connected) {
1546 $sql = dba::clean_query($sql);
1547 $sql = dba::any_value_fallback($sql);
1549 $stmt = @vsprintf($sql, $args);
1551 $ret = dba::p($stmt);
1553 if (is_bool($ret)) {
1557 $columns = dba::columnCount($ret);
1559 $data = dba::inArray($ret);
1561 if ((count($data) == 0) && ($columns == 0)) {
1568 function dba_timer() {
1569 return microtime(true);