3 namespace Friendica\Database;
5 // Do not use Core\Config in this class at risk of infinite loop.
6 // Please use App->getConfigVariable() instead.
7 //use Friendica\Core\Config;
9 use Friendica\Core\System;
10 use Friendica\Util\DateTimeFormat;
18 require_once 'include/dba.php';
21 * @class MySQL database class
23 * This class is for the low level database stuff that does driver specific things.
27 const NULL_DATE = '0001-01-01';
28 const NULL_DATETIME = '0001-01-01 00:00:00';
30 public static $connected = false;
32 private static $server_info = '';
33 private static $connection;
34 private static $driver;
35 private static $error = false;
36 private static $errorno = 0;
37 private static $affected_rows = 0;
38 private static $in_transaction = false;
39 private static $in_retrial = false;
40 private static $relation = [];
41 private static $db_serveraddr = '';
42 private static $db_user = '';
43 private static $db_pass = '';
44 private static $db_name = '';
45 private static $db_charset = '';
47 public static function connect($serveraddr, $user, $pass, $db, $charset = null)
49 if (!is_null(self::$connection) && self::connected()) {
53 // We are storing these values for being able to perform a reconnect
54 self::$db_serveraddr = $serveraddr;
55 self::$db_user = $user;
56 self::$db_pass = $pass;
58 self::$db_charset = $charset;
61 $serveraddr = trim($serveraddr);
63 $serverdata = explode(':', $serveraddr);
64 $server = $serverdata[0];
66 if (count($serverdata) > 1) {
67 $port = trim($serverdata[1]);
70 $server = trim($server);
74 $charset = trim($charset);
76 if (!(strlen($server) && strlen($user))) {
80 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
81 self::$driver = 'pdo';
82 $connect = "mysql:host=".$server.";dbname=".$db;
85 $connect .= ";port=".$port;
89 $connect .= ";charset=".$charset;
93 self::$connection = @new PDO($connect, $user, $pass);
94 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
95 self::$connected = true;
96 } catch (PDOException $e) {
97 /// @TODO At least log exception, don't ignore it!
101 if (!self::$connected && class_exists('\mysqli')) {
102 self::$driver = 'mysqli';
105 self::$connection = @new mysqli($server, $user, $pass, $db, $port);
107 self::$connection = @new mysqli($server, $user, $pass, $db);
110 if (!mysqli_connect_errno()) {
111 self::$connected = true;
114 self::$connection->set_charset($charset);
119 // No suitable SQL driver was found.
120 if (!self::$connected) {
121 self::$driver = null;
122 self::$connection = null;
125 return self::$connected;
129 * Disconnects the current database connection
131 public static function disconnect()
133 if (is_null(self::$connection)) {
137 switch (self::$driver) {
139 self::$connection = null;
142 self::$connection->close();
143 self::$connection = null;
149 * Perform a reconnect of an existing database connection
151 public static function reconnect() {
154 $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset);
159 * Return the database object.
162 public static function getConnection()
164 return self::$connection;
168 * @brief Returns the MySQL server version string
170 * This function discriminate between the deprecated mysql API and the current
171 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
175 public static function serverInfo() {
176 if (self::$server_info == '') {
177 switch (self::$driver) {
179 self::$server_info = self::$connection->getAttribute(PDO::ATTR_SERVER_VERSION);
182 self::$server_info = self::$connection->server_info;
186 return self::$server_info;
190 * @brief Returns the selected database name
194 public static function databaseName() {
195 $ret = self::p("SELECT DATABASE() AS `db`");
196 $data = self::toArray($ret);
197 return $data[0]['db'];
201 * @brief Analyze a database query and log this if some conditions are met.
203 * @param string $query The database query that will be analyzed
205 private static function logIndex($query) {
208 if (!$a->getConfigVariable('system', 'db_log_index')) {
212 // Don't explain an explain statement
213 if (strtolower(substr($query, 0, 7)) == "explain") {
217 // Only do the explain on "select", "update" and "delete"
218 if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
222 $r = self::p("EXPLAIN ".$query);
223 if (!self::isResult($r)) {
227 $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch'));
228 $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist'));
230 while ($row = self::fetch($r)) {
231 if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) {
232 $log = (in_array($row['key'], $watchlist) &&
233 ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index'))));
238 if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) {
242 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
247 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
248 @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t".
249 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
250 basename($backtrace[1]["file"])."\t".
251 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
252 substr($query, 0, 2000)."\n", FILE_APPEND);
257 public static function escape($str) {
258 if (self::$connected) {
259 switch (self::$driver) {
261 return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
264 return @self::$connection->real_escape_string($str);
267 return str_replace("'", "\\'", $str);
271 public static function connected() {
274 if (is_null(self::$connection)) {
278 switch (self::$driver) {
280 $r = self::p("SELECT 1");
281 if (self::isResult($r)) {
282 $row = self::toArray($r);
283 $connected = ($row[0]['1'] == '1');
287 $connected = self::$connection->ping();
294 * @brief Replaces ANY_VALUE() function by MIN() function,
295 * if the database server does not support ANY_VALUE().
297 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
298 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
299 * A standard fall-back is to use MIN().
301 * @param string $sql An SQL string without the values
302 * @return string The input SQL string modified if necessary.
304 public static function anyValueFallback($sql) {
305 $server_info = self::serverInfo();
306 if (version_compare($server_info, '5.7.5', '<') ||
307 (stripos($server_info, 'MariaDB') !== false)) {
308 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
314 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
316 * This is safe when we bind the parameters later.
317 * The parameter values aren't part of the SQL.
319 * @param string $sql An SQL string without the values
320 * @return string The input SQL string modified if necessary.
322 public static function cleanQuery($sql) {
323 $search = ["\t", "\n", "\r", " "];
324 $replace = [' ', ' ', ' ', ' '];
327 $sql = str_replace($search, $replace, $sql);
328 } while ($oldsql != $sql);
335 * @brief Replaces the ? placeholders with the parameters in the $args array
337 * @param string $sql SQL query
338 * @param array $args The parameters that are to replace the ? placeholders
339 * @return string The replaced SQL query
341 private static function replaceParameters($sql, $args) {
343 foreach ($args AS $param => $value) {
344 if (is_int($args[$param]) || is_float($args[$param])) {
345 $replace = intval($args[$param]);
347 $replace = "'".self::escape($args[$param])."'";
350 $pos = strpos($sql, '?', $offset);
351 if ($pos !== false) {
352 $sql = substr_replace($sql, $replace, $pos, 1);
354 $offset = $pos + strlen($replace);
360 * @brief Convert parameter array to an universal form
361 * @param array $args Parameter array
362 * @return array universalized parameter array
364 private static function getParam($args) {
367 // When the second function parameter is an array then use this as the parameter array
368 if ((count($args) > 0) && (is_array($args[1]))) {
376 * @brief Executes a prepared statement that returns data
377 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
379 * Please only use it with complicated queries.
380 * For all regular queries please use DBA::select or DBA::exists
382 * @param string $sql SQL statement
383 * @return bool|object statement object or result object
385 public static function p($sql) {
388 $stamp1 = microtime(true);
390 $params = self::getParam(func_get_args());
392 // Renumber the array keys to be sure that they fit
395 foreach ($params AS $param) {
396 // Avoid problems with some MySQL servers and boolean values. See issue #3645
397 if (is_bool($param)) {
398 $param = (int)$param;
400 $args[++$i] = $param;
403 if (!self::$connected) {
407 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
408 // Question: Should we continue or stop the query here?
409 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
412 $sql = self::cleanQuery($sql);
413 $sql = self::anyValueFallback($sql);
417 if ($a->getConfigValue('system', 'db_callstack')) {
418 $sql = "/*".System::callstack()." */ ".$sql;
423 self::$affected_rows = 0;
425 // We have to make some things different if this function is called from "e"
426 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
428 if (isset($trace[1])) {
429 $called_from = $trace[1];
431 // We use just something that is defined to avoid warnings
432 $called_from = $trace[0];
434 // We are having an own error logging in the function "e"
435 $called_from_e = ($called_from['function'] == 'e');
437 switch (self::$driver) {
439 // If there are no arguments we use "query"
440 if (count($args) == 0) {
441 if (!$retval = self::$connection->query($sql)) {
442 $errorInfo = self::$connection->errorInfo();
443 self::$error = $errorInfo[2];
444 self::$errorno = $errorInfo[1];
448 self::$affected_rows = $retval->rowCount();
452 if (!$stmt = self::$connection->prepare($sql)) {
453 $errorInfo = self::$connection->errorInfo();
454 self::$error = $errorInfo[2];
455 self::$errorno = $errorInfo[1];
460 foreach ($args AS $param => $value) {
461 if (is_int($args[$param])) {
462 $data_type = PDO::PARAM_INT;
464 $data_type = PDO::PARAM_STR;
466 $stmt->bindParam($param, $args[$param], $data_type);
469 if (!$stmt->execute()) {
470 $errorInfo = $stmt->errorInfo();
471 self::$error = $errorInfo[2];
472 self::$errorno = $errorInfo[1];
476 self::$affected_rows = $retval->rowCount();
480 // There are SQL statements that cannot be executed with a prepared statement
481 $parts = explode(' ', $orig_sql);
482 $command = strtolower($parts[0]);
483 $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
485 // The fallback routine is called as well when there are no arguments
486 if (!$can_be_prepared || (count($args) == 0)) {
487 $retval = self::$connection->query(self::replaceParameters($sql, $args));
488 if (self::$connection->errno) {
489 self::$error = self::$connection->error;
490 self::$errorno = self::$connection->errno;
493 if (isset($retval->num_rows)) {
494 self::$affected_rows = $retval->num_rows;
496 self::$affected_rows = self::$connection->affected_rows;
502 $stmt = self::$connection->stmt_init();
504 if (!$stmt->prepare($sql)) {
505 self::$error = $stmt->error;
506 self::$errorno = $stmt->errno;
513 foreach ($args AS $param => $value) {
514 if (is_int($args[$param])) {
516 } elseif (is_float($args[$param])) {
518 } elseif (is_string($args[$param])) {
523 $values[] = &$args[$param];
526 if (count($values) > 0) {
527 array_unshift($values, $param_types);
528 call_user_func_array([$stmt, 'bind_param'], $values);
531 if (!$stmt->execute()) {
532 self::$error = self::$connection->error;
533 self::$errorno = self::$connection->errno;
536 $stmt->store_result();
538 self::$affected_rows = $retval->affected_rows;
543 // We are having an own error logging in the function "e"
544 if ((self::$errorno != 0) && !$called_from_e) {
545 // We have to preserve the error code, somewhere in the logging it get lost
546 $error = self::$error;
547 $errorno = self::$errorno;
549 logger('DB Error '.self::$errorno.': '.self::$error."\n".
550 System::callstack(8)."\n".self::replaceParameters($sql, $args));
552 // On a lost connection we try to reconnect - but only once.
553 if ($errorno == 2006) {
554 if (self::$in_retrial || !self::reconnect()) {
555 // It doesn't make sense to continue when the database connection was lost
556 if (self::$in_retrial) {
557 logger('Giving up retrial because of database error '.$errorno.': '.$error);
559 logger("Couldn't reconnect after database error ".$errorno.': '.$error);
564 logger('Reconnected after database error '.$errorno.': '.$error);
565 self::$in_retrial = true;
566 $ret = self::p($sql, $args);
567 self::$in_retrial = false;
572 self::$error = $error;
573 self::$errorno = $errorno;
576 $a->saveTimestamp($stamp1, 'database');
578 if ($a->getConfigValue('system', 'db_log')) {
579 $stamp2 = microtime(true);
580 $duration = (float)($stamp2 - $stamp1);
582 if (($duration > $a->getConfigValue('system', 'db_loglimit'))) {
583 $duration = round($duration, 3);
584 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
586 @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t".
587 basename($backtrace[1]["file"])."\t".
588 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
589 substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
596 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
598 * Please use DBA::delete, DBA::insert, DBA::update, ... instead
600 * @param string $sql SQL statement
601 * @return boolean Was the query successfull? False is returned only if an error occurred
603 public static function e($sql) {
606 $stamp = microtime(true);
608 $params = self::getParam(func_get_args());
610 // In a case of a deadlock we are repeating the query 20 times
614 $stmt = self::p($sql, $params);
616 if (is_bool($stmt)) {
618 } elseif (is_object($stmt)) {
626 } while ((self::$errorno == 1213) && (--$timeout > 0));
628 if (self::$errorno != 0) {
629 // We have to preserve the error code, somewhere in the logging it get lost
630 $error = self::$error;
631 $errorno = self::$errorno;
633 logger('DB Error '.self::$errorno.': '.self::$error."\n".
634 System::callstack(8)."\n".self::replaceParameters($sql, $params));
636 // On a lost connection we simply quit.
637 // A reconnect like in self::p could be dangerous with modifications
638 if ($errorno == 2006) {
639 logger('Giving up because of database error '.$errorno.': '.$error);
643 self::$error = $error;
644 self::$errorno = $errorno;
647 $a->saveTimestamp($stamp, "database_write");
653 * @brief Check if data exists
655 * @param string $table Table name
656 * @param array $condition array of fields for condition
658 * @return boolean Are there rows for that condition?
660 public static function exists($table, $condition) {
667 if (empty($condition)) {
668 return DBStructure::existsTable($table);
672 $first_key = key($condition);
673 if (!is_int($first_key)) {
674 $fields = [$first_key];
677 $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
679 if (is_bool($stmt)) {
682 $retval = (self::numRows($stmt) > 0);
691 * Fetches the first row
693 * Please use DBA::selectFirst or DBA::exists whenever this is possible.
695 * @brief Fetches the first row
696 * @param string $sql SQL statement
697 * @return array first row of query
699 public static function fetchFirst($sql) {
700 $params = self::getParam(func_get_args());
702 $stmt = self::p($sql, $params);
704 if (is_bool($stmt)) {
707 $retval = self::fetch($stmt);
716 * @brief Returns the number of affected rows of the last statement
718 * @return int Number of rows
720 public static function affectedRows() {
721 return self::$affected_rows;
725 * @brief Returns the number of columns of a statement
727 * @param object Statement object
728 * @return int Number of columns
730 public static function columnCount($stmt) {
731 if (!is_object($stmt)) {
734 switch (self::$driver) {
736 return $stmt->columnCount();
738 return $stmt->field_count;
743 * @brief Returns the number of rows of a statement
745 * @param PDOStatement|mysqli_result|mysqli_stmt Statement object
746 * @return int Number of rows
748 public static function numRows($stmt) {
749 if (!is_object($stmt)) {
752 switch (self::$driver) {
754 return $stmt->rowCount();
756 return $stmt->num_rows;
762 * @brief Fetch a single row
764 * @param mixed $stmt statement object
765 * @return array current row
767 public static function fetch($stmt) {
770 $stamp1 = microtime(true);
774 if (!is_object($stmt)) {
778 switch (self::$driver) {
780 $columns = $stmt->fetch(PDO::FETCH_ASSOC);
783 if (get_class($stmt) == 'mysqli_result') {
784 $columns = $stmt->fetch_assoc();
788 // This code works, but is slow
790 // Bind the result to a result array
794 for ($x = 0; $x < $stmt->field_count; $x++) {
795 $cols[] = &$cols_num[$x];
798 call_user_func_array([$stmt, 'bind_result'], $cols);
800 if (!$stmt->fetch()) {
805 // We need to get the field names for the array keys
806 // It seems that there is no better way to do this.
807 $result = $stmt->result_metadata();
808 $fields = $result->fetch_fields();
810 foreach ($cols_num AS $param => $col) {
811 $columns[$fields[$param]->name] = $col;
815 $a->saveTimestamp($stamp1, 'database');
821 * @brief Insert a row into a table
823 * @param string $table Table name
824 * @param array $param parameter array
825 * @param bool $on_duplicate_update Do an update on a duplicate entry
827 * @return boolean was the insert successful?
829 public static function insert($table, $param, $on_duplicate_update = false) {
831 if (empty($table) || empty($param)) {
832 logger('Table and fields have to be set');
836 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
837 substr(str_repeat("?, ", count($param)), 0, -2).")";
839 if ($on_duplicate_update) {
840 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
842 $values = array_values($param);
843 $param = array_merge_recursive($values, $values);
846 return self::e($sql, $param);
850 * @brief Fetch the id of the last insert command
852 * @return integer Last inserted id
854 public static function lastInsertId() {
855 switch (self::$driver) {
857 $id = self::$connection->lastInsertId();
860 $id = self::$connection->insert_id;
867 * @brief Locks a table for exclusive write access
869 * This function can be extended in the future to accept a table array as well.
871 * @param string $table Table name
873 * @return boolean was the lock successful?
875 public static function lock($table) {
876 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
877 if (self::$driver == 'pdo') {
878 self::e("SET autocommit=0");
879 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
881 self::$connection->autocommit(false);
884 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
886 if (self::$driver == 'pdo') {
887 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
891 if (self::$driver == 'pdo') {
892 self::e("SET autocommit=1");
894 self::$connection->autocommit(true);
897 self::$in_transaction = true;
903 * @brief Unlocks all locked tables
905 * @return boolean was the unlock successful?
907 public static function unlock() {
908 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
909 self::performCommit();
911 if (self::$driver == 'pdo') {
912 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
915 $success = self::e("UNLOCK TABLES");
917 if (self::$driver == 'pdo') {
918 self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
919 self::e("SET autocommit=1");
921 self::$connection->autocommit(true);
924 self::$in_transaction = false;
929 * @brief Starts a transaction
931 * @return boolean Was the command executed successfully?
933 public static function transaction() {
934 if (!self::performCommit()) {
938 switch (self::$driver) {
940 if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
946 if (!self::$connection->begin_transaction()) {
952 self::$in_transaction = true;
956 private static function performCommit()
958 switch (self::$driver) {
960 if (!self::$connection->inTransaction()) {
964 return self::$connection->commit();
967 return self::$connection->commit();
974 * @brief Does a commit
976 * @return boolean Was the command executed successfully?
978 public static function commit() {
979 if (!self::performCommit()) {
982 self::$in_transaction = false;
987 * @brief Does a rollback
989 * @return boolean Was the command executed successfully?
991 public static function rollback() {
994 switch (self::$driver) {
996 if (!self::$connection->inTransaction()) {
1000 $ret = self::$connection->rollBack();
1004 $ret = self::$connection->rollback();
1007 self::$in_transaction = false;
1012 * @brief Build the array with the table relations
1014 * The array is build from the database definitions in DBStructure.php
1016 * This process must only be started once, since the value is cached.
1018 private static function buildRelationData() {
1019 $definition = DBStructure::definition();
1021 foreach ($definition AS $table => $structure) {
1022 foreach ($structure['fields'] AS $field => $field_struct) {
1023 if (isset($field_struct['relation'])) {
1024 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1025 self::$relation[$rel_table][$rel_field][$table][] = $field;
1033 * @brief Delete a row from a table
1035 * @param string $table Table name
1036 * @param array $conditions Field condition(s)
1037 * @param array $options
1038 * - cascade: If true we delete records in other tables that depend on the one we're deleting through
1039 * relations (default: true)
1040 * @param boolean $in_process Internal use: Only do a commit after the last delete
1041 * @param array $callstack Internal use: prevent endless loops
1043 * @return boolean|array was the delete successful? When $in_process is set: deletion data
1045 public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
1047 if (empty($table) || empty($conditions)) {
1048 logger('Table and conditions have to be set');
1054 // Create a key for the loop prevention
1055 $key = $table . ':' . json_encode($conditions);
1057 // We quit when this key already exists in the callstack.
1058 if (isset($callstack[$key])) {
1062 $callstack[$key] = true;
1064 $table = self::escape($table);
1066 $commands[$key] = ['table' => $table, 'conditions' => $conditions];
1068 // Don't use "defaults" here, since it would set "false" to "true"
1069 if (isset($options['cascade'])) {
1070 $cascade = $options['cascade'];
1075 // To speed up the whole process we cache the table relations
1076 if ($cascade && count(self::$relation) == 0) {
1077 self::buildRelationData();
1080 // Is there a relation entry for the table?
1081 if ($cascade && isset(self::$relation[$table])) {
1082 // We only allow a simple "one field" relation.
1083 $field = array_keys(self::$relation[$table])[0];
1084 $rel_def = array_values(self::$relation[$table])[0];
1086 // Create a key for preventing double queries
1087 $qkey = $field . '-' . $table . ':' . json_encode($conditions);
1089 // When the search field is the relation field, we don't need to fetch the rows
1090 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1091 if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
1092 foreach ($rel_def AS $rel_table => $rel_fields) {
1093 foreach ($rel_fields AS $rel_field) {
1094 $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
1095 $commands = array_merge($commands, $retval);
1098 // We quit when this key already exists in the callstack.
1099 } elseif (!isset($callstack[$qkey])) {
1101 $callstack[$qkey] = true;
1103 // Fetch all rows that are to be deleted
1104 $data = self::select($table, [$field], $conditions);
1106 while ($row = self::fetch($data)) {
1107 // Now we accumulate the delete commands
1108 $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
1109 $commands = array_merge($commands, $retval);
1114 // Since we had split the delete command we don't need the original command anymore
1115 unset($commands[$key]);
1120 // Now we finalize the process
1121 $do_transaction = !self::$in_transaction;
1123 if ($do_transaction) {
1124 self::transaction();
1130 foreach ($commands AS $command) {
1131 $conditions = $command['conditions'];
1133 $first_key = key($conditions);
1135 $condition_string = self::buildCondition($conditions);
1137 if ((count($command['conditions']) > 1) || is_int($first_key)) {
1138 $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
1139 logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
1141 if (!self::e($sql, $conditions)) {
1142 if ($do_transaction) {
1148 $key_table = $command['table'];
1149 $key_condition = array_keys($command['conditions'])[0];
1150 $value = array_values($command['conditions'])[0];
1152 // Split the SQL queries in chunks of 100 values
1153 // We do the $i stuff here to make the code better readable
1154 $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0;
1155 if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
1159 $compacted[$key_table][$key_condition][$i][$value] = $value;
1160 $counter[$key_table][$key_condition] = $i;
1163 foreach ($compacted AS $table => $values) {
1164 foreach ($values AS $field => $field_value_list) {
1165 foreach ($field_value_list AS $field_values) {
1166 $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
1167 substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
1169 logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
1171 if (!self::e($sql, $field_values)) {
1172 if ($do_transaction) {
1180 if ($do_transaction) {
1190 * @brief Updates rows
1192 * Updates rows in the database. When $old_fields is set to an array,
1193 * the system will only do an update if the fields in that array changed.
1196 * Only the values in $old_fields are compared.
1197 * This is an intentional behaviour.
1200 * We include the timestamp field in $fields but not in $old_fields.
1201 * Then the row will only get the new timestamp when the other fields had changed.
1203 * When $old_fields is set to a boolean value the system will do this compare itself.
1204 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1207 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1208 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1210 * @param string $table Table name
1211 * @param array $fields contains the fields that are updated
1212 * @param array $condition condition array with the key values
1213 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1215 * @return boolean was the update successfull?
1217 public static function update($table, $fields, $condition, $old_fields = []) {
1219 if (empty($table) || empty($fields) || empty($condition)) {
1220 logger('Table, fields and condition have to be set');
1224 $table = self::escape($table);
1226 $condition_string = self::buildCondition($condition);
1228 if (is_bool($old_fields)) {
1229 $do_insert = $old_fields;
1231 $old_fields = self::selectFirst($table, [], $condition);
1233 if (is_bool($old_fields)) {
1235 $values = array_merge($condition, $fields);
1236 return self::insert($table, $values, $do_insert);
1242 $do_update = (count($old_fields) == 0);
1244 foreach ($old_fields AS $fieldname => $content) {
1245 if (isset($fields[$fieldname])) {
1246 if ($fields[$fieldname] == $content) {
1247 unset($fields[$fieldname]);
1254 if (!$do_update || (count($fields) == 0)) {
1258 $sql = "UPDATE `".$table."` SET `".
1259 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1261 $params1 = array_values($fields);
1262 $params2 = array_values($condition);
1263 $params = array_merge_recursive($params1, $params2);
1265 return self::e($sql, $params);
1269 * Retrieve a single record from a table and returns it in an associative array
1271 * @brief Retrieve a single record from a table
1272 * @param string $table
1273 * @param array $fields
1274 * @param array $condition
1275 * @param array $params
1276 * @return bool|array
1279 public static function selectFirst($table, array $fields = [], array $condition = [], $params = [])
1281 $params['limit'] = 1;
1282 $result = self::select($table, $fields, $condition, $params);
1284 if (is_bool($result)) {
1287 $row = self::fetch($result);
1288 self::close($result);
1294 * @brief Select rows from a table
1296 * @param string $table Table name
1297 * @param array $fields Array of selected fields, empty for all
1298 * @param array $condition Array of fields for condition
1299 * @param array $params Array of several parameters
1301 * @return boolean|object
1305 * $fields = array("id", "uri", "uid", "network");
1307 * $condition = array("uid" => 1, "network" => 'dspr');
1309 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1311 * $params = array("order" => array("id", "received" => true), "limit" => 10);
1313 * $data = DBA::select($table, $fields, $condition, $params);
1315 public static function select($table, array $fields = [], array $condition = [], array $params = [])
1321 $table = self::escape($table);
1323 if (count($fields) > 0) {
1324 $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
1326 $select_fields = "*";
1329 $condition_string = self::buildCondition($condition);
1331 $param_string = self::buildParameter($params);
1333 $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
1335 $result = self::p($sql, $condition);
1341 * @brief Counts the rows from a table satisfying the provided condition
1343 * @param string $table Table name
1344 * @param array $condition array of fields for condition
1351 * $condition = ["uid" => 1, "network" => 'dspr'];
1353 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1355 * $count = DBA::count($table, $condition);
1357 public static function count($table, array $condition = [])
1363 $condition_string = self::buildCondition($condition);
1365 $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
1367 $row = self::fetchFirst($sql, $condition);
1369 return $row['count'];
1373 * @brief Returns the SQL condition string built from the provided condition array
1375 * This function operates with two modes.
1376 * - Supplied with a filed/value associative array, it builds simple strict
1377 * equality conditions linked by AND.
1378 * - Supplied with a flat list, the first element is the condition string and
1379 * the following arguments are the values to be interpolated
1381 * $condition = ["uid" => 1, "network" => 'dspr'];
1383 * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
1385 * In either case, the provided array is left with the parameters only
1387 * @param array $condition
1390 public static function buildCondition(array &$condition = [])
1392 $condition_string = '';
1393 if (count($condition) > 0) {
1395 $first_key = key($condition);
1396 if (is_int($first_key)) {
1397 $condition_string = " WHERE (" . array_shift($condition) . ")";
1400 $condition_string = "";
1401 foreach ($condition as $field => $value) {
1402 if ($condition_string != "") {
1403 $condition_string .= " AND ";
1405 if (is_array($value)) {
1406 /* Workaround for MySQL Bug #64791.
1407 * Never mix data types inside any IN() condition.
1408 * In case of mixed types, cast all as string.
1409 * Logic needs to be consistent with DBA::p() data types.
1413 foreach ($value as $single_value) {
1414 if (is_int($single_value)) {
1421 if ($is_int && $is_alpha) {
1422 foreach ($value as &$ref) {
1424 $ref = (string)$ref;
1427 unset($ref); //Prevent accidental re-use.
1430 $new_values = array_merge($new_values, array_values($value));
1431 $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
1432 $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
1434 $new_values[$field] = $value;
1435 $condition_string .= "`" . $field . "` = ?";
1438 $condition_string = " WHERE (" . $condition_string . ")";
1439 $condition = $new_values;
1443 return $condition_string;
1447 * @brief Returns the SQL parameter string built from the provided parameter array
1449 * @param array $params
1452 public static function buildParameter(array $params = [])
1455 if (isset($params['order'])) {
1456 $order_string = " ORDER BY ";
1457 foreach ($params['order'] AS $fields => $order) {
1458 if (!is_int($fields)) {
1459 $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
1461 $order_string .= "`" . $order . "`, ";
1464 $order_string = substr($order_string, 0, -2);
1468 if (isset($params['limit']) && is_int($params['limit'])) {
1469 $limit_string = " LIMIT " . intval($params['limit']);
1472 if (isset($params['limit']) && is_array($params['limit'])) {
1473 $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
1476 return $order_string.$limit_string;
1480 * @brief Fills an array with data from a query
1482 * @param object $stmt statement object
1483 * @return array Data array
1485 public static function toArray($stmt, $do_close = true) {
1486 if (is_bool($stmt)) {
1491 while ($row = self::fetch($stmt)) {
1501 * @brief Returns the error number of the last query
1503 * @return string Error number (0 if no error)
1505 public static function errorNo() {
1506 return self::$errorno;
1510 * @brief Returns the error message of the last query
1512 * @return string Error message ('' if no error)
1514 public static function errorMessage() {
1515 return self::$error;
1519 * @brief Closes the current statement
1521 * @param object $stmt statement object
1522 * @return boolean was the close successful?
1524 public static function close($stmt) {
1527 $stamp1 = microtime(true);
1529 if (!is_object($stmt)) {
1533 switch (self::$driver) {
1535 $ret = $stmt->closeCursor();
1538 // MySQLi offers both a mysqli_stmt and a mysqli_result class.
1539 // We should be careful not to assume the object type of $stmt
1540 // because DBA::p() has been able to return both types.
1541 if ($stmt instanceof mysqli_stmt) {
1542 $stmt->free_result();
1543 $ret = $stmt->close();
1544 } elseif ($stmt instanceof mysqli_result) {
1553 $a->saveTimestamp($stamp1, 'database');
1559 * @brief Return a list of database processes
1562 * 'list' => List of processes, separated in their different states
1563 * 'amount' => Number of concurrent database processes
1565 public static function processlist()
1567 $ret = self::p("SHOW PROCESSLIST");
1568 $data = self::toArray($ret);
1574 foreach ($data as $process) {
1575 $state = trim($process["State"]);
1577 // Filter out all non blocking processes
1578 if (!in_array($state, ["", "init", "statistics", "updating"])) {
1585 foreach ($states as $state => $usage) {
1586 if ($statelist != "") {
1589 $statelist .= $state.": ".$usage;
1591 return(["list" => $statelist, "amount" => $processes]);
1595 * Checks if $array is a filled array with at least one entry.
1597 * @param mixed $array A filled array with at least one entry
1599 * @return boolean Whether $array is a filled array or an object with rows
1601 public static function isResult($array)
1603 // It could be a return value from an update statement
1604 if (is_bool($array)) {
1608 if (is_object($array)) {
1609 return self::numRows($array) > 0;
1612 return (is_array($array) && (count($array) > 0));
1616 * @brief Callback function for "esc_array"
1618 * @param mixed $value Array value
1619 * @param string $key Array key
1620 * @param boolean $add_quotation add quotation marks for string values
1623 private static function escapeArrayCallback(&$value, $key, $add_quotation)
1625 if (!$add_quotation) {
1626 if (is_bool($value)) {
1627 $value = ($value ? '1' : '0');
1629 $value = self::escape($value);
1634 if (is_bool($value)) {
1635 $value = ($value ? 'true' : 'false');
1636 } elseif (is_float($value) || is_integer($value)) {
1637 $value = (string) $value;
1639 $value = "'" . self::escape($value) . "'";
1644 * @brief Escapes a whole array
1646 * @param mixed $arr Array with values to be escaped
1647 * @param boolean $add_quotation add quotation marks for string values
1650 public static function escapeArray(&$arr, $add_quotation = false)
1652 array_walk($arr, 'self::escapeArrayCallback', $add_quotation);