3 namespace Friendica\Database;
5 use Friendica\Core\Config\Cache\IConfigCache;
6 use Friendica\Core\System;
7 use Friendica\Util\DateTimeFormat;
8 use Friendica\Util\Profiler;
15 use Psr\Log\LoggerInterface;
18 * @class MySQL database class
20 * This class is for the low level database stuff that does driver specific things.
25 * Lowest possible date value
27 const NULL_DATE = '0001-01-01';
29 * Lowest possible datetime value
31 const NULL_DATETIME = '0001-01-01 00:00:00';
33 public static $connected = false;
38 private static $configCache;
42 private static $profiler;
44 * @var LoggerInterface
46 private static $logger;
47 private static $server_info = '';
48 private static $connection;
49 private static $driver;
50 private static $error = false;
51 private static $errorno = 0;
52 private static $affected_rows = 0;
53 private static $in_transaction = false;
54 private static $in_retrial = false;
55 private static $relation = [];
56 private static $db_serveraddr = '';
57 private static $db_user = '';
58 private static $db_pass = '';
59 private static $db_name = '';
60 private static $db_charset = '';
62 public static function connect(IConfigCache $configCache, Profiler $profiler, LoggerInterface $logger, $serveraddr, $user, $pass, $db, $charset = null)
64 if (!is_null(self::$connection) && self::connected()) {
68 // We are storing these values for being able to perform a reconnect
69 self::$configCache = $configCache;
70 self::$profiler = $profiler;
71 self::$logger = $logger;
72 self::$db_serveraddr = $serveraddr;
73 self::$db_user = $user;
74 self::$db_pass = $pass;
76 self::$db_charset = $charset;
79 $serveraddr = trim($serveraddr);
81 $serverdata = explode(':', $serveraddr);
82 $server = $serverdata[0];
84 if (count($serverdata) > 1) {
85 $port = trim($serverdata[1]);
88 $server = trim($server);
92 $charset = trim($charset);
94 if (!(strlen($server) && strlen($user))) {
98 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
99 self::$driver = 'pdo';
100 $connect = "mysql:host=".$server.";dbname=".$db;
103 $connect .= ";port=".$port;
107 $connect .= ";charset=".$charset;
111 self::$connection = @new PDO($connect, $user, $pass);
112 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
113 self::$connected = true;
114 } catch (PDOException $e) {
115 /// @TODO At least log exception, don't ignore it!
119 if (!self::$connected && class_exists('\mysqli')) {
120 self::$driver = 'mysqli';
123 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
125 self::$connection = @new mysqli($server, $user, $pass, $db);
128 if (!mysqli_connect_errno()) {
129 self::$connected = true;
132 self::$connection->set_charset($charset);
137 // No suitable SQL driver was found.
138 if (!self::$connected) {
139 self::$driver = null;
140 self::$connection = null;
143 return self::$connected;
147 * Sets the logger for DBA
149 * @note this is necessary because if we want to load the logger configuration
150 * from the DB, but there's an error, we would print out an exception.
151 * So the logger gets updated after the logger configuration can be retrieved
154 * @param LoggerInterface $logger
156 public static function setLogger(LoggerInterface $logger)
158 self::$logger = $logger;
162 * Disconnects the current database connection
164 public static function disconnect()
166 if (is_null(self::$connection)) {
170 switch (self::$driver) {
172 self::$connection = null;
175 self::$connection->close();
176 self::$connection = null;
182 * Perform a reconnect of an existing database connection
184 public static function reconnect() {
187 $ret = self::connect(self::$configCache, self::$profiler, self::$logger, self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
192 * Return the database object.
195 public static function getConnection()
197 return self::$connection;
201 * @brief Returns the MySQL server version string
203 * This function discriminate between the deprecated mysql API and the current
204 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
208 public static function serverInfo() {
209 if (self::$server_info == '') {
210 switch (self::$driver) {
212 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
215 self::$server_info = self::$connection->server_info;
219 return self::$server_info;
223 * @brief Returns the selected database name
228 public static function databaseName() {
229 $ret = self::p("SELECT DATABASE() AS `db`");
230 $data = self::toArray($ret);
231 return $data[0]['db'];
235 * @brief Analyze a database query and log this if some conditions are met.
237 * @param string $query The database query that will be analyzed
240 private static function logIndex($query) {
242 if (!self::$configCache->get('system', 'db_log_index')) {
246 // Don't explain an explain statement
247 if (strtolower(substr($query, 0, 7)) == "explain") {
251 // Only do the explain on "select", "update" and "delete"
252 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
256 $r = self::p("EXPLAIN ".$query);
257 if (!self::isResult($r)) {
261 $watchlist = explode(',', self::$configCache->get('system', 'db_log_index_watch'));
262 $blacklist = explode(',', self::$configCache->get('system', 'db_log_index_blacklist'));
264 while ($row = self::fetch($r)) {
265 if ((intval(self::$configCache->get('system', 'db_loglimit_index')) > 0)) {
266 $log = (in_array($row['key'], $watchlist) &&
267 ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index'))));
272 if ((intval(self::$configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval(self::$configCache->get('system', 'db_loglimit_index_high')))) {
276 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
281 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
282 @file_put_contents(self::$configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
283 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
284 basename($backtrace[1]["file"])."\t".
285 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
286 substr($query, 0, 2000)."\n", FILE_APPEND);
292 * Removes every not whitelisted character from the identifier string
294 * @param string $identifier
296 * @return string sanitized identifier
299 private static function sanitizeIdentifier($identifier)
301 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
304 public static function escape($str) {
305 if (self::$connected) {
306 switch (self::$driver) {
308 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
311 return @self::$connection->real_escape_string($str);
314 return str_replace("'", "\\'", $str);
318 public static function connected() {
321 if (is_null(self::$connection)) {
325 switch (self::$driver) {
327 $r = self::p("SELECT 1");
328 if (self::isResult($r)) {
329 $row = self::toArray($r);
330 $connected = ($row[0]['1'] == '1');
334 $connected = self::$connection->ping();
341 * @brief Replaces ANY_VALUE() function by MIN() function,
342 * if the database server does not support ANY_VALUE().
344 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
345 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
346 * A standard fall-back is to use MIN().
348 * @param string $sql An SQL string without the values
349 * @return string The input SQL string modified if necessary.
351 public static function anyValueFallback($sql) {
352 $server_info = self::serverInfo();
353 if (version_compare($server_info, '5.7.5', '<') ||
354 (stripos($server_info, 'MariaDB') !== false)) {
355 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
361 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
363 * This is safe when we bind the parameters later.
364 * The parameter values aren't part of the SQL.
366 * @param string $sql An SQL string without the values
367 * @return string The input SQL string modified if necessary.
369 public static function cleanQuery($sql) {
370 $search = ["\t", "\n", "\r", " "];
371 $replace = [' ', ' ', ' ', ' '];
374 $sql = str_replace($search, $replace, $sql);
375 } while ($oldsql != $sql);
382 * @brief Replaces the ? placeholders with the parameters in the $args array
384 * @param string $sql SQL query
385 * @param array $args The parameters that are to replace the ? placeholders
386 * @return string The replaced SQL query
388 private static function replaceParameters($sql, $args) {
390 foreach ($args AS $param => $value) {
391 if (is_int($args[$param]) || is_float($args[$param])) {
392 $replace = intval($args[$param]);
394 $replace = "'".self::escape($args[$param])."'";
397 $pos = strpos($sql, '?', $offset);
398 if ($pos !== false) {
399 $sql = substr_replace($sql, $replace, $pos, 1);
401 $offset = $pos + strlen($replace);
407 * @brief Convert parameter array to an universal form
408 * @param array $args Parameter array
409 * @return array universalized parameter array
411 private static function getParam($args) {
414 // When the second function parameter is an array then use this as the parameter array
415 if ((count($args) > 0) && (is_array($args[1]))) {
423 * @brief Executes a prepared statement that returns data
424 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
426 * Please only use it with complicated queries.
427 * For all regular queries please use DBA::select or DBA::exists
429 * @param string $sql SQL statement
430 * @return bool|object statement object or result object
433 public static function p($sql) {
435 $stamp1 = microtime(true);
437 $params = self::getParam(func_get_args());
439 // Renumber the array keys to be sure that they fit
442 foreach ($params AS $param) {
443 // Avoid problems with some MySQL servers and boolean values. See issue #3645
444 if (is_bool($param)) {
445 $param = (int)$param;
447 $args[++$i] = $param;
450 if (!self::$connected) {
454 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
455 // Question: Should we continue or stop the query here?
456 self::$logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
459 $sql = self::cleanQuery($sql);
460 $sql = self::anyValueFallback($sql);
464 if (self::$configCache->get('system', 'db_callstack') !== null) {
465 $sql = "/*".System::callstack()." */ ".$sql;
470 self::$affected_rows = 0;
472 // We have to make some things different if this function is called from "e"
473 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
475 if (isset($trace[1])) {
476 $called_from = $trace[1];
478 // We use just something that is defined to avoid warnings
479 $called_from = $trace[0];
481 // We are having an own error logging in the function "e"
482 $called_from_e = ($called_from['function'] == 'e');
484 switch (self::$driver) {
486 // If there are no arguments we use "query"
487 if (count($args) == 0) {
488 if (!$retval = self::$connection->query($sql)) {
489 $errorInfo = self::$connection->errorInfo();
490 self::$error = $errorInfo[2];
491 self::$errorno = $errorInfo[1];
495 self::$affected_rows = $retval->rowCount();
499 if (!$stmt = self::$connection->prepare($sql)) {
500 $errorInfo = self::$connection->errorInfo();
501 self::$error = $errorInfo[2];
502 self::$errorno = $errorInfo[1];
507 foreach ($args AS $param => $value) {
508 if (is_int($args[$param])) {
509 $data_type = PDO::PARAM_INT;
511 $data_type = PDO::PARAM_STR;
513 $stmt->bindParam($param, $args[$param], $data_type);
516 if (!$stmt->execute()) {
517 $errorInfo = $stmt->errorInfo();
518 self::$error = $errorInfo[2];
519 self::$errorno = $errorInfo[1];
523 self::$affected_rows = $retval->rowCount();
527 // There are SQL statements that cannot be executed with a prepared statement
528 $parts = explode(' ', $orig_sql);
529 $command = strtolower($parts[0]);
530 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
532 // The fallback routine is called as well when there are no arguments
533 if (!$can_be_prepared || (count($args) == 0)) {
534 $retval = self::$connection->query(self::replaceParameters($sql, $args));
535 if (self::$connection->errno) {
536 self::$error = self::$connection->error;
537 self::$errorno = self::$connection->errno;
540 if (isset($retval->num_rows)) {
541 self::$affected_rows = $retval->num_rows;
543 self::$affected_rows = self::$connection->affected_rows;
549 $stmt = self::$connection->stmt_init();
551 if (!$stmt->prepare($sql)) {
552 self::$error = $stmt->error;
553 self::$errorno = $stmt->errno;
560 foreach ($args AS $param => $value) {
561 if (is_int($args[$param])) {
563 } elseif (is_float($args[$param])) {
565 } elseif (is_string($args[$param])) {
570 $values[] = &$args[$param];
573 if (count($values) > 0) {
574 array_unshift($values, $param_types);
575 call_user_func_array([$stmt, 'bind_param'], $values);
578 if (!$stmt->execute()) {
579 self::$error = self::$connection->error;
580 self::$errorno = self::$connection->errno;
583 $stmt->store_result();
585 self::$affected_rows = $retval->affected_rows;
590 // We are having an own error logging in the function "e"
591 if ((self::$errorno != 0) && !$called_from_e) {
592 // We have to preserve the error code, somewhere in the logging it get lost
593 $error = self::$error;
594 $errorno = self::$errorno;
596 self::$logger->error('DB Error', [
597 'code' => self::$errorno,
598 'error' => self::$error,
599 'callstack' => System::callstack(8),
600 'params' => self::replaceParameters($sql, $args),
603 // On a lost connection we try to reconnect - but only once.
604 if ($errorno == 2006) {
605 if (self::$in_retrial || !self::reconnect()) {
606 // It doesn't make sense to continue when the database connection was lost
607 if (self::$in_retrial) {
608 self::$logger->notice('Giving up retrial because of database error', [
609 'code' => self::$errorno,
610 'error' => self::$error,
613 self::$logger->notice('Couldn\'t reconnect after database error', [
614 'code' => self::$errorno,
615 'error' => self::$error,
621 self::$logger->notice('Reconnected after database error', [
622 'code' => self::$errorno,
623 'error' => self::$error,
625 self::$in_retrial = true;
626 $ret = self::p($sql, $args);
627 self::$in_retrial = false;
632 self::$error = $error;
633 self::$errorno = $errorno;
636 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
638 if (self::$configCache->get('system', 'db_log')) {
639 $stamp2 = microtime(true);
640 $duration = (float)($stamp2 - $stamp1);
642 if (($duration > self::$configCache->get('system', 'db_loglimit'))) {
643 $duration = round($duration, 3);
644 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
646 @file_put_contents(self::$configCache->get('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
647 basename($backtrace[1]["file"])."\t".
648 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
649 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
656 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
658 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
660 * @param string $sql SQL statement
661 * @return boolean Was the query successfull? False is returned only if an error occurred
664 public static function e($sql) {
666 $stamp = microtime(true);
668 $params = self::getParam(func_get_args());
670 // In a case of a deadlock we are repeating the query 20 times
674 $stmt = self::p($sql, $params);
676 if (is_bool($stmt)) {
678 } elseif (is_object($stmt)) {
686 } while ((self::$errorno == 1213) && (--$timeout > 0));
688 if (self::$errorno != 0) {
689 // We have to preserve the error code, somewhere in the logging it get lost
690 $error = self::$error;
691 $errorno = self::$errorno;
693 self::$logger->error('DB Error', [
694 'code' => self::$errorno,
695 'error' => self::$error,
696 'callstack' => System::callstack(8),
697 'params' => self::replaceParameters($sql, $params),
700 // On a lost connection we simply quit.
701 // A reconnect like in self::p could be dangerous with modifications
702 if ($errorno == 2006) {
703 self::$logger->notice('Giving up because of database error', [
704 'code' => self::$errorno,
705 'error' => self::$error,
710 self::$error = $error;
711 self::$errorno = $errorno;
714 self::$profiler->saveTimestamp($stamp, "database_write", System::callstack());
720 * @brief Check if data exists
722 * @param string $table Table name
723 * @param array $condition array of fields for condition
725 * @return boolean Are there rows for that condition?
728 public static function exists($table, $condition) {
735 if (empty($condition)) {
736 return DBStructure::existsTable($table);
740 $first_key = key($condition);
741 if (!is_int($first_key)) {
742 $fields = [$first_key];
745 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
747 if (is_bool($stmt)) {
750 $retval = (self::numRows($stmt) > 0);
759 * Fetches the first row
761 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
763 * @brief Fetches the first row
764 * @param string $sql SQL statement
765 * @return array first row of query
768 public static function fetchFirst($sql) {
769 $params = self::getParam(func_get_args());
771 $stmt = self::p($sql, $params);
773 if (is_bool($stmt)) {
776 $retval = self::fetch($stmt);
785 * @brief Returns the number of affected rows of the last statement
787 * @return int Number of rows
789 public static function affectedRows() {
790 return self::$affected_rows;
794 * @brief Returns the number of columns of a statement
796 * @param object Statement object
797 * @return int Number of columns
799 public static function columnCount($stmt) {
800 if (!is_object($stmt)) {
803 switch (self::$driver) {
805 return $stmt->columnCount();
807 return $stmt->field_count;
812 * @brief Returns the number of rows of a statement
814 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
815 * @return int Number of rows
817 public static function numRows($stmt) {
818 if (!is_object($stmt)) {
821 switch (self::$driver) {
823 return $stmt->rowCount();
825 return $stmt->num_rows;
831 * @brief Fetch a single row
833 * @param mixed $stmt statement object
834 * @return array current row
836 public static function fetch($stmt) {
838 $stamp1 = microtime(true);
842 if (!is_object($stmt)) {
846 switch (self::$driver) {
848 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
851 if (get_class($stmt) == 'mysqli_result') {
852 $columns = $stmt->fetch_assoc();
856 // This code works, but is slow
858 // Bind the result to a result array
862 for ($x = 0; $x < $stmt->field_count; $x++) {
863 $cols[] = &$cols_num[$x];
866 call_user_func_array([$stmt, 'bind_result'], $cols);
868 if (!$stmt->fetch()) {
873 // We need to get the field names for the array keys
874 // It seems that there is no better way to do this.
875 $result = $stmt->result_metadata();
876 $fields = $result->fetch_fields();
878 foreach ($cols_num AS $param => $col) {
879 $columns[$fields[$param]->name] = $col;
883 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
889 * @brief Insert a row into a table
891 * @param string/array $table Table name
893 * @return string formatted and sanitzed table name
896 public static function formatTableName($table)
898 if (is_string($table)) {
899 return "`" . self::sanitizeIdentifier($table) . "`";
902 if (!is_array($table)) {
906 $scheme = key($table);
908 return "`" . self::sanitizeIdentifier($scheme) . "`.`" . self::sanitizeIdentifier($table[$scheme]) . "`";
912 * @brief Insert a row into a table
914 * @param string $table Table name
915 * @param array $param parameter array
916 * @param bool $on_duplicate_update Do an update on a duplicate entry
918 * @return boolean was the insert successful?
921 public static function insert($table, $param, $on_duplicate_update = false) {
923 if (empty($table) || empty($param)) {
924 self::$logger->info('Table and fields have to be set');
928 $sql = "INSERT INTO " . self::formatTableName($table) . " (`".implode("`, `", array_keys($param))."`) VALUES (".
929 substr(str_repeat("?, ", count($param)), 0, -2).")";
931 if ($on_duplicate_update) {
932 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
934 $values = array_values($param);
935 $param = array_merge_recursive($values, $values);
938 return self::e($sql, $param);
942 * @brief Fetch the id of the last insert command
944 * @return integer Last inserted id
946 public static function lastInsertId() {
947 switch (self::$driver) {
949 $id = self::$connection->lastInsertId();
952 $id = self::$connection->insert_id;
959 * @brief Locks a table for exclusive write access
961 * This function can be extended in the future to accept a table array as well.
963 * @param string $table Table name
965 * @return boolean was the lock successful?
968 public static function lock($table) {
969 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
970 if (self::$driver == 'pdo') {
971 self::e("SET autocommit=0");
972 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
974 self::$connection->autocommit(false);
977 $success = self::e("LOCK TABLES " . self::formatTableName($table) ." WRITE");
979 if (self::$driver == 'pdo') {
980 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
984 if (self::$driver == 'pdo') {
985 self::e("SET autocommit=1");
987 self::$connection->autocommit(true);
990 self::$in_transaction = true;
996 * @brief Unlocks all locked tables
998 * @return boolean was the unlock successful?
1001 public static function unlock() {
1002 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1003 self::performCommit();
1005 if (self::$driver == 'pdo') {
1006 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1009 $success = self::e("UNLOCK TABLES");
1011 if (self::$driver == 'pdo') {
1012 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
1013 self::e("SET autocommit=1");
1015 self::$connection->autocommit(true);
1018 self::$in_transaction = false;
1023 * @brief Starts a transaction
1025 * @return boolean Was the command executed successfully?
1027 public static function transaction() {
1028 if (!self::performCommit()) {
1032 switch (self::$driver) {
1034 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
1040 if (!self::$connection->begin_transaction()) {
1046 self::$in_transaction = true;
1050 private static function performCommit()
1052 switch (self::$driver) {
1054 if (!self::$connection->inTransaction()) {
1058 return self::$connection->commit();
1061 return self::$connection->commit();
1068 * @brief Does a commit
1070 * @return boolean Was the command executed successfully?
1072 public static function commit() {
1073 if (!self::performCommit()) {
1076 self::$in_transaction = false;
1081 * @brief Does a rollback
1083 * @return boolean Was the command executed successfully?
1085 public static function rollback() {
1088 switch (self::$driver) {
1090 if (!self::$connection->inTransaction()) {
1094 $ret = self::$connection->rollBack();
1098 $ret = self::$connection->rollback();
1101 self::$in_transaction = false;
1106 * @brief Build the array with the table relations
1108 * The array is build from the database definitions in DBStructure.php
1110 * This process must only be started once, since the value is cached.
1112 private static function buildRelationData() {
1113 $definition = DBStructure::definition(self::$configCache->get('system', 'basepath'));
1115 foreach ($definition AS $table => $structure) {
1116 foreach ($structure['fields'] AS $field => $field_struct) {
1117 if (isset($field_struct['relation'])) {
1118 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1119 self::$relation[$rel_table][$rel_field][$table][] = $field;
1127 * @brief Delete a row from a table
1129 * @param string $table Table name
1130 * @param array $conditions Field condition(s)
1131 * @param array $options
1132 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1133 * relations (default: true)
1134 * @param array $callstack Internal use: prevent endless loops
1136 * @return boolean was the delete successful?
1137 * @throws \Exception
1139 public static function delete($table, array $conditions, array $options = [], array &$callstack = [])
1141 if (empty($table) || empty($conditions)) {
1142 self::$logger->info('Table and conditions have to be set');
1148 // Create a key for the loop prevention
1149 $key = $table . ':' . json_encode($conditions);
1151 // We quit when this key already exists in the callstack.
1152 if (isset($callstack[$key])) {
1156 $callstack[$key] = true;
1158 $table = self::sanitizeIdentifier($table);
1160 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1162 // Don't use "defaults" here, since it would set "false" to "true"
1163 if (isset($options['cascade'])) {
1164 $cascade = $options['cascade'];
1169 // To speed up the whole process we cache the table relations
1170 if ($cascade && count(self::$relation) == 0) {
1171 self::buildRelationData();
1174 // Is there a relation entry for the table?
1175 if ($cascade && isset(self::$relation[$table])) {
1176 // We only allow a simple "one field" relation.
1177 $field = array_keys(self::$relation[$table])[0];
1178 $rel_def = array_values(self::$relation[$table])[0];
1180 // Create a key for preventing double queries
1181 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1183 // When the search field is the relation field, we don't need to fetch the rows
1184 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1185 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1186 foreach ($rel_def AS $rel_table => $rel_fields) {
1187 foreach ($rel_fields AS $rel_field) {
1188 self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1191 // We quit when this key already exists in the callstack.
1192 } elseif (!isset($callstack[$qkey])) {
1193 $callstack[$qkey] = true;
1195 // Fetch all rows that are to be deleted
1196 $data = self::select($table, [$field], $conditions);
1198 while ($row = self::fetch($data)) {
1199 self::delete($table, [$field => $row[$field]], $options, $callstack);
1204 // Since we had split the delete command we don't need the original command anymore
1205 unset($commands[$key]);
1209 // Now we finalize the process
1210 $do_transaction = !self::$in_transaction;
1212 if ($do_transaction) {
1213 self::transaction();
1219 foreach ($commands AS $command) {
1220 $conditions = $command['conditions'];
1222 $first_key = key($conditions);
1224 $condition_string = self::buildCondition($conditions);
1226 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1227 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1228 self::$logger->debug(self::replaceParameters($sql, $conditions));
1230 if (!self::e($sql, $conditions)) {
1231 if ($do_transaction) {
1237 $key_table = $command['table'];
1238 $key_condition = array_keys($command['conditions'])[0];
1239 $value = array_values($command['conditions'])[0];
1241 // Split the SQL queries in chunks of 100 values
1242 // We do the $i stuff here to make the code better readable
1243 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1244 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1248 $compacted[$key_table][$key_condition][$i][$value] = $value;
1249 $counter[$key_table][$key_condition] = $i;
1252 foreach ($compacted AS $table => $values) {
1253 foreach ($values AS $field => $field_value_list) {
1254 foreach ($field_value_list AS $field_values) {
1255 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1256 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1258 self::$logger->debug(self::replaceParameters($sql, $field_values));
1260 if (!self::e($sql, $field_values)) {
1261 if ($do_transaction) {
1269 if ($do_transaction) {
1276 * @brief Updates rows
1278 * Updates rows in the database. When $old_fields is set to an array,
1279 * the system will only do an update if the fields in that array changed.
1282 * Only the values in $old_fields are compared.
1283 * This is an intentional behaviour.
1286 * We include the timestamp field in $fields but not in $old_fields.
1287 * Then the row will only get the new timestamp when the other fields had changed.
1289 * When $old_fields is set to a boolean value the system will do this compare itself.
1290 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1293 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1294 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1296 * @param string $table Table name
1297 * @param array $fields contains the fields that are updated
1298 * @param array $condition condition array with the key values
1299 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1301 * @return boolean was the update successfull?
1302 * @throws \Exception
1304 public static function update($table, $fields, $condition, $old_fields = []) {
1306 if (empty($table) || empty($fields) || empty($condition)) {
1307 self::$logger->info('Table, fields and condition have to be set');
1311 $condition_string = self::buildCondition($condition);
1313 if (is_bool($old_fields)) {
1314 $do_insert = $old_fields;
1316 $old_fields = self::selectFirst($table, [], $condition);
1318 if (is_bool($old_fields)) {
1320 $values = array_merge($condition, $fields);
1321 return self::insert($table, $values, $do_insert);
1327 $do_update = (count($old_fields) == 0);
1329 foreach ($old_fields AS $fieldname => $content) {
1330 if (isset($fields[$fieldname])) {
1331 if (($fields[$fieldname] == $content) && !is_null($content)) {
1332 unset($fields[$fieldname]);
1339 if (!$do_update || (count($fields) == 0)) {
1343 $sql = "UPDATE ". self::formatTableName($table) . " SET `".
1344 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1346 $params1 = array_values($fields);
1347 $params2 = array_values($condition);
1348 $params = array_merge_recursive($params1, $params2);
1350 return self::e($sql, $params);
1354 * Retrieve a single record from a table and returns it in an associative array
1356 * @brief Retrieve a single record from a table
1357 * @param string $table
1358 * @param array $fields
1359 * @param array $condition
1360 * @param array $params
1361 * @return bool|array
1362 * @throws \Exception
1365 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1367 $params['limit'] = 1;
1368 $result = self::select($table, $fields, $condition, $params);
1370 if (is_bool($result)) {
1373 $row = self::fetch($result);
1374 self::close($result);
1380 * @brief Select rows from a table
1382 * @param string $table Table name
1383 * @param array $fields Array of selected fields, empty for all
1384 * @param array $condition Array of fields for condition
1385 * @param array $params Array of several parameters
1387 * @return boolean|object
1391 * $fields = array("id", "uri", "uid", "network");
1393 * $condition = array("uid" => 1, "network" => 'dspr');
1395 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1397 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1399 * $data = DBA::select($table, $fields, $condition, $params);
1400 * @throws \Exception
1402 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1404 if (empty($table)) {
1408 if (count($fields) > 0) {
1409 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1411 $select_fields = "*";
1414 $condition_string = self::buildCondition($condition);
1416 $param_string = self::buildParameter($params);
1418 $sql = "SELECT " . $select_fields . " FROM " . self::formatTableName($table) . $condition_string . $param_string;
1420 $result = self::p($sql, $condition);
1426 * @brief Counts the rows from a table satisfying the provided condition
1428 * @param string $table Table name
1429 * @param array $condition array of fields for condition
1436 * $condition = ["uid" => 1, "network" => 'dspr'];
1438 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1440 * $count = DBA::count($table, $condition);
1441 * @throws \Exception
1443 public static function count($table, array $condition = [])
1445 if (empty($table)) {
1449 $condition_string = self::buildCondition($condition);
1451 $sql = "SELECT COUNT(*) AS `count` FROM " . self::formatTableName($table) . $condition_string;
1453 $row = self::fetchFirst($sql, $condition);
1455 return $row['count'];
1459 * @brief Returns the SQL condition string built from the provided condition array
1461 * This function operates with two modes.
1462 * - Supplied with a filed/value associative array, it builds simple strict
1463 * equality conditions linked by AND.
1464 * - Supplied with a flat list, the first element is the condition string and
1465 * the following arguments are the values to be interpolated
1467 * $condition = ["uid" => 1, "network" => 'dspr'];
1469 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1471 * In either case, the provided array is left with the parameters only
1473 * @param array $condition
1476 public static function buildCondition(array &$condition = [])
1478 $condition_string = '';
1479 if (count($condition) > 0) {
1481 $first_key = key($condition);
1482 if (is_int($first_key)) {
1483 $condition_string = " WHERE (" . array_shift($condition) . ")";
1486 $condition_string = "";
1487 foreach ($condition as $field => $value) {
1488 if ($condition_string != "") {
1489 $condition_string .= " AND ";
1491 if (is_array($value)) {
1492 /* Workaround for MySQL Bug #64791.
1493 * Never mix data types inside any IN() condition.
1494 * In case of mixed types, cast all as string.
1495 * Logic needs to be consistent with DBA::p() data types.
1499 foreach ($value as $single_value) {
1500 if (is_int($single_value)) {
1507 if ($is_int && $is_alpha) {
1508 foreach ($value as &$ref) {
1510 $ref = (string)$ref;
1513 unset($ref); //Prevent accidental re-use.
1516 $new_values = array_merge($new_values, array_values($value));
1517 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1518 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1519 } elseif (is_null($value)) {
1520 $condition_string .= "`" . $field . "` IS NULL";
1522 $new_values[$field] = $value;
1523 $condition_string .= "`" . $field . "` = ?";
1526 $condition_string = " WHERE (" . $condition_string . ")";
1527 $condition = $new_values;
1531 return $condition_string;
1535 * @brief Returns the SQL parameter string built from the provided parameter array
1537 * @param array $params
1540 public static function buildParameter(array $params = [])
1542 $groupby_string = '';
1543 if (isset($params['group_by'])) {
1544 $groupby_string = " GROUP BY ";
1545 foreach ($params['group_by'] as $fields) {
1546 $groupby_string .= "`" . $fields . "`, ";
1548 $groupby_string = substr($groupby_string, 0, -2);
1552 if (isset($params['order'])) {
1553 $order_string = " ORDER BY ";
1554 foreach ($params['order'] AS $fields => $order) {
1555 if ($order === 'RAND()') {
1556 $order_string .= "RAND(), ";
1557 } elseif (!is_int($fields)) {
1558 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1560 $order_string .= "`" . $order . "`, ";
1563 $order_string = substr($order_string, 0, -2);
1567 if (isset($params['limit']) && is_numeric($params['limit'])) {
1568 $limit_string = " LIMIT " . intval($params['limit']);
1571 if (isset($params['limit']) && is_array($params['limit'])) {
1572 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1575 return $groupby_string . $order_string . $limit_string;
1579 * @brief Fills an array with data from a query
1581 * @param object $stmt statement object
1582 * @param bool $do_close
1583 * @return array Data array
1585 public static function toArray($stmt, $do_close = true) {
1586 if (is_bool($stmt)) {
1591 while ($row = self::fetch($stmt)) {
1601 * @brief Returns the error number of the last query
1603 * @return string Error number (0 if no error)
1605 public static function errorNo() {
1606 return self::$errorno;
1610 * @brief Returns the error message of the last query
1612 * @return string Error message ('' if no error)
1614 public static function errorMessage() {
1615 return self::$error;
1619 * @brief Closes the current statement
1621 * @param object $stmt statement object
1622 * @return boolean was the close successful?
1624 public static function close($stmt) {
1626 $stamp1 = microtime(true);
1628 if (!is_object($stmt)) {
1632 switch (self::$driver) {
1634 $ret = $stmt->closeCursor();
1637 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1638 // We should be careful not to assume the object type of $stmt
1639 // because DBA::p() has been able to return both types.
1640 if ($stmt instanceof mysqli_stmt) {
1641 $stmt->free_result();
1642 $ret = $stmt->close();
1643 } elseif ($stmt instanceof mysqli_result) {
1652 self::$profiler->saveTimestamp($stamp1, 'database', System::callstack());
1658 * @brief Return a list of database processes
1661 * 'list' => List of processes, separated in their different states
1662 * 'amount' => Number of concurrent database processes
1663 * @throws \Exception
1665 public static function processlist()
1667 $ret = self::p("SHOW PROCESSLIST");
1668 $data = self::toArray($ret);
1672 foreach ($data as $process) {
1673 $state = trim($process["State"]);
1675 // Filter out all non blocking processes
1676 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1683 foreach ($states as $state => $usage) {
1684 if ($statelist != "") {
1687 $statelist .= $state.": ".$usage;
1689 return(["list" => $statelist, "amount" => $processes]);
1693 * Checks if $array is a filled array with at least one entry.
1695 * @param mixed $array A filled array with at least one entry
1697 * @return boolean Whether $array is a filled array or an object with rows
1699 public static function isResult($array)
1701 // It could be a return value from an update statement
1702 if (is_bool($array)) {
1706 if (is_object($array)) {
1707 return self::numRows($array) > 0;
1710 return (is_array($array) && (count($array) > 0));
1714 * @brief Callback function for "esc_array"
1716 * @param mixed $value Array value
1717 * @param string $key Array key
1718 * @param boolean $add_quotation add quotation marks for string values
1721 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1723 if (!$add_quotation) {
1724 if (is_bool($value)) {
1725 $value = ($value ? '1' : '0');
1727 $value = self::escape($value);
1732 if (is_bool($value)) {
1733 $value = ($value ? 'true' : 'false');
1734 } elseif (is_float($value) || is_integer($value)) {
1735 $value = (string) $value;
1737 $value = "'" . self::escape($value) . "'";
1742 * @brief Escapes a whole array
1744 * @param mixed $arr Array with values to be escaped
1745 * @param boolean $add_quotation add quotation marks for string values
1748 public static function escapeArray(&$arr, $add_quotation = false)
1750 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);