3 namespace Friendica\Database;
5 use Friendica\Core\Config\Cache\ConfigCache;
6 use Friendica\Core\System;
7 use Friendica\Util\DateTimeFormat;
8 use Friendica\Util\Profiler;
12 use ParagonIE\HiddenString\HiddenString;
16 use Psr\Log\LoggerInterface;
19 * @class MySQL database class
21 * This class is for the low level database stuff that does driver specific things.
25 private $connected = false;
36 * @var LoggerInterface
39 private $server_info = '';
40 /** @var PDO|mysqli */
43 private $error = false;
45 private $affected_rows = 0;
46 private $in_transaction = false;
47 private $in_retrial = false;
48 private $relation = [];
49 private $db_serveraddr;
58 public function __construct(ConfigCache $configCache, Profiler $profiler, LoggerInterface $logger, $serveraddr, $user, HiddenString $pass, $db, $charset = null)
60 // We are storing these values for being able to perform a reconnect
61 $this->configCache = $configCache;
62 $this->profiler = $profiler;
63 $this->logger = $logger;
64 $this->db_serveraddr = $serveraddr;
65 $this->db_user = $user;
66 $this->db_pass = $pass;
68 $this->db_charset = $charset;
75 public function connect()
77 if (!is_null($this->connection) && $this->connected()) {
82 $serveraddr = trim($this->db_serveraddr);
84 $serverdata = explode(':', $serveraddr);
85 $server = $serverdata[0];
87 if (count($serverdata) > 1) {
88 $port = trim($serverdata[1]);
91 $server = trim($server);
92 $user = trim($this->db_user);
93 $pass = trim($this->db_pass);
94 $db = trim($this->db_name);
95 $charset = trim($this->db_charset);
97 if (!(strlen($server) && strlen($user))) {
101 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
102 $this->driver = 'pdo';
103 $connect = "mysql:host=" . $server . ";dbname=" . $db;
106 $connect .= ";port=" . $port;
110 $connect .= ";charset=" . $charset;
114 $this->connection = @new PDO($connect, $user, $pass);
115 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
116 $this->connected = true;
117 } catch (PDOException $e) {
118 /// @TODO At least log exception, don't ignore it!
122 if (!$this->connected && class_exists('\mysqli')) {
123 $this->driver = 'mysqli';
126 $this->connection = @new mysqli($server, $user, $pass, $db, $port);
128 $this->connection = @new mysqli($server, $user, $pass, $db);
131 if (!mysqli_connect_errno()) {
132 $this->connected = true;
135 $this->connection->set_charset($charset);
140 // No suitable SQL driver was found.
141 if (!$this->connected) {
142 $this->driver = null;
143 $this->connection = null;
146 return $this->connected;
150 * Sets the logger for DBA
152 * @note this is necessary because if we want to load the logger configuration
153 * from the DB, but there's an error, we would print out an exception.
154 * So the logger gets updated after the logger configuration can be retrieved
157 * @param LoggerInterface $logger
159 public function setLogger(LoggerInterface $logger)
161 $this->logger = $logger;
165 * Disconnects the current database connection
167 public function disconnect()
169 if (is_null($this->connection)) {
173 switch ($this->driver) {
175 $this->connection = null;
178 $this->connection->close();
179 $this->connection = null;
185 * Perform a reconnect of an existing database connection
187 public function reconnect()
190 return $this->connect();
194 * Return the database object.
198 public function getConnection()
200 return $this->connection;
204 * @brief Returns the MySQL server version string
206 * This function discriminate between the deprecated mysql API and the current
207 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
211 public function serverInfo()
213 if ($this->server_info == '') {
214 switch ($this->driver) {
216 $this->server_info = $this->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
219 $this->server_info = $this->connection->server_info;
223 return $this->server_info;
227 * @brief Returns the selected database name
232 public function databaseName()
234 $ret = $this->p("SELECT DATABASE() AS `db`");
235 $data = $this->toArray($ret);
236 return $data[0]['db'];
240 * @brief Analyze a database query and log this if some conditions are met.
242 * @param string $query The database query that will be analyzed
246 private function logIndex($query)
249 if (!$this->configCache->get('system', 'db_log_index')) {
253 // Don't explain an explain statement
254 if (strtolower(substr($query, 0, 7)) == "explain") {
258 // Only do the explain on "select", "update" and "delete"
259 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
263 $r = $this->p("EXPLAIN " . $query);
264 if (!$this->isResult($r)) {
268 $watchlist = explode(',', $this->configCache->get('system', 'db_log_index_watch'));
269 $blacklist = explode(',', $this->configCache->get('system', 'db_log_index_blacklist'));
271 while ($row = $this->fetch($r)) {
272 if ((intval($this->configCache->get('system', 'db_loglimit_index')) > 0)) {
273 $log = (in_array($row['key'], $watchlist) &&
274 ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index'))));
279 if ((intval($this->configCache->get('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($this->configCache->get('system', 'db_loglimit_index_high')))) {
283 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
288 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
289 @file_put_contents($this->configCache->get('system', 'db_log_index'), DateTimeFormat::utcNow() . "\t" .
290 $row['key'] . "\t" . $row['rows'] . "\t" . $row['Extra'] . "\t" .
291 basename($backtrace[1]["file"]) . "\t" .
292 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
293 substr($query, 0, 2000) . "\n", FILE_APPEND);
299 * Removes every not whitelisted character from the identifier string
301 * @param string $identifier
303 * @return string sanitized identifier
306 private function sanitizeIdentifier($identifier)
308 return preg_replace('/[^A-Za-z0-9_\-]+/', '', $identifier);
311 public function escape($str)
313 if ($this->connected) {
314 switch ($this->driver) {
316 return substr(@$this->connection->quote($str, PDO::PARAM_STR), 1, -1);
319 return @$this->connection->real_escape_string($str);
322 return str_replace("'", "\\'", $str);
326 public function connected()
330 if (is_null($this->connection)) {
334 switch ($this->driver) {
336 $r = $this->p("SELECT 1");
337 if ($this->isResult($r)) {
338 $row = $this->toArray($r);
339 $connected = ($row[0]['1'] == '1');
343 $connected = $this->connection->ping();
350 * @brief Replaces ANY_VALUE() function by MIN() function,
351 * if the database server does not support ANY_VALUE().
353 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
354 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
355 * A standard fall-back is to use MIN().
357 * @param string $sql An SQL string without the values
359 * @return string The input SQL string modified if necessary.
361 public function anyValueFallback($sql)
363 $server_info = $this->serverInfo();
364 if (version_compare($server_info, '5.7.5', '<') ||
365 (stripos($server_info, 'MariaDB') !== false)) {
366 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
372 * @brief Replaces the ? placeholders with the parameters in the $args array
374 * @param string $sql SQL query
375 * @param array $args The parameters that are to replace the ? placeholders
377 * @return string The replaced SQL query
379 private function replaceParameters($sql, $args)
382 foreach ($args AS $param => $value) {
383 if (is_int($args[$param]) || is_float($args[$param])) {
384 $replace = intval($args[$param]);
386 $replace = "'" . $this->escape($args[$param]) . "'";
389 $pos = strpos($sql, '?', $offset);
390 if ($pos !== false) {
391 $sql = substr_replace($sql, $replace, $pos, 1);
393 $offset = $pos + strlen($replace);
399 * @brief Executes a prepared statement that returns data
400 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
402 * Please only use it with complicated queries.
403 * For all regular queries please use DBA::select or DBA::exists
405 * @param string $sql SQL statement
407 * @return bool|object statement object or result object
410 public function p($sql)
413 $stamp1 = microtime(true);
415 $params = DBA::getParam(func_get_args());
417 // Renumber the array keys to be sure that they fit
420 foreach ($params AS $param) {
421 // Avoid problems with some MySQL servers and boolean values. See issue #3645
422 if (is_bool($param)) {
423 $param = (int)$param;
425 $args[++$i] = $param;
428 if (!$this->connected) {
432 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
433 // Question: Should we continue or stop the query here?
434 $this->logger->warning('Query parameters mismatch.', ['query' => $sql, 'args' => $args, 'callstack' => System::callstack()]);
437 $sql = DBA::cleanQuery($sql);
438 $sql = $this->anyValueFallback($sql);
442 if ($this->configCache->get('system', 'db_callstack') !== null) {
443 $sql = "/*" . System::callstack() . " */ " . $sql;
448 $this->affected_rows = 0;
450 // We have to make some things different if this function is called from "e"
451 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
453 if (isset($trace[1])) {
454 $called_from = $trace[1];
456 // We use just something that is defined to avoid warnings
457 $called_from = $trace[0];
459 // We are having an own error logging in the function "e"
460 $called_from_e = ($called_from['function'] == 'e');
462 switch ($this->driver) {
464 // If there are no arguments we use "query"
465 if (count($args) == 0) {
466 if (!$retval = $this->connection->query($sql)) {
467 $errorInfo = $this->connection->errorInfo();
468 $this->error = $errorInfo[2];
469 $this->errorno = $errorInfo[1];
473 $this->affected_rows = $retval->rowCount();
477 /** @var $stmt mysqli_stmt|PDOStatement */
478 if (!$stmt = $this->connection->prepare($sql)) {
479 $errorInfo = $this->connection->errorInfo();
480 $this->error = $errorInfo[2];
481 $this->errorno = $errorInfo[1];
486 foreach ($args AS $param => $value) {
487 if (is_int($args[$param])) {
488 $data_type = PDO::PARAM_INT;
490 $data_type = PDO::PARAM_STR;
492 $stmt->bindParam($param, $args[$param], $data_type);
495 if (!$stmt->execute()) {
496 $errorInfo = $stmt->errorInfo();
497 $this->error = $errorInfo[2];
498 $this->errorno = $errorInfo[1];
502 $this->affected_rows = $retval->rowCount();
506 // There are SQL statements that cannot be executed with a prepared statement
507 $parts = explode(' ', $orig_sql);
508 $command = strtolower($parts[0]);
509 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
511 // The fallback routine is called as well when there are no arguments
512 if (!$can_be_prepared || (count($args) == 0)) {
513 $retval = $this->connection->query($this->replaceParameters($sql, $args));
514 if ($this->connection->errno) {
515 $this->error = $this->connection->error;
516 $this->errorno = $this->connection->errno;
519 if (isset($retval->num_rows)) {
520 $this->affected_rows = $retval->num_rows;
522 $this->affected_rows = $this->connection->affected_rows;
528 $stmt = $this->connection->stmt_init();
530 if (!$stmt->prepare($sql)) {
531 $this->error = $stmt->error;
532 $this->errorno = $stmt->errno;
539 foreach ($args AS $param => $value) {
540 if (is_int($args[$param])) {
542 } elseif (is_float($args[$param])) {
544 } elseif (is_string($args[$param])) {
549 $values[] = &$args[$param];
552 if (count($values) > 0) {
553 array_unshift($values, $param_types);
554 call_user_func_array([$stmt, 'bind_param'], $values);
557 if (!$stmt->execute()) {
558 $this->error = $this->connection->error;
559 $this->errorno = $this->connection->errno;
562 $stmt->store_result();
564 $this->affected_rows = $retval->affected_rows;
569 // We are having an own error logging in the function "e"
570 if (($this->errorno != 0) && !$called_from_e) {
571 // We have to preserve the error code, somewhere in the logging it get lost
572 $error = $this->error;
573 $errorno = $this->errorno;
575 $this->logger->error('DB Error', [
576 'code' => $this->errorno,
577 'error' => $this->error,
578 'callstack' => System::callstack(8),
579 'params' => $this->replaceParameters($sql, $args),
582 // On a lost connection we try to reconnect - but only once.
583 if ($errorno == 2006) {
584 if ($this->in_retrial || !$this->reconnect()) {
585 // It doesn't make sense to continue when the database connection was lost
586 if ($this->in_retrial) {
587 $this->logger->notice('Giving up retrial because of database error', [
588 'code' => $this->errorno,
589 'error' => $this->error,
592 $this->logger->notice('Couldn\'t reconnect after database error', [
593 'code' => $this->errorno,
594 'error' => $this->error,
600 $this->logger->notice('Reconnected after database error', [
601 'code' => $this->errorno,
602 'error' => $this->error,
604 $this->in_retrial = true;
605 $ret = $this->p($sql, $args);
606 $this->in_retrial = false;
611 $this->error = $error;
612 $this->errorno = $errorno;
615 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
617 if ($this->configCache->get('system', 'db_log')) {
618 $stamp2 = microtime(true);
619 $duration = (float)($stamp2 - $stamp1);
621 if (($duration > $this->configCache->get('system', 'db_loglimit'))) {
622 $duration = round($duration, 3);
623 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
625 @file_put_contents($this->configCache->get('system', 'db_log'), DateTimeFormat::utcNow() . "\t" . $duration . "\t" .
626 basename($backtrace[1]["file"]) . "\t" .
627 $backtrace[1]["line"] . "\t" . $backtrace[2]["function"] . "\t" .
628 substr($this->replaceParameters($sql, $args), 0, 2000) . "\n", FILE_APPEND);
635 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
637 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
639 * @param string $sql SQL statement
641 * @return boolean Was the query successfull? False is returned only if an error occurred
644 public function e($sql)
647 $stamp = microtime(true);
649 $params = DBA::getParam(func_get_args());
651 // In a case of a deadlock we are repeating the query 20 times
655 $stmt = $this->p($sql, $params);
657 if (is_bool($stmt)) {
659 } elseif (is_object($stmt)) {
667 } while (($this->errorno == 1213) && (--$timeout > 0));
669 if ($this->errorno != 0) {
670 // We have to preserve the error code, somewhere in the logging it get lost
671 $error = $this->error;
672 $errorno = $this->errorno;
674 $this->logger->error('DB Error', [
675 'code' => $this->errorno,
676 'error' => $this->error,
677 'callstack' => System::callstack(8),
678 'params' => $this->replaceParameters($sql, $params),
681 // On a lost connection we simply quit.
682 // A reconnect like in $this->p could be dangerous with modifications
683 if ($errorno == 2006) {
684 $this->logger->notice('Giving up because of database error', [
685 'code' => $this->errorno,
686 'error' => $this->error,
691 $this->error = $error;
692 $this->errorno = $errorno;
695 $this->profiler->saveTimestamp($stamp, "database_write", System::callstack());
701 * @brief Check if data exists
703 * @param string $table Table name
704 * @param array $condition array of fields for condition
706 * @return boolean Are there rows for that condition?
709 public function exists($table, $condition)
717 if (empty($condition)) {
718 return DBStructure::existsTable($table);
722 $first_key = key($condition);
723 if (!is_int($first_key)) {
724 $fields = [$first_key];
727 $stmt = $this->select($table, $fields, $condition, ['limit' => 1]);
729 if (is_bool($stmt)) {
732 $retval = ($this->numRows($stmt) > 0);
741 * Fetches the first row
743 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
745 * @brief Fetches the first row
747 * @param string $sql SQL statement
749 * @return array first row of query
752 public function fetchFirst($sql)
754 $params = DBA::getParam(func_get_args());
756 $stmt = $this->p($sql, $params);
758 if (is_bool($stmt)) {
761 $retval = $this->fetch($stmt);
770 * @brief Returns the number of affected rows of the last statement
772 * @return int Number of rows
774 public function affectedRows()
776 return $this->affected_rows;
780 * @brief Returns the number of columns of a statement
782 * @param object Statement object
784 * @return int Number of columns
786 public function columnCount($stmt)
788 if (!is_object($stmt)) {
791 switch ($this->driver) {
793 return $stmt->columnCount();
795 return $stmt->field_count;
801 * @brief Returns the number of rows of a statement
803 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
805 * @return int Number of rows
807 public function numRows($stmt)
809 if (!is_object($stmt)) {
812 switch ($this->driver) {
814 return $stmt->rowCount();
816 return $stmt->num_rows;
822 * @brief Fetch a single row
824 * @param mixed $stmt statement object
826 * @return array current row
828 public function fetch($stmt)
831 $stamp1 = microtime(true);
835 if (!is_object($stmt)) {
839 switch ($this->driver) {
841 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
844 if (get_class($stmt) == 'mysqli_result') {
845 $columns = $stmt->fetch_assoc();
849 // This code works, but is slow
851 // Bind the result to a result array
855 for ($x = 0; $x < $stmt->field_count; $x++) {
856 $cols[] = &$cols_num[$x];
859 call_user_func_array([$stmt, 'bind_result'], $cols);
861 if (!$stmt->fetch()) {
866 // We need to get the field names for the array keys
867 // It seems that there is no better way to do this.
868 $result = $stmt->result_metadata();
869 $fields = $result->fetch_fields();
871 foreach ($cols_num AS $param => $col) {
872 $columns[$fields[$param]->name] = $col;
876 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
882 * @brief Insert a row into a table
884 * @param string/array $table Table name
886 * @return string formatted and sanitzed table name
889 public function formatTableName($table)
891 if (is_string($table)) {
892 return "`" . $this->sanitizeIdentifier($table) . "`";
895 if (!is_array($table)) {
899 $scheme = key($table);
901 return "`" . $this->sanitizeIdentifier($scheme) . "`.`" . $this->sanitizeIdentifier($table[$scheme]) . "`";
905 * @brief Insert a row into a table
907 * @param string $table Table name
908 * @param array $param parameter array
909 * @param bool $on_duplicate_update Do an update on a duplicate entry
911 * @return boolean was the insert successful?
914 public function insert($table, $param, $on_duplicate_update = false)
917 if (empty($table) || empty($param)) {
918 $this->logger->info('Table and fields have to be set');
922 $sql = "INSERT INTO " . $this->formatTableName($table) . " (`" . implode("`, `", array_keys($param)) . "`) VALUES (" .
923 substr(str_repeat("?, ", count($param)), 0, -2) . ")";
925 if ($on_duplicate_update) {
926 $sql .= " ON DUPLICATE KEY UPDATE `" . implode("` = ?, `", array_keys($param)) . "` = ?";
928 $values = array_values($param);
929 $param = array_merge_recursive($values, $values);
932 return $this->e($sql, $param);
936 * @brief Fetch the id of the last insert command
938 * @return integer Last inserted id
940 public function lastInsertId()
942 switch ($this->driver) {
944 $id = $this->connection->lastInsertId();
947 $id = $this->connection->insert_id;
954 * @brief Locks a table for exclusive write access
956 * This function can be extended in the future to accept a table array as well.
958 * @param string $table Table name
960 * @return boolean was the lock successful?
963 public function lock($table)
965 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
966 if ($this->driver == 'pdo') {
967 $this->e("SET autocommit=0");
968 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
970 $this->connection->autocommit(false);
973 $success = $this->e("LOCK TABLES " . $this->formatTableName($table) . " WRITE");
975 if ($this->driver == 'pdo') {
976 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
980 if ($this->driver == 'pdo') {
981 $this->e("SET autocommit=1");
983 $this->connection->autocommit(true);
986 $this->in_transaction = true;
992 * @brief Unlocks all locked tables
994 * @return boolean was the unlock successful?
997 public function unlock()
999 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
1000 $this->performCommit();
1002 if ($this->driver == 'pdo') {
1003 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
1006 $success = $this->e("UNLOCK TABLES");
1008 if ($this->driver == 'pdo') {
1009 $this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
1010 $this->e("SET autocommit=1");
1012 $this->connection->autocommit(true);
1015 $this->in_transaction = false;
1020 * @brief Starts a transaction
1022 * @return boolean Was the command executed successfully?
1024 public function transaction()
1026 if (!$this->performCommit()) {
1030 switch ($this->driver) {
1032 if (!$this->connection->inTransaction() && !$this->connection->beginTransaction()) {
1038 if (!$this->connection->begin_transaction()) {
1044 $this->in_transaction = true;
1048 private function performCommit()
1050 switch ($this->driver) {
1052 if (!$this->connection->inTransaction()) {
1056 return $this->connection->commit();
1059 return $this->connection->commit();
1066 * @brief Does a commit
1068 * @return boolean Was the command executed successfully?
1070 public function commit()
1072 if (!$this->performCommit()) {
1075 $this->in_transaction = false;
1080 * @brief Does a rollback
1082 * @return boolean Was the command executed successfully?
1084 public function rollback()
1088 switch ($this->driver) {
1090 if (!$this->connection->inTransaction()) {
1094 $ret = $this->connection->rollBack();
1098 $ret = $this->connection->rollback();
1101 $this->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 function buildRelationData()
1114 $definition = DBStructure::definition($this->configCache->get('system', 'basepath'));
1116 foreach ($definition AS $table => $structure) {
1117 foreach ($structure['fields'] AS $field => $field_struct) {
1118 if (isset($field_struct['relation'])) {
1119 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1120 $this->relation[$rel_table][$rel_field][$table][] = $field;
1128 * @brief Delete a row from a table
1130 * @param string $table Table name
1131 * @param array $conditions Field condition(s)
1132 * @param array $options
1133 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1134 * relations (default: true)
1135 * @param array $callstack Internal use: prevent endless loops
1137 * @return boolean was the delete successful?
1138 * @throws \Exception
1140 public function delete($table, array $conditions, array $options = [], array &$callstack = [])
1142 if (empty($table) || empty($conditions)) {
1143 $this->logger->info('Table and conditions have to be set');
1149 // Create a key for the loop prevention
1150 $key = $table . ':' . json_encode($conditions);
1152 // We quit when this key already exists in the callstack.
1153 if (isset($callstack[$key])) {
1157 $callstack[$key] = true;
1159 $table = $this->sanitizeIdentifier($table);
1161 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1163 // Don't use "defaults" here, since it would set "false" to "true"
1164 if (isset($options['cascade'])) {
1165 $cascade = $options['cascade'];
1170 // To speed up the whole process we cache the table relations
1171 if ($cascade && count($this->relation) == 0) {
1172 $this->buildRelationData();
1175 // Is there a relation entry for the table?
1176 if ($cascade && isset($this->relation[$table])) {
1177 // We only allow a simple "one field" relation.
1178 $field = array_keys($this->relation[$table])[0];
1179 $rel_def = array_values($this->relation[$table])[0];
1181 // Create a key for preventing double queries
1182 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1184 // When the search field is the relation field, we don't need to fetch the rows
1185 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1186 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1187 foreach ($rel_def AS $rel_table => $rel_fields) {
1188 foreach ($rel_fields AS $rel_field) {
1189 $this->delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, $callstack);
1192 // We quit when this key already exists in the callstack.
1193 } elseif (!isset($callstack[$qkey])) {
1194 $callstack[$qkey] = true;
1196 // Fetch all rows that are to be deleted
1197 $data = $this->select($table, [$field], $conditions);
1199 while ($row = $this->fetch($data)) {
1200 $this->delete($table, [$field => $row[$field]], $options, $callstack);
1203 $this->close($data);
1205 // Since we had split the delete command we don't need the original command anymore
1206 unset($commands[$key]);
1210 // Now we finalize the process
1211 $do_transaction = !$this->in_transaction;
1213 if ($do_transaction) {
1214 $this->transaction();
1220 foreach ($commands AS $command) {
1221 $conditions = $command['conditions'];
1223 $first_key = key($conditions);
1225 $condition_string = DBA::buildCondition($conditions);
1227 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1228 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1229 $this->logger->debug($this->replaceParameters($sql, $conditions));
1231 if (!$this->e($sql, $conditions)) {
1232 if ($do_transaction) {
1238 $key_table = $command['table'];
1239 $key_condition = array_keys($command['conditions'])[0];
1240 $value = array_values($command['conditions'])[0];
1242 // Split the SQL queries in chunks of 100 values
1243 // We do the $i stuff here to make the code better readable
1244 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1245 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1249 $compacted[$key_table][$key_condition][$i][$value] = $value;
1250 $counter[$key_table][$key_condition] = $i;
1253 foreach ($compacted AS $table => $values) {
1254 foreach ($values AS $field => $field_value_list) {
1255 foreach ($field_value_list AS $field_values) {
1256 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1257 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1259 $this->logger->debug($this->replaceParameters($sql, $field_values));
1261 if (!$this->e($sql, $field_values)) {
1262 if ($do_transaction) {
1270 if ($do_transaction) {
1277 * @brief Updates rows
1279 * Updates rows in the database. When $old_fields is set to an array,
1280 * the system will only do an update if the fields in that array changed.
1283 * Only the values in $old_fields are compared.
1284 * This is an intentional behaviour.
1287 * We include the timestamp field in $fields but not in $old_fields.
1288 * Then the row will only get the new timestamp when the other fields had changed.
1290 * When $old_fields is set to a boolean value the system will do this compare itself.
1291 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1294 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1295 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1297 * @param string $table Table name
1298 * @param array $fields contains the fields that are updated
1299 * @param array $condition condition array with the key values
1300 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1302 * @return boolean was the update successfull?
1303 * @throws \Exception
1305 public function update($table, $fields, $condition, $old_fields = [])
1308 if (empty($table) || empty($fields) || empty($condition)) {
1309 $this->logger->info('Table, fields and condition have to be set');
1313 $condition_string = DBA::buildCondition($condition);
1315 if (is_bool($old_fields)) {
1316 $do_insert = $old_fields;
1318 $old_fields = $this->selectFirst($table, [], $condition);
1320 if (is_bool($old_fields)) {
1322 $values = array_merge($condition, $fields);
1323 return $this->insert($table, $values, $do_insert);
1329 $do_update = (count($old_fields) == 0);
1331 foreach ($old_fields AS $fieldname => $content) {
1332 if (isset($fields[$fieldname])) {
1333 if (($fields[$fieldname] == $content) && !is_null($content)) {
1334 unset($fields[$fieldname]);
1341 if (!$do_update || (count($fields) == 0)) {
1345 $sql = "UPDATE " . $this->formatTableName($table) . " SET `" .
1346 implode("` = ?, `", array_keys($fields)) . "` = ?" . $condition_string;
1348 $params1 = array_values($fields);
1349 $params2 = array_values($condition);
1350 $params = array_merge_recursive($params1, $params2);
1352 return $this->e($sql, $params);
1356 * Retrieve a single record from a table and returns it in an associative array
1358 * @brief Retrieve a single record from a table
1360 * @param string $table
1361 * @param array $fields
1362 * @param array $condition
1363 * @param array $params
1365 * @return bool|array
1366 * @throws \Exception
1367 * @see $this->select
1369 public function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1371 $params['limit'] = 1;
1372 $result = $this->select($table, $fields, $condition, $params);
1374 if (is_bool($result)) {
1377 $row = $this->fetch($result);
1378 $this->close($result);
1384 * @brief Select rows from a table
1386 * @param string $table Table name
1387 * @param array $fields Array of selected fields, empty for all
1388 * @param array $condition Array of fields for condition
1389 * @param array $params Array of several parameters
1391 * @return boolean|object
1395 * $fields = array("id", "uri", "uid", "network");
1397 * $condition = array("uid" => 1, "network" => 'dspr');
1399 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1401 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1403 * $data = DBA::select($table, $fields, $condition, $params);
1404 * @throws \Exception
1406 public function select($table, array $fields = [], array $condition = [], array $params = [])
1408 if (empty($table)) {
1412 if (count($fields) > 0) {
1413 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1415 $select_fields = "*";
1418 $condition_string = DBA::buildCondition($condition);
1420 $param_string = DBA::buildParameter($params);
1422 $sql = "SELECT " . $select_fields . " FROM " . $this->formatTableName($table) . $condition_string . $param_string;
1424 $result = $this->p($sql, $condition);
1430 * @brief Counts the rows from a table satisfying the provided condition
1432 * @param string $table Table name
1433 * @param array $condition array of fields for condition
1440 * $condition = ["uid" => 1, "network" => 'dspr'];
1442 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1444 * $count = DBA::count($table, $condition);
1445 * @throws \Exception
1447 public function count($table, array $condition = [])
1449 if (empty($table)) {
1453 $condition_string = DBA::buildCondition($condition);
1455 $sql = "SELECT COUNT(*) AS `count` FROM " . $this->formatTableName($table) . $condition_string;
1457 $row = $this->fetchFirst($sql, $condition);
1459 return $row['count'];
1463 * @brief Fills an array with data from a query
1465 * @param object $stmt statement object
1466 * @param bool $do_close
1468 * @return array Data array
1470 public function toArray($stmt, $do_close = true)
1472 if (is_bool($stmt)) {
1477 while ($row = $this->fetch($stmt)) {
1481 $this->close($stmt);
1487 * @brief Returns the error number of the last query
1489 * @return string Error number (0 if no error)
1491 public function errorNo()
1493 return $this->errorno;
1497 * @brief Returns the error message of the last query
1499 * @return string Error message ('' if no error)
1501 public function errorMessage()
1503 return $this->error;
1507 * @brief Closes the current statement
1509 * @param object $stmt statement object
1511 * @return boolean was the close successful?
1513 public function close($stmt)
1516 $stamp1 = microtime(true);
1518 if (!is_object($stmt)) {
1522 switch ($this->driver) {
1524 $ret = $stmt->closeCursor();
1527 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1528 // We should be careful not to assume the object type of $stmt
1529 // because DBA::p() has been able to return both types.
1530 if ($stmt instanceof mysqli_stmt) {
1531 $stmt->free_result();
1532 $ret = $stmt->close();
1533 } elseif ($stmt instanceof mysqli_result) {
1542 $this->profiler->saveTimestamp($stamp1, 'database', System::callstack());
1548 * @brief Return a list of database processes
1551 * 'list' => List of processes, separated in their different states
1552 * 'amount' => Number of concurrent database processes
1553 * @throws \Exception
1555 public function processlist()
1557 $ret = $this->p("SHOW PROCESSLIST");
1558 $data = $this->toArray($ret);
1562 foreach ($data as $process) {
1563 $state = trim($process["State"]);
1565 // Filter out all non blocking processes
1566 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1573 foreach ($states as $state => $usage) {
1574 if ($statelist != "") {
1577 $statelist .= $state . ": " . $usage;
1579 return (["list" => $statelist, "amount" => $processes]);
1583 * Checks if $array is a filled array with at least one entry.
1585 * @param mixed $array A filled array with at least one entry
1587 * @return boolean Whether $array is a filled array or an object with rows
1589 public function isResult($array)
1591 // It could be a return value from an update statement
1592 if (is_bool($array)) {
1596 if (is_object($array)) {
1597 return $this->numRows($array) > 0;
1600 return (is_array($array) && (count($array) > 0));
1604 * @brief Callback function for "esc_array"
1606 * @param mixed $value Array value
1607 * @param string $key Array key
1608 * @param boolean $add_quotation add quotation marks for string values
1612 private function escapeArrayCallback(&$value, $key, $add_quotation)
1614 if (!$add_quotation) {
1615 if (is_bool($value)) {
1616 $value = ($value ? '1' : '0');
1618 $value = $this->escape($value);
1623 if (is_bool($value)) {
1624 $value = ($value ? 'true' : 'false');
1625 } elseif (is_float($value) || is_integer($value)) {
1626 $value = (string)$value;
1628 $value = "'" . $this->escape($value) . "'";
1633 * @brief Escapes a whole array
1635 * @param mixed $arr Array with values to be escaped
1636 * @param boolean $add_quotation add quotation marks for string values
1640 public function escapeArray(&$arr, $add_quotation = false)
1642 array_walk($arr, [$this, 'escapeArrayCallback'], $add_quotation);