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;
19 require_once 'include/dba.php';
22 * @class MySQL database class
24 * This class is for the low level database stuff that does driver specific things.
29 * Lowest possible date value
31 const NULL_DATE = '0001-01-01';
33 * Lowest possible datetime value
35 const NULL_DATETIME = '0001-01-01 00:00:00';
37 public static $connected = false;
39 private static $server_info = '';
40 private static $connection;
41 private static $driver;
42 private static $error = false;
43 private static $errorno = 0;
44 private static $affected_rows = 0;
45 private static $in_transaction = false;
46 private static $in_retrial = false;
47 private static $relation = [];
48 private static $db_serveraddr = '';
49 private static $db_user = '';
50 private static $db_pass = '';
51 private static $db_name = '';
52 private static $db_charset = '';
54 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
56 if (!is_null(self::$connection) && self::connected()) {
60 // We are storing these values for being able to perform a reconnect
61 self::$db_serveraddr = $serveraddr;
62 self::$db_user = $user;
63 self::$db_pass = $pass;
65 self::$db_charset = $charset;
68 $serveraddr = trim($serveraddr);
70 $serverdata = explode(':', $serveraddr);
71 $server = $serverdata[0];
73 if (count($serverdata) > 1) {
74 $port = trim($serverdata[1]);
77 $server = trim($server);
81 $charset = trim($charset);
83 if (!(strlen($server) && strlen($user))) {
87 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
88 self::$driver = 'pdo';
89 $connect = "mysql:host=".$server.";dbname=".$db;
92 $connect .= ";port=".$port;
96 $connect .= ";charset=".$charset;
100 self::$connection = @new PDO($connect, $user, $pass);
101 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
102 self::$connected = true;
103 } catch (PDOException $e) {
104 /// @TODO At least log exception, don't ignore it!
108 if (!self::$connected && class_exists('\mysqli')) {
109 self::$driver = 'mysqli';
112 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
114 self::$connection = @new mysqli($server, $user, $pass, $db);
117 if (!mysqli_connect_errno()) {
118 self::$connected = true;
121 self::$connection->set_charset($charset);
126 // No suitable SQL driver was found.
127 if (!self::$connected) {
128 self::$driver = null;
129 self::$connection = null;
132 return self::$connected;
136 * Disconnects the current database connection
138 public static function disconnect()
140 if (is_null(self::$connection)) {
144 switch (self::$driver) {
146 self::$connection = null;
149 self::$connection->close();
150 self::$connection = null;
156 * Perform a reconnect of an existing database connection
158 public static function reconnect() {
161 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
166 * Return the database object.
169 public static function getConnection()
171 return self::$connection;
175 * @brief Returns the MySQL server version string
177 * This function discriminate between the deprecated mysql API and the current
178 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
182 public static function serverInfo() {
183 if (self::$server_info == '') {
184 switch (self::$driver) {
186 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
189 self::$server_info = self::$connection->server_info;
193 return self::$server_info;
197 * @brief Returns the selected database name
201 public static function databaseName() {
202 $ret = self::p("SELECT DATABASE() AS `db`");
203 $data = self::toArray($ret);
204 return $data[0]['db'];
208 * @brief Analyze a database query and log this if some conditions are met.
210 * @param string $query The database query that will be analyzed
212 private static function logIndex($query) {
215 if (!$a->getConfigVariable('system', 'db_log_index')) {
219 // Don't explain an explain statement
220 if (strtolower(substr($query, 0, 7)) == "explain") {
224 // Only do the explain on "select", "update" and "delete"
225 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
229 $r = self::p("EXPLAIN ".$query);
230 if (!self::isResult($r)) {
234 $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch'));
235 $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist'));
237 while ($row = self::fetch($r)) {
238 if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) {
239 $log = (in_array($row['key'], $watchlist) &&
240 ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index'))));
245 if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) {
249 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
254 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
255 @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
256 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
257 basename($backtrace[1]["file"])."\t".
258 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
259 substr($query, 0, 2000)."\n", FILE_APPEND);
264 public static function escape($str) {
265 if (self::$connected) {
266 switch (self::$driver) {
268 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
271 return @self::$connection->real_escape_string($str);
274 return str_replace("'", "\\'", $str);
278 public static function connected() {
281 if (is_null(self::$connection)) {
285 switch (self::$driver) {
287 $r = self::p("SELECT 1");
288 if (self::isResult($r)) {
289 $row = self::toArray($r);
290 $connected = ($row[0]['1'] == '1');
294 $connected = self::$connection->ping();
301 * @brief Replaces ANY_VALUE() function by MIN() function,
302 * if the database server does not support ANY_VALUE().
304 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
305 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
306 * A standard fall-back is to use MIN().
308 * @param string $sql An SQL string without the values
309 * @return string The input SQL string modified if necessary.
311 public static function anyValueFallback($sql) {
312 $server_info = self::serverInfo();
313 if (version_compare($server_info, '5.7.5', '<') ||
314 (stripos($server_info, 'MariaDB') !== false)) {
315 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
321 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
323 * This is safe when we bind the parameters later.
324 * The parameter values aren't part of the SQL.
326 * @param string $sql An SQL string without the values
327 * @return string The input SQL string modified if necessary.
329 public static function cleanQuery($sql) {
330 $search = ["\t", "\n", "\r", " "];
331 $replace = [' ', ' ', ' ', ' '];
334 $sql = str_replace($search, $replace, $sql);
335 } while ($oldsql != $sql);
342 * @brief Replaces the ? placeholders with the parameters in the $args array
344 * @param string $sql SQL query
345 * @param array $args The parameters that are to replace the ? placeholders
346 * @return string The replaced SQL query
348 private static function replaceParameters($sql, $args) {
350 foreach ($args AS $param => $value) {
351 if (is_int($args[$param]) || is_float($args[$param])) {
352 $replace = intval($args[$param]);
354 $replace = "'".self::escape($args[$param])."'";
357 $pos = strpos($sql, '?', $offset);
358 if ($pos !== false) {
359 $sql = substr_replace($sql, $replace, $pos, 1);
361 $offset = $pos + strlen($replace);
367 * @brief Convert parameter array to an universal form
368 * @param array $args Parameter array
369 * @return array universalized parameter array
371 private static function getParam($args) {
374 // When the second function parameter is an array then use this as the parameter array
375 if ((count($args) > 0) && (is_array($args[1]))) {
383 * @brief Executes a prepared statement that returns data
384 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
386 * Please only use it with complicated queries.
387 * For all regular queries please use DBA::select or DBA::exists
389 * @param string $sql SQL statement
390 * @return bool|object statement object or result object
392 public static function p($sql) {
395 $stamp1 = microtime(true);
397 $params = self::getParam(func_get_args());
399 // Renumber the array keys to be sure that they fit
402 foreach ($params AS $param) {
403 // Avoid problems with some MySQL servers and boolean values. See issue #3645
404 if (is_bool($param)) {
405 $param = (int)$param;
407 $args[++$i] = $param;
410 if (!self::$connected) {
414 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
415 // Question: Should we continue or stop the query here?
416 Logger::log('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), Logger::DEBUG);
419 $sql = self::cleanQuery($sql);
420 $sql = self::anyValueFallback($sql);
424 if ($a->getConfigValue('system', 'db_callstack')) {
425 $sql = "/*".System::callstack()." */ ".$sql;
430 self::$affected_rows = 0;
432 // We have to make some things different if this function is called from "e"
433 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
435 if (isset($trace[1])) {
436 $called_from = $trace[1];
438 // We use just something that is defined to avoid warnings
439 $called_from = $trace[0];
441 // We are having an own error logging in the function "e"
442 $called_from_e = ($called_from['function'] == 'e');
444 switch (self::$driver) {
446 // If there are no arguments we use "query"
447 if (count($args) == 0) {
448 if (!$retval = self::$connection->query($sql)) {
449 $errorInfo = self::$connection->errorInfo();
450 self::$error = $errorInfo[2];
451 self::$errorno = $errorInfo[1];
455 self::$affected_rows = $retval->rowCount();
459 if (!$stmt = self::$connection->prepare($sql)) {
460 $errorInfo = self::$connection->errorInfo();
461 self::$error = $errorInfo[2];
462 self::$errorno = $errorInfo[1];
467 foreach ($args AS $param => $value) {
468 if (is_int($args[$param])) {
469 $data_type = PDO::PARAM_INT;
471 $data_type = PDO::PARAM_STR;
473 $stmt->bindParam($param, $args[$param], $data_type);
476 if (!$stmt->execute()) {
477 $errorInfo = $stmt->errorInfo();
478 self::$error = $errorInfo[2];
479 self::$errorno = $errorInfo[1];
483 self::$affected_rows = $retval->rowCount();
487 // There are SQL statements that cannot be executed with a prepared statement
488 $parts = explode(' ', $orig_sql);
489 $command = strtolower($parts[0]);
490 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
492 // The fallback routine is called as well when there are no arguments
493 if (!$can_be_prepared || (count($args) == 0)) {
494 $retval = self::$connection->query(self::replaceParameters($sql, $args));
495 if (self::$connection->errno) {
496 self::$error = self::$connection->error;
497 self::$errorno = self::$connection->errno;
500 if (isset($retval->num_rows)) {
501 self::$affected_rows = $retval->num_rows;
503 self::$affected_rows = self::$connection->affected_rows;
509 $stmt = self::$connection->stmt_init();
511 if (!$stmt->prepare($sql)) {
512 self::$error = $stmt->error;
513 self::$errorno = $stmt->errno;
520 foreach ($args AS $param => $value) {
521 if (is_int($args[$param])) {
523 } elseif (is_float($args[$param])) {
525 } elseif (is_string($args[$param])) {
530 $values[] = &$args[$param];
533 if (count($values) > 0) {
534 array_unshift($values, $param_types);
535 call_user_func_array([$stmt, 'bind_param'], $values);
538 if (!$stmt->execute()) {
539 self::$error = self::$connection->error;
540 self::$errorno = self::$connection->errno;
543 $stmt->store_result();
545 self::$affected_rows = $retval->affected_rows;
550 // We are having an own error logging in the function "e"
551 if ((self::$errorno != 0) && !$called_from_e) {
552 // We have to preserve the error code, somewhere in the logging it get lost
553 $error = self::$error;
554 $errorno = self::$errorno;
556 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
557 System::callstack(8)."\n".self::replaceParameters($sql, $args));
559 // On a lost connection we try to reconnect - but only once.
560 if ($errorno == 2006) {
561 if (self::$in_retrial || !self::reconnect()) {
562 // It doesn't make sense to continue when the database connection was lost
563 if (self::$in_retrial) {
564 Logger::log('Giving up retrial because of database error '.$errorno.': '.$error);
566 Logger::log("Couldn't reconnect after database error ".$errorno.': '.$error);
571 Logger::log('Reconnected after database error '.$errorno.': '.$error);
572 self::$in_retrial = true;
573 $ret = self::p($sql, $args);
574 self::$in_retrial = false;
579 self::$error = $error;
580 self::$errorno = $errorno;
583 $a->saveTimestamp($stamp1, 'database');
585 if ($a->getConfigValue('system', 'db_log')) {
586 $stamp2 = microtime(true);
587 $duration = (float)($stamp2 - $stamp1);
589 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
590 $duration = round($duration, 3);
591 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
593 @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
594 basename($backtrace[1]["file"])."\t".
595 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
596 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
603 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
605 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
607 * @param string $sql SQL statement
608 * @return boolean Was the query successfull? False is returned only if an error occurred
610 public static function e($sql) {
613 $stamp = microtime(true);
615 $params = self::getParam(func_get_args());
617 // In a case of a deadlock we are repeating the query 20 times
621 $stmt = self::p($sql, $params);
623 if (is_bool($stmt)) {
625 } elseif (is_object($stmt)) {
633 } while ((self::$errorno == 1213) && (--$timeout > 0));
635 if (self::$errorno != 0) {
636 // We have to preserve the error code, somewhere in the logging it get lost
637 $error = self::$error;
638 $errorno = self::$errorno;
640 Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
641 System::callstack(8)."\n".self::replaceParameters($sql, $params));
643 // On a lost connection we simply quit.
644 // A reconnect like in self::p could be dangerous with modifications
645 if ($errorno == 2006) {
646 Logger::log('Giving up because of database error '.$errorno.': '.$error);
650 self::$error = $error;
651 self::$errorno = $errorno;
654 $a->saveTimestamp($stamp, "database_write");
660 * @brief Check if data exists
662 * @param string $table Table name
663 * @param array $condition array of fields for condition
665 * @return boolean Are there rows for that condition?
667 public static function exists($table, $condition) {
674 if (empty($condition)) {
675 return DBStructure::existsTable($table);
679 $first_key = key($condition);
680 if (!is_int($first_key)) {
681 $fields = [$first_key];
684 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
686 if (is_bool($stmt)) {
689 $retval = (self::numRows($stmt) > 0);
698 * Fetches the first row
700 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
702 * @brief Fetches the first row
703 * @param string $sql SQL statement
704 * @return array first row of query
706 public static function fetchFirst($sql) {
707 $params = self::getParam(func_get_args());
709 $stmt = self::p($sql, $params);
711 if (is_bool($stmt)) {
714 $retval = self::fetch($stmt);
723 * @brief Returns the number of affected rows of the last statement
725 * @return int Number of rows
727 public static function affectedRows() {
728 return self::$affected_rows;
732 * @brief Returns the number of columns of a statement
734 * @param object Statement object
735 * @return int Number of columns
737 public static function columnCount($stmt) {
738 if (!is_object($stmt)) {
741 switch (self::$driver) {
743 return $stmt->columnCount();
745 return $stmt->field_count;
750 * @brief Returns the number of rows of a statement
752 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
753 * @return int Number of rows
755 public static function numRows($stmt) {
756 if (!is_object($stmt)) {
759 switch (self::$driver) {
761 return $stmt->rowCount();
763 return $stmt->num_rows;
769 * @brief Fetch a single row
771 * @param mixed $stmt statement object
772 * @return array current row
774 public static function fetch($stmt) {
777 $stamp1 = microtime(true);
781 if (!is_object($stmt)) {
785 switch (self::$driver) {
787 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
790 if (get_class($stmt) == 'mysqli_result') {
791 $columns = $stmt->fetch_assoc();
795 // This code works, but is slow
797 // Bind the result to a result array
801 for ($x = 0; $x < $stmt->field_count; $x++) {
802 $cols[] = &$cols_num[$x];
805 call_user_func_array([$stmt, 'bind_result'], $cols);
807 if (!$stmt->fetch()) {
812 // We need to get the field names for the array keys
813 // It seems that there is no better way to do this.
814 $result = $stmt->result_metadata();
815 $fields = $result->fetch_fields();
817 foreach ($cols_num AS $param => $col) {
818 $columns[$fields[$param]->name] = $col;
822 $a->saveTimestamp($stamp1, 'database');
828 * @brief Insert a row into a table
830 * @param string $table Table name
831 * @param array $param parameter array
832 * @param bool $on_duplicate_update Do an update on a duplicate entry
834 * @return boolean was the insert successful?
836 public static function insert($table, $param, $on_duplicate_update = false) {
838 if (empty($table) || empty($param)) {
839 Logger::log('Table and fields have to be set');
843 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
844 substr(str_repeat("?, ", count($param)), 0, -2).")";
846 if ($on_duplicate_update) {
847 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
849 $values = array_values($param);
850 $param = array_merge_recursive($values, $values);
853 return self::e($sql, $param);
857 * @brief Fetch the id of the last insert command
859 * @return integer Last inserted id
861 public static function lastInsertId() {
862 switch (self::$driver) {
864 $id = self::$connection->lastInsertId();
867 $id = self::$connection->insert_id;
874 * @brief Locks a table for exclusive write access
876 * This function can be extended in the future to accept a table array as well.
878 * @param string $table Table name
880 * @return boolean was the lock successful?
882 public static function lock($table) {
883 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
884 if (self::$driver == 'pdo') {
885 self::e("SET autocommit=0");
886 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
888 self::$connection->autocommit(false);
891 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
893 if (self::$driver == 'pdo') {
894 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
898 if (self::$driver == 'pdo') {
899 self::e("SET autocommit=1");
901 self::$connection->autocommit(true);
904 self::$in_transaction = true;
910 * @brief Unlocks all locked tables
912 * @return boolean was the unlock successful?
914 public static function unlock() {
915 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
916 self::performCommit();
918 if (self::$driver == 'pdo') {
919 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
922 $success = self::e("UNLOCK TABLES");
924 if (self::$driver == 'pdo') {
925 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
926 self::e("SET autocommit=1");
928 self::$connection->autocommit(true);
931 self::$in_transaction = false;
936 * @brief Starts a transaction
938 * @return boolean Was the command executed successfully?
940 public static function transaction() {
941 if (!self::performCommit()) {
945 switch (self::$driver) {
947 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
953 if (!self::$connection->begin_transaction()) {
959 self::$in_transaction = true;
963 private static function performCommit()
965 switch (self::$driver) {
967 if (!self::$connection->inTransaction()) {
971 return self::$connection->commit();
974 return self::$connection->commit();
981 * @brief Does a commit
983 * @return boolean Was the command executed successfully?
985 public static function commit() {
986 if (!self::performCommit()) {
989 self::$in_transaction = false;
994 * @brief Does a rollback
996 * @return boolean Was the command executed successfully?
998 public static function rollback() {
1001 switch (self::$driver) {
1003 if (!self::$connection->inTransaction()) {
1007 $ret = self::$connection->rollBack();
1011 $ret = self::$connection->rollback();
1014 self::$in_transaction = false;
1019 * @brief Build the array with the table relations
1021 * The array is build from the database definitions in DBStructure.php
1023 * This process must only be started once, since the value is cached.
1025 private static function buildRelationData() {
1026 $definition = DBStructure::definition();
1028 foreach ($definition AS $table => $structure) {
1029 foreach ($structure['fields'] AS $field => $field_struct) {
1030 if (isset($field_struct['relation'])) {
1031 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1032 self::$relation[$rel_table][$rel_field][$table][] = $field;
1040 * @brief Delete a row from a table
1042 * @param string $table Table name
1043 * @param array $conditions Field condition(s)
1044 * @param array $options
1045 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1046 * relations (default: true)
1047 * @param boolean $in_process Internal use: Only do a commit after the last delete
1048 * @param array $callstack Internal use: prevent endless loops
1050 * @return boolean|array was the delete successful? When $in_process is set: deletion data
1052 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
1054 if (empty($table) || empty($conditions)) {
1055 Logger::log('Table and conditions have to be set');
1061 // Create a key for the loop prevention
1062 $key = $table . ':' . json_encode($conditions);
1064 // We quit when this key already exists in the callstack.
1065 if (isset($callstack[$key])) {
1069 $callstack[$key] = true;
1071 $table = self::escape($table);
1073 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1075 // Don't use "defaults" here, since it would set "false" to "true"
1076 if (isset($options['cascade'])) {
1077 $cascade = $options['cascade'];
1082 // To speed up the whole process we cache the table relations
1083 if ($cascade && count(self::$relation) == 0) {
1084 self::buildRelationData();
1087 // Is there a relation entry for the table?
1088 if ($cascade && isset(self::$relation[$table])) {
1089 // We only allow a simple "one field" relation.
1090 $field = array_keys(self::$relation[$table])[0];
1091 $rel_def = array_values(self::$relation[$table])[0];
1093 // Create a key for preventing double queries
1094 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1096 // When the search field is the relation field, we don't need to fetch the rows
1097 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1098 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1099 foreach ($rel_def AS $rel_table => $rel_fields) {
1100 foreach ($rel_fields AS $rel_field) {
1101 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
1102 $commands = array_merge($commands, $retval);
1105 // We quit when this key already exists in the callstack.
1106 } elseif (!isset($callstack[$qkey])) {
1108 $callstack[$qkey] = true;
1110 // Fetch all rows that are to be deleted
1111 $data = self::select($table, [$field], $conditions);
1113 while ($row = self::fetch($data)) {
1114 // Now we accumulate the delete commands
1115 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
1116 $commands = array_merge($commands, $retval);
1121 // Since we had split the delete command we don't need the original command anymore
1122 unset($commands[$key]);
1127 // Now we finalize the process
1128 $do_transaction = !self::$in_transaction;
1130 if ($do_transaction) {
1131 self::transaction();
1137 foreach ($commands AS $command) {
1138 $conditions = $command['conditions'];
1140 $first_key = key($conditions);
1142 $condition_string = self::buildCondition($conditions);
1144 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1145 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1146 Logger::log(self::replaceParameters($sql, $conditions), Logger::DATA);
1148 if (!self::e($sql, $conditions)) {
1149 if ($do_transaction) {
1155 $key_table = $command['table'];
1156 $key_condition = array_keys($command['conditions'])[0];
1157 $value = array_values($command['conditions'])[0];
1159 // Split the SQL queries in chunks of 100 values
1160 // We do the $i stuff here to make the code better readable
1161 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1162 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1166 $compacted[$key_table][$key_condition][$i][$value] = $value;
1167 $counter[$key_table][$key_condition] = $i;
1170 foreach ($compacted AS $table => $values) {
1171 foreach ($values AS $field => $field_value_list) {
1172 foreach ($field_value_list AS $field_values) {
1173 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1174 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1176 Logger::log(self::replaceParameters($sql, $field_values), Logger::DATA);
1178 if (!self::e($sql, $field_values)) {
1179 if ($do_transaction) {
1187 if ($do_transaction) {
1197 * @brief Updates rows
1199 * Updates rows in the database. When $old_fields is set to an array,
1200 * the system will only do an update if the fields in that array changed.
1203 * Only the values in $old_fields are compared.
1204 * This is an intentional behaviour.
1207 * We include the timestamp field in $fields but not in $old_fields.
1208 * Then the row will only get the new timestamp when the other fields had changed.
1210 * When $old_fields is set to a boolean value the system will do this compare itself.
1211 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1214 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1215 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1217 * @param string $table Table name
1218 * @param array $fields contains the fields that are updated
1219 * @param array $condition condition array with the key values
1220 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1222 * @return boolean was the update successfull?
1224 public static function update($table, $fields, $condition, $old_fields = []) {
1226 if (empty($table) || empty($fields) || empty($condition)) {
1227 Logger::log('Table, fields and condition have to be set');
1231 $table = self::escape($table);
1233 $condition_string = self::buildCondition($condition);
1235 if (is_bool($old_fields)) {
1236 $do_insert = $old_fields;
1238 $old_fields = self::selectFirst($table, [], $condition);
1240 if (is_bool($old_fields)) {
1242 $values = array_merge($condition, $fields);
1243 return self::insert($table, $values, $do_insert);
1249 $do_update = (count($old_fields) == 0);
1251 foreach ($old_fields AS $fieldname => $content) {
1252 if (isset($fields[$fieldname])) {
1253 if ($fields[$fieldname] == $content) {
1254 unset($fields[$fieldname]);
1261 if (!$do_update || (count($fields) == 0)) {
1265 $sql = "UPDATE `".$table."` SET `".
1266 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1268 $params1 = array_values($fields);
1269 $params2 = array_values($condition);
1270 $params = array_merge_recursive($params1, $params2);
1272 return self::e($sql, $params);
1276 * Retrieve a single record from a table and returns it in an associative array
1278 * @brief Retrieve a single record from a table
1279 * @param string $table
1280 * @param array $fields
1281 * @param array $condition
1282 * @param array $params
1283 * @return bool|array
1286 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1288 $params['limit'] = 1;
1289 $result = self::select($table, $fields, $condition, $params);
1291 if (is_bool($result)) {
1294 $row = self::fetch($result);
1295 self::close($result);
1301 * @brief Select rows from a table
1303 * @param string $table Table name
1304 * @param array $fields Array of selected fields, empty for all
1305 * @param array $condition Array of fields for condition
1306 * @param array $params Array of several parameters
1308 * @return boolean|object
1312 * $fields = array("id", "uri", "uid", "network");
1314 * $condition = array("uid" => 1, "network" => 'dspr');
1316 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1318 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1320 * $data = DBA::select($table, $fields, $condition, $params);
1322 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1328 $table = self::escape($table);
1330 if (count($fields) > 0) {
1331 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1333 $select_fields = "*";
1336 $condition_string = self::buildCondition($condition);
1338 $param_string = self::buildParameter($params);
1340 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1342 $result = self::p($sql, $condition);
1348 * @brief Counts the rows from a table satisfying the provided condition
1350 * @param string $table Table name
1351 * @param array $condition array of fields for condition
1358 * $condition = ["uid" => 1, "network" => 'dspr'];
1360 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1362 * $count = DBA::count($table, $condition);
1364 public static function count($table, array $condition = [])
1370 $condition_string = self::buildCondition($condition);
1372 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1374 $row = self::fetchFirst($sql, $condition);
1376 return $row['count'];
1380 * @brief Returns the SQL condition string built from the provided condition array
1382 * This function operates with two modes.
1383 * - Supplied with a filed/value associative array, it builds simple strict
1384 * equality conditions linked by AND.
1385 * - Supplied with a flat list, the first element is the condition string and
1386 * the following arguments are the values to be interpolated
1388 * $condition = ["uid" => 1, "network" => 'dspr'];
1390 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1392 * In either case, the provided array is left with the parameters only
1394 * @param array $condition
1397 public static function buildCondition(array &$condition = [])
1399 $condition_string = '';
1400 if (count($condition) > 0) {
1402 $first_key = key($condition);
1403 if (is_int($first_key)) {
1404 $condition_string = " WHERE (" . array_shift($condition) . ")";
1407 $condition_string = "";
1408 foreach ($condition as $field => $value) {
1409 if ($condition_string != "") {
1410 $condition_string .= " AND ";
1412 if (is_array($value)) {
1413 /* Workaround for MySQL Bug #64791.
1414 * Never mix data types inside any IN() condition.
1415 * In case of mixed types, cast all as string.
1416 * Logic needs to be consistent with DBA::p() data types.
1420 foreach ($value as $single_value) {
1421 if (is_int($single_value)) {
1428 if ($is_int && $is_alpha) {
1429 foreach ($value as &$ref) {
1431 $ref = (string)$ref;
1434 unset($ref); //Prevent accidental re-use.
1437 $new_values = array_merge($new_values, array_values($value));
1438 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1439 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1441 $new_values[$field] = $value;
1442 $condition_string .= "`" . $field . "` = ?";
1445 $condition_string = " WHERE (" . $condition_string . ")";
1446 $condition = $new_values;
1450 return $condition_string;
1454 * @brief Returns the SQL parameter string built from the provided parameter array
1456 * @param array $params
1459 public static function buildParameter(array $params = [])
1462 if (isset($params['order'])) {
1463 $order_string = " ORDER BY ";
1464 foreach ($params['order'] AS $fields => $order) {
1465 if (!is_int($fields)) {
1466 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1468 $order_string .= "`" . $order . "`, ";
1471 $order_string = substr($order_string, 0, -2);
1475 if (isset($params['limit']) && is_int($params['limit'])) {
1476 $limit_string = " LIMIT " . intval($params['limit']);
1479 if (isset($params['limit']) && is_array($params['limit'])) {
1480 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1483 return $order_string.$limit_string;
1487 * @brief Fills an array with data from a query
1489 * @param object $stmt statement object
1490 * @return array Data array
1492 public static function toArray($stmt, $do_close = true) {
1493 if (is_bool($stmt)) {
1498 while ($row = self::fetch($stmt)) {
1508 * @brief Returns the error number of the last query
1510 * @return string Error number (0 if no error)
1512 public static function errorNo() {
1513 return self::$errorno;
1517 * @brief Returns the error message of the last query
1519 * @return string Error message ('' if no error)
1521 public static function errorMessage() {
1522 return self::$error;
1526 * @brief Closes the current statement
1528 * @param object $stmt statement object
1529 * @return boolean was the close successful?
1531 public static function close($stmt) {
1534 $stamp1 = microtime(true);
1536 if (!is_object($stmt)) {
1540 switch (self::$driver) {
1542 $ret = $stmt->closeCursor();
1545 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1546 // We should be careful not to assume the object type of $stmt
1547 // because DBA::p() has been able to return both types.
1548 if ($stmt instanceof mysqli_stmt) {
1549 $stmt->free_result();
1550 $ret = $stmt->close();
1551 } elseif ($stmt instanceof mysqli_result) {
1560 $a->saveTimestamp($stamp1, 'database');
1566 * @brief Return a list of database processes
1569 * 'list' => List of processes, separated in their different states
1570 * 'amount' => Number of concurrent database processes
1572 public static function processlist()
1574 $ret = self::p("SHOW PROCESSLIST");
1575 $data = self::toArray($ret);
1581 foreach ($data as $process) {
1582 $state = trim($process["State"]);
1584 // Filter out all non blocking processes
1585 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1592 foreach ($states as $state => $usage) {
1593 if ($statelist != "") {
1596 $statelist .= $state.": ".$usage;
1598 return(["list" => $statelist, "amount" => $processes]);
1602 * Checks if $array is a filled array with at least one entry.
1604 * @param mixed $array A filled array with at least one entry
1606 * @return boolean Whether $array is a filled array or an object with rows
1608 public static function isResult($array)
1610 // It could be a return value from an update statement
1611 if (is_bool($array)) {
1615 if (is_object($array)) {
1616 return self::numRows($array) > 0;
1619 return (is_array($array) && (count($array) > 0));
1623 * @brief Callback function for "esc_array"
1625 * @param mixed $value Array value
1626 * @param string $key Array key
1627 * @param boolean $add_quotation add quotation marks for string values
1630 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1632 if (!$add_quotation) {
1633 if (is_bool($value)) {
1634 $value = ($value ? '1' : '0');
1636 $value = self::escape($value);
1641 if (is_bool($value)) {
1642 $value = ($value ? 'true' : 'false');
1643 } elseif (is_float($value) || is_integer($value)) {
1644 $value = (string) $value;
1646 $value = "'" . self::escape($value) . "'";
1651 * @brief Escapes a whole array
1653 * @param mixed $arr Array with values to be escaped
1654 * @param boolean $add_quotation add quotation marks for string values
1657 public static function escapeArray(&$arr, $add_quotation = false)
1659 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);