From c316c5ae30fce567819defad9f4ccd6f3c6fa054 Mon Sep 17 00:00:00 2001 From: Hypolite Petovan Date: Thu, 19 Jul 2018 22:06:13 -0400 Subject: [PATCH 1/4] Add new Friendica\Database\dba class --- src/Database/DBA.php | 1522 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1522 insertions(+) create mode 100644 src/Database/DBA.php diff --git a/src/Database/DBA.php b/src/Database/DBA.php new file mode 100644 index 0000000000..28eedec151 --- /dev/null +++ b/src/Database/DBA.php @@ -0,0 +1,1522 @@ +getConfigVariable() instead. +//use Friendica\Core\Config; + +use Friendica\Core\System; +use Friendica\Util\DateTimeFormat; + +/** + * @class MySQL database class + * + * This class is for the low level database stuff that does driver specific things. + */ +class dba +{ + public static $connected = false; + + private static $server_info = ''; + private static $db; + private static $driver; + private static $error = false; + private static $errorno = 0; + private static $affected_rows = 0; + private static $in_transaction = false; + private static $in_retrial = false; + private static $relation = []; + private static $db_serveraddr = ''; + private static $db_user = ''; + private static $db_pass = ''; + private static $db_name = ''; + private static $db_charset = ''; + + public static function connect($serveraddr, $user, $pass, $db, $charset = null) + { + if (!is_null(self::$db) && self::connected()) { + return true; + } + + // We are storing these values for being able to perform a reconnect + self::$db_serveraddr = $serveraddr; + self::$db_user = $user; + self::$db_pass = $pass; + self::$db_name = $db; + self::$db_charset = $charset; + + $serveraddr = trim($serveraddr); + + $serverdata = explode(':', $serveraddr); + $server = $serverdata[0]; + + if (count($serverdata) > 1) { + $port = trim($serverdata[1]); + } + + $server = trim($server); + $user = trim($user); + $pass = trim($pass); + $db = trim($db); + $charset = trim($charset); + + if (!(strlen($server) && strlen($user))) { + return false; + } + + if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) { + self::$driver = 'pdo'; + $connect = "mysql:host=".$server.";dbname=".$db; + + if (isset($port)) { + $connect .= ";port=".$port; + } + + if ($charset) { + $connect .= ";charset=".$charset; + } + + try { + self::$db = @new PDO($connect, $user, $pass); + self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); + self::$connected = true; + } catch (PDOException $e) { + } + } + + if (!self::$connected && class_exists('mysqli')) { + self::$driver = 'mysqli'; + self::$db = @new mysqli($server, $user, $pass, $db, $port); + if (!mysqli_connect_errno()) { + self::$connected = true; + + if ($charset) { + self::$db->set_charset($charset); + } + } + } + + // No suitable SQL driver was found. + if (!self::$connected) { + self::$driver = null; + self::$db = null; + } + + return self::$connected; + } + + /** + * Disconnects the current database connection + */ + public static function disconnect() + { + if (is_null(self::$db)) { + return; + } + + switch (self::$driver) { + case 'pdo': + self::$db = null; + break; + case 'mysqli': + self::$db->close(); + self::$db = null; + break; + } + } + + /** + * Perform a reconnect of an existing database connection + */ + public static function reconnect() { + self::disconnect(); + + $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset); + return $ret; + } + + /** + * Return the database object. + * @return PDO|mysqli + */ + public static function get_db() + { + return self::$db; + } + + /** + * @brief Returns the MySQL server version string + * + * This function discriminate between the deprecated mysql API and the current + * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1 + * + * @return string + */ + public static function server_info() { + if (self::$server_info == '') { + switch (self::$driver) { + case 'pdo': + self::$server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION); + break; + case 'mysqli': + self::$server_info = self::$db->server_info; + break; + } + } + return self::$server_info; + } + + /** + * @brief Returns the selected database name + * + * @return string + */ + public static function database_name() { + $ret = self::p("SELECT DATABASE() AS `db`"); + $data = self::inArray($ret); + return $data[0]['db']; + } + + /** + * @brief Analyze a database query and log this if some conditions are met. + * + * @param string $query The database query that will be analyzed + */ + private static function logIndex($query) { + $a = get_app(); + + if (!$a->getConfigVariable('system', 'db_log_index')) { + return; + } + + // Don't explain an explain statement + if (strtolower(substr($query, 0, 7)) == "explain") { + return; + } + + // Only do the explain on "select", "update" and "delete" + if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) { + return; + } + + $r = self::p("EXPLAIN ".$query); + if (!DBM::is_result($r)) { + return; + } + + $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch')); + $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist')); + + while ($row = self::fetch($r)) { + if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) { + $log = (in_array($row['key'], $watchlist) && + ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index')))); + } else { + $log = false; + } + + if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) { + $log = true; + } + + if (in_array($row['key'], $blacklist) || ($row['key'] == "")) { + $log = false; + } + + if ($log) { + $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t". + $row['key']."\t".$row['rows']."\t".$row['Extra']."\t". + basename($backtrace[1]["file"])."\t". + $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t". + substr($query, 0, 2000)."\n", FILE_APPEND); + } + } + } + + public static function escape($str) { + switch (self::$driver) { + case 'pdo': + return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1); + case 'mysqli': + return @self::$db->real_escape_string($str); + } + } + + public static function connected() { + $connected = false; + + if (is_null(self::$db)) { + return false; + } + + switch (self::$driver) { + case 'pdo': + $r = self::p("SELECT 1"); + if (DBM::is_result($r)) { + $row = self::inArray($r); + $connected = ($row[0]['1'] == '1'); + } + break; + case 'mysqli': + $connected = self::$db->ping(); + break; + } + return $connected; + } + + /** + * @brief Replaces ANY_VALUE() function by MIN() function, + * if the database server does not support ANY_VALUE(). + * + * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5). + * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html + * A standard fall-back is to use MIN(). + * + * @param string $sql An SQL string without the values + * @return string The input SQL string modified if necessary. + */ + public static function any_value_fallback($sql) { + $server_info = self::server_info(); + if (version_compare($server_info, '5.7.5', '<') || + (stripos($server_info, 'MariaDB') !== false)) { + $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql); + } + return $sql; + } + + /** + * @brief beautifies the query - useful for "SHOW PROCESSLIST" + * + * This is safe when we bind the parameters later. + * The parameter values aren't part of the SQL. + * + * @param string $sql An SQL string without the values + * @return string The input SQL string modified if necessary. + */ + public static function clean_query($sql) { + $search = ["\t", "\n", "\r", " "]; + $replace = [' ', ' ', ' ', ' ']; + do { + $oldsql = $sql; + $sql = str_replace($search, $replace, $sql); + } while ($oldsql != $sql); + + return $sql; + } + + + /** + * @brief Replaces the ? placeholders with the parameters in the $args array + * + * @param string $sql SQL query + * @param array $args The parameters that are to replace the ? placeholders + * @return string The replaced SQL query + */ + private static function replaceParameters($sql, $args) { + $offset = 0; + foreach ($args AS $param => $value) { + if (is_int($args[$param]) || is_float($args[$param])) { + $replace = intval($args[$param]); + } else { + $replace = "'".self::escape($args[$param])."'"; + } + + $pos = strpos($sql, '?', $offset); + if ($pos !== false) { + $sql = substr_replace($sql, $replace, $pos, 1); + } + $offset = $pos + strlen($replace); + } + return $sql; + } + + /** + * @brief Convert parameter array to an universal form + * @param array $args Parameter array + * @return array universalized parameter array + */ + private static function getParam($args) { + unset($args[0]); + + // When the second function parameter is an array then use this as the parameter array + if ((count($args) > 0) && (is_array($args[1]))) { + return $args[1]; + } else { + return $args; + } + } + + /** + * @brief Executes a prepared statement that returns data + * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid); + * + * Please only use it with complicated queries. + * For all regular queries please use dba::select or dba::exists + * + * @param string $sql SQL statement + * @return bool|object statement object or result object + */ + public static function p($sql) { + $a = get_app(); + + $stamp1 = microtime(true); + + $params = self::getParam(func_get_args()); + + // Renumber the array keys to be sure that they fit + $i = 0; + $args = []; + foreach ($params AS $param) { + // Avoid problems with some MySQL servers and boolean values. See issue #3645 + if (is_bool($param)) { + $param = (int)$param; + } + $args[++$i] = $param; + } + + if (!self::$connected) { + return false; + } + + if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) { + // Question: Should we continue or stop the query here? + logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG); + } + + $sql = self::clean_query($sql); + $sql = self::any_value_fallback($sql); + + $orig_sql = $sql; + + if ($a->getConfigValue('system', 'db_callstack')) { + $sql = "/*".System::callstack()." */ ".$sql; + } + + self::$error = ''; + self::$errorno = 0; + self::$affected_rows = 0; + + // We have to make some things different if this function is called from "e" + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); + + if (isset($trace[1])) { + $called_from = $trace[1]; + } else { + // We use just something that is defined to avoid warnings + $called_from = $trace[0]; + } + // We are having an own error logging in the function "e" + $called_from_e = ($called_from['function'] == 'e'); + + switch (self::$driver) { + case 'pdo': + // If there are no arguments we use "query" + if (count($args) == 0) { + if (!$retval = self::$db->query($sql)) { + $errorInfo = self::$db->errorInfo(); + self::$error = $errorInfo[2]; + self::$errorno = $errorInfo[1]; + $retval = false; + break; + } + self::$affected_rows = $retval->rowCount(); + break; + } + + if (!$stmt = self::$db->prepare($sql)) { + $errorInfo = self::$db->errorInfo(); + self::$error = $errorInfo[2]; + self::$errorno = $errorInfo[1]; + $retval = false; + break; + } + + foreach ($args AS $param => $value) { + if (is_int($args[$param])) { + $data_type = PDO::PARAM_INT; + } else { + $data_type = PDO::PARAM_STR; + } + $stmt->bindParam($param, $args[$param], $data_type); + } + + if (!$stmt->execute()) { + $errorInfo = $stmt->errorInfo(); + self::$error = $errorInfo[2]; + self::$errorno = $errorInfo[1]; + $retval = false; + } else { + $retval = $stmt; + self::$affected_rows = $retval->rowCount(); + } + break; + case 'mysqli': + // There are SQL statements that cannot be executed with a prepared statement + $parts = explode(' ', $orig_sql); + $command = strtolower($parts[0]); + $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']); + + // The fallback routine is called as well when there are no arguments + if (!$can_be_prepared || (count($args) == 0)) { + $retval = self::$db->query(self::replaceParameters($sql, $args)); + if (self::$db->errno) { + self::$error = self::$db->error; + self::$errorno = self::$db->errno; + $retval = false; + } else { + if (isset($retval->num_rows)) { + self::$affected_rows = $retval->num_rows; + } else { + self::$affected_rows = self::$db->affected_rows; + } + } + break; + } + + $stmt = self::$db->stmt_init(); + + if (!$stmt->prepare($sql)) { + self::$error = $stmt->error; + self::$errorno = $stmt->errno; + $retval = false; + break; + } + + $param_types = ''; + $values = []; + foreach ($args AS $param => $value) { + if (is_int($args[$param])) { + $param_types .= 'i'; + } elseif (is_float($args[$param])) { + $param_types .= 'd'; + } elseif (is_string($args[$param])) { + $param_types .= 's'; + } else { + $param_types .= 'b'; + } + $values[] = &$args[$param]; + } + + if (count($values) > 0) { + array_unshift($values, $param_types); + call_user_func_array([$stmt, 'bind_param'], $values); + } + + if (!$stmt->execute()) { + self::$error = self::$db->error; + self::$errorno = self::$db->errno; + $retval = false; + } else { + $stmt->store_result(); + $retval = $stmt; + self::$affected_rows = $retval->affected_rows; + } + break; + } + + // We are having an own error logging in the function "e" + if ((self::$errorno != 0) && !$called_from_e) { + // We have to preserve the error code, somewhere in the logging it get lost + $error = self::$error; + $errorno = self::$errorno; + + logger('DB Error '.self::$errorno.': '.self::$error."\n". + System::callstack(8)."\n".self::replaceParameters($sql, $args)); + + // On a lost connection we try to reconnect - but only once. + if ($errorno == 2006) { + if (self::$in_retrial || !self::reconnect()) { + // It doesn't make sense to continue when the database connection was lost + if (self::$in_retrial) { + logger('Giving up retrial because of database error '.$errorno.': '.$error); + } else { + logger("Couldn't reconnect after database error ".$errorno.': '.$error); + } + exit(1); + } else { + // We try it again + logger('Reconnected after database error '.$errorno.': '.$error); + self::$in_retrial = true; + $ret = self::p($sql, $args); + self::$in_retrial = false; + return $ret; + } + } + + self::$error = $error; + self::$errorno = $errorno; + } + + $a->save_timestamp($stamp1, 'database'); + + if ($a->getConfigValue('system', 'db_log')) { + $stamp2 = microtime(true); + $duration = (float)($stamp2 - $stamp1); + + if (($duration > $a->getConfigValue('system', 'db_loglimit'))) { + $duration = round($duration, 3); + $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + + @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t". + basename($backtrace[1]["file"])."\t". + $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t". + substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND); + } + } + return $retval; + } + + /** + * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data + * + * Please use dba::delete, dba::insert, dba::update, ... instead + * + * @param string $sql SQL statement + * @return boolean Was the query successfull? False is returned only if an error occurred + */ + public static function e($sql) { + $a = get_app(); + + $stamp = microtime(true); + + $params = self::getParam(func_get_args()); + + // In a case of a deadlock we are repeating the query 20 times + $timeout = 20; + + do { + $stmt = self::p($sql, $params); + + if (is_bool($stmt)) { + $retval = $stmt; + } elseif (is_object($stmt)) { + $retval = true; + } else { + $retval = false; + } + + self::close($stmt); + + } while ((self::$errorno == 1213) && (--$timeout > 0)); + + if (self::$errorno != 0) { + // We have to preserve the error code, somewhere in the logging it get lost + $error = self::$error; + $errorno = self::$errorno; + + logger('DB Error '.self::$errorno.': '.self::$error."\n". + System::callstack(8)."\n".self::replaceParameters($sql, $params)); + + // On a lost connection we simply quit. + // A reconnect like in self::p could be dangerous with modifications + if ($errorno == 2006) { + logger('Giving up because of database error '.$errorno.': '.$error); + exit(1); + } + + self::$error = $error; + self::$errorno = $errorno; + } + + $a->save_timestamp($stamp, "database_write"); + + return $retval; + } + + /** + * @brief Check if data exists + * + * @param string $table Table name + * @param array $condition array of fields for condition + * + * @return boolean Are there rows for that condition? + */ + public static function exists($table, $condition) { + if (empty($table)) { + return false; + } + + $fields = []; + + reset($condition); + $first_key = key($condition); + if (!is_int($first_key)) { + $fields = [$first_key]; + } + + $stmt = self::select($table, $fields, $condition, ['limit' => 1]); + + if (is_bool($stmt)) { + $retval = $stmt; + } else { + $retval = (self::num_rows($stmt) > 0); + } + + self::close($stmt); + + return $retval; + } + + /** + * Fetches the first row + * + * Please use dba::selectFirst or dba::exists whenever this is possible. + * + * @brief Fetches the first row + * @param string $sql SQL statement + * @return array first row of query + */ + public static function fetch_first($sql) { + $params = self::getParam(func_get_args()); + + $stmt = self::p($sql, $params); + + if (is_bool($stmt)) { + $retval = $stmt; + } else { + $retval = self::fetch($stmt); + } + + self::close($stmt); + + return $retval; + } + + /** + * @brief Returns the number of affected rows of the last statement + * + * @return int Number of rows + */ + public static function affected_rows() { + return self::$affected_rows; + } + + /** + * @brief Returns the number of columns of a statement + * + * @param object Statement object + * @return int Number of columns + */ + public static function columnCount($stmt) { + if (!is_object($stmt)) { + return 0; + } + switch (self::$driver) { + case 'pdo': + return $stmt->columnCount(); + case 'mysqli': + return $stmt->field_count; + } + return 0; + } + /** + * @brief Returns the number of rows of a statement + * + * @param PDOStatement|mysqli_result|mysqli_stmt Statement object + * @return int Number of rows + */ + public static function num_rows($stmt) { + if (!is_object($stmt)) { + return 0; + } + switch (self::$driver) { + case 'pdo': + return $stmt->rowCount(); + case 'mysqli': + return $stmt->num_rows; + } + return 0; + } + + /** + * @brief Fetch a single row + * + * @param mixed $stmt statement object + * @return array current row + */ + public static function fetch($stmt) { + $a = get_app(); + + $stamp1 = microtime(true); + + $columns = []; + + if (!is_object($stmt)) { + return false; + } + + switch (self::$driver) { + case 'pdo': + $columns = $stmt->fetch(PDO::FETCH_ASSOC); + break; + case 'mysqli': + if (get_class($stmt) == 'mysqli_result') { + $columns = $stmt->fetch_assoc(); + break; + } + + // This code works, but is slow + + // Bind the result to a result array + $cols = []; + + $cols_num = []; + for ($x = 0; $x < $stmt->field_count; $x++) { + $cols[] = &$cols_num[$x]; + } + + call_user_func_array([$stmt, 'bind_result'], $cols); + + if (!$stmt->fetch()) { + return false; + } + + // The slow part: + // We need to get the field names for the array keys + // It seems that there is no better way to do this. + $result = $stmt->result_metadata(); + $fields = $result->fetch_fields(); + + foreach ($cols_num AS $param => $col) { + $columns[$fields[$param]->name] = $col; + } + } + + $a->save_timestamp($stamp1, 'database'); + + return $columns; + } + + /** + * @brief Insert a row into a table + * + * @param string $table Table name + * @param array $param parameter array + * @param bool $on_duplicate_update Do an update on a duplicate entry + * + * @return boolean was the insert successfull? + */ + public static function insert($table, $param, $on_duplicate_update = false) { + + if (empty($table) || empty($param)) { + logger('Table and fields have to be set'); + return false; + } + + $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (". + substr(str_repeat("?, ", count($param)), 0, -2).")"; + + if ($on_duplicate_update) { + $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?"; + + $values = array_values($param); + $param = array_merge_recursive($values, $values); + } + + return self::e($sql, $param); + } + + /** + * @brief Fetch the id of the last insert command + * + * @return integer Last inserted id + */ + public static function lastInsertId() { + switch (self::$driver) { + case 'pdo': + $id = self::$db->lastInsertId(); + break; + case 'mysqli': + $id = self::$db->insert_id; + break; + } + return $id; + } + + /** + * @brief Locks a table for exclusive write access + * + * This function can be extended in the future to accept a table array as well. + * + * @param string $table Table name + * + * @return boolean was the lock successful? + */ + public static function lock($table) { + // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html + if (self::$driver == 'pdo') { + self::e("SET autocommit=0"); + self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); + } else { + self::$db->autocommit(false); + } + + $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE"); + + if (self::$driver == 'pdo') { + self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); + } + + if (!$success) { + if (self::$driver == 'pdo') { + self::e("SET autocommit=1"); + } else { + self::$db->autocommit(true); + } + } else { + self::$in_transaction = true; + } + return $success; + } + + /** + * @brief Unlocks all locked tables + * + * @return boolean was the unlock successful? + */ + public static function unlock() { + // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html + self::performCommit(); + + if (self::$driver == 'pdo') { + self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); + } + + $success = self::e("UNLOCK TABLES"); + + if (self::$driver == 'pdo') { + self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); + self::e("SET autocommit=1"); + } else { + self::$db->autocommit(true); + } + + self::$in_transaction = false; + return $success; + } + + /** + * @brief Starts a transaction + * + * @return boolean Was the command executed successfully? + */ + public static function transaction() { + if (!self::performCommit()) { + return false; + } + + switch (self::$driver) { + case 'pdo': + if (self::$db->inTransaction()) { + break; + } + if (!self::$db->beginTransaction()) { + return false; + } + break; + case 'mysqli': + if (!self::$db->begin_transaction()) { + return false; + } + break; + } + + self::$in_transaction = true; + return true; + } + + private static function performCommit() + { + switch (self::$driver) { + case 'pdo': + if (!self::$db->inTransaction()) { + return true; + } + return self::$db->commit(); + case 'mysqli': + return self::$db->commit(); + } + return true; + } + + /** + * @brief Does a commit + * + * @return boolean Was the command executed successfully? + */ + public static function commit() { + if (!self::performCommit()) { + return false; + } + self::$in_transaction = false; + return true; + } + + /** + * @brief Does a rollback + * + * @return boolean Was the command executed successfully? + */ + public static function rollback() { + $ret = false; + + switch (self::$driver) { + case 'pdo': + if (!self::$db->inTransaction()) { + $ret = true; + break; + } + $ret = self::$db->rollBack(); + break; + case 'mysqli': + $ret = self::$db->rollback(); + break; + } + self::$in_transaction = false; + return $ret; + } + + /** + * @brief Build the array with the table relations + * + * The array is build from the database definitions in DBStructure.php + * + * This process must only be started once, since the value is cached. + */ + private static function buildRelationData() { + $definition = DBStructure::definition(); + + foreach ($definition AS $table => $structure) { + foreach ($structure['fields'] AS $field => $field_struct) { + if (isset($field_struct['relation'])) { + foreach ($field_struct['relation'] AS $rel_table => $rel_field) { + self::$relation[$rel_table][$rel_field][$table][] = $field; + } + } + } + } + } + + /** + * @brief Delete a row from a table + * + * @param string $table Table name + * @param array $conditions Field condition(s) + * @param array $options + * - cascade: If true we delete records in other tables that depend on the one we're deleting through + * relations (default: true) + * @param boolean $in_process Internal use: Only do a commit after the last delete + * @param array $callstack Internal use: prevent endless loops + * + * @return boolean|array was the delete successful? When $in_process is set: deletion data + */ + public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = []) + { + if (empty($table) || empty($conditions)) { + logger('Table and conditions have to be set'); + return false; + } + + $commands = []; + + // Create a key for the loop prevention + $key = $table . ':' . json_encode($conditions); + + // We quit when this key already exists in the callstack. + if (isset($callstack[$key])) { + return $commands; + } + + $callstack[$key] = true; + + $table = self::escape($table); + + $commands[$key] = ['table' => $table, 'conditions' => $conditions]; + + $cascade = defaults($options, 'cascade', true); + + // To speed up the whole process we cache the table relations + if ($cascade && count(self::$relation) == 0) { + self::buildRelationData(); + } + + // Is there a relation entry for the table? + if ($cascade && isset(self::$relation[$table])) { + // We only allow a simple "one field" relation. + $field = array_keys(self::$relation[$table])[0]; + $rel_def = array_values(self::$relation[$table])[0]; + + // Create a key for preventing double queries + $qkey = $field . '-' . $table . ':' . json_encode($conditions); + + // When the search field is the relation field, we don't need to fetch the rows + // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend + if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) { + foreach ($rel_def AS $rel_table => $rel_fields) { + foreach ($rel_fields AS $rel_field) { + $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack); + $commands = array_merge($commands, $retval); + } + } + // We quit when this key already exists in the callstack. + } elseif (!isset($callstack[$qkey])) { + + $callstack[$qkey] = true; + + // Fetch all rows that are to be deleted + $data = self::select($table, [$field], $conditions); + + while ($row = self::fetch($data)) { + // Now we accumulate the delete commands + $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack); + $commands = array_merge($commands, $retval); + } + + self::close($data); + + // Since we had split the delete command we don't need the original command anymore + unset($commands[$key]); + } + } + + if (!$in_process) { + // Now we finalize the process + $do_transaction = !self::$in_transaction; + + if ($do_transaction) { + self::transaction(); + } + + $compacted = []; + $counter = []; + + foreach ($commands AS $command) { + $conditions = $command['conditions']; + reset($conditions); + $first_key = key($conditions); + + $condition_string = self::buildCondition($conditions); + + if ((count($command['conditions']) > 1) || is_int($first_key)) { + $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string; + logger(self::replaceParameters($sql, $conditions), LOGGER_DATA); + + if (!self::e($sql, $conditions)) { + if ($do_transaction) { + self::rollback(); + } + return false; + } + } else { + $key_table = $command['table']; + $key_condition = array_keys($command['conditions'])[0]; + $value = array_values($command['conditions'])[0]; + + // Split the SQL queries in chunks of 100 values + // We do the $i stuff here to make the code better readable + $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0; + if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) { + ++$i; + } + + $compacted[$key_table][$key_condition][$i][$value] = $value; + $counter[$key_table][$key_condition] = $i; + } + } + foreach ($compacted AS $table => $values) { + foreach ($values AS $field => $field_value_list) { + foreach ($field_value_list AS $field_values) { + $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" . + substr(str_repeat("?, ", count($field_values)), 0, -2) . ");"; + + logger(self::replaceParameters($sql, $field_values), LOGGER_DATA); + + if (!self::e($sql, $field_values)) { + if ($do_transaction) { + self::rollback(); + } + return false; + } + } + } + } + if ($do_transaction) { + self::commit(); + } + return true; + } + + return $commands; + } + + /** + * @brief Updates rows + * + * Updates rows in the database. When $old_fields is set to an array, + * the system will only do an update if the fields in that array changed. + * + * Attention: + * Only the values in $old_fields are compared. + * This is an intentional behaviour. + * + * Example: + * We include the timestamp field in $fields but not in $old_fields. + * Then the row will only get the new timestamp when the other fields had changed. + * + * When $old_fields is set to a boolean value the system will do this compare itself. + * When $old_fields is set to "true" the system will do an insert if the row doesn't exists. + * + * Attention: + * Only set $old_fields to a boolean value when you are sure that you will update a single row. + * When you set $old_fields to "true" then $fields must contain all relevant fields! + * + * @param string $table Table name + * @param array $fields contains the fields that are updated + * @param array $condition condition array with the key values + * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate) + * + * @return boolean was the update successfull? + */ + public static function update($table, $fields, $condition, $old_fields = []) { + + if (empty($table) || empty($fields) || empty($condition)) { + logger('Table, fields and condition have to be set'); + return false; + } + + $table = self::escape($table); + + $condition_string = self::buildCondition($condition); + + if (is_bool($old_fields)) { + $do_insert = $old_fields; + + $old_fields = self::selectFirst($table, [], $condition); + + if (is_bool($old_fields)) { + if ($do_insert) { + $values = array_merge($condition, $fields); + return self::insert($table, $values, $do_insert); + } + $old_fields = []; + } + } + + $do_update = (count($old_fields) == 0); + + foreach ($old_fields AS $fieldname => $content) { + if (isset($fields[$fieldname])) { + if ($fields[$fieldname] == $content) { + unset($fields[$fieldname]); + } else { + $do_update = true; + } + } + } + + if (!$do_update || (count($fields) == 0)) { + return true; + } + + $sql = "UPDATE `".$table."` SET `". + implode("` = ?, `", array_keys($fields))."` = ?".$condition_string; + + $params1 = array_values($fields); + $params2 = array_values($condition); + $params = array_merge_recursive($params1, $params2); + + return self::e($sql, $params); + } + + /** + * Retrieve a single record from a table and returns it in an associative array + * + * @brief Retrieve a single record from a table + * @param string $table + * @param array $fields + * @param array $condition + * @param array $params + * @return bool|array + * @see self::select + */ + public static function selectFirst($table, array $fields = [], array $condition = [], $params = []) + { + $params['limit'] = 1; + $result = self::select($table, $fields, $condition, $params); + + if (is_bool($result)) { + return $result; + } else { + $row = self::fetch($result); + self::close($result); + return $row; + } + } + + /** + * @brief Select rows from a table + * + * @param string $table Table name + * @param array $fields Array of selected fields, empty for all + * @param array $condition Array of fields for condition + * @param array $params Array of several parameters + * + * @return boolean|object + * + * Example: + * $table = "item"; + * $fields = array("id", "uri", "uid", "network"); + * + * $condition = array("uid" => 1, "network" => 'dspr'); + * or: + * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'); + * + * $params = array("order" => array("id", "received" => true), "limit" => 10); + * + * $data = dba::select($table, $fields, $condition, $params); + */ + public static function select($table, array $fields = [], array $condition = [], array $params = []) + { + if ($table == '') { + return false; + } + + $table = self::escape($table); + + if (count($fields) > 0) { + $select_fields = "`" . implode("`, `", array_values($fields)) . "`"; + } else { + $select_fields = "*"; + } + + $condition_string = self::buildCondition($condition); + + $param_string = self::buildParameter($params); + + $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string; + + $result = self::p($sql, $condition); + + return $result; + } + + /** + * @brief Counts the rows from a table satisfying the provided condition + * + * @param string $table Table name + * @param array $condition array of fields for condition + * + * @return int + * + * Example: + * $table = "item"; + * + * $condition = ["uid" => 1, "network" => 'dspr']; + * or: + * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr']; + * + * $count = dba::count($table, $condition); + */ + public static function count($table, array $condition = []) + { + if ($table == '') { + return false; + } + + $condition_string = self::buildCondition($condition); + + $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string; + + $row = self::fetch_first($sql, $condition); + + return $row['count']; + } + + /** + * @brief Returns the SQL condition string built from the provided condition array + * + * This function operates with two modes. + * - Supplied with a filed/value associative array, it builds simple strict + * equality conditions linked by AND. + * - Supplied with a flat list, the first element is the condition string and + * the following arguments are the values to be interpolated + * + * $condition = ["uid" => 1, "network" => 'dspr']; + * or: + * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr']; + * + * In either case, the provided array is left with the parameters only + * + * @param array $condition + * @return string + */ + public static function buildCondition(array &$condition = []) + { + $condition_string = ''; + if (count($condition) > 0) { + reset($condition); + $first_key = key($condition); + if (is_int($first_key)) { + $condition_string = " WHERE (" . array_shift($condition) . ")"; + } else { + $new_values = []; + $condition_string = ""; + foreach ($condition as $field => $value) { + if ($condition_string != "") { + $condition_string .= " AND "; + } + if (is_array($value)) { + /* Workaround for MySQL Bug #64791. + * Never mix data types inside any IN() condition. + * In case of mixed types, cast all as string. + * Logic needs to be consistent with dba::p() data types. + */ + $is_int = false; + $is_alpha = false; + foreach ($value as $single_value) { + if (is_int($single_value)) { + $is_int = true; + } else { + $is_alpha = true; + } + } + + if ($is_int && $is_alpha) { + foreach ($value as &$ref) { + if (is_int($ref)) { + $ref = (string)$ref; + } + } + unset($ref); //Prevent accidental re-use. + } + + $new_values = array_merge($new_values, array_values($value)); + $placeholders = substr(str_repeat("?, ", count($value)), 0, -2); + $condition_string .= "`" . $field . "` IN (" . $placeholders . ")"; + } else { + $new_values[$field] = $value; + $condition_string .= "`" . $field . "` = ?"; + } + } + $condition_string = " WHERE (" . $condition_string . ")"; + $condition = $new_values; + } + } + + return $condition_string; + } + + /** + * @brief Returns the SQL parameter string built from the provided parameter array + * + * @param array $params + * @return string + */ + public static function buildParameter(array $params = []) + { + $order_string = ''; + if (isset($params['order'])) { + $order_string = " ORDER BY "; + foreach ($params['order'] AS $fields => $order) { + if (!is_int($fields)) { + $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", "; + } else { + $order_string .= "`" . $order . "`, "; + } + } + $order_string = substr($order_string, 0, -2); + } + + $limit_string = ''; + if (isset($params['limit']) && is_int($params['limit'])) { + $limit_string = " LIMIT " . $params['limit']; + } + + if (isset($params['limit']) && is_array($params['limit'])) { + $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]); + } + + return $order_string.$limit_string; + } + + /** + * @brief Fills an array with data from a query + * + * @param object $stmt statement object + * @return array Data array + */ + public static function inArray($stmt, $do_close = true) { + if (is_bool($stmt)) { + return $stmt; + } + + $data = []; + while ($row = self::fetch($stmt)) { + $data[] = $row; + } + if ($do_close) { + self::close($stmt); + } + return $data; + } + + /** + * @brief Returns the error number of the last query + * + * @return string Error number (0 if no error) + */ + public static function errorNo() { + return self::$errorno; + } + + /** + * @brief Returns the error message of the last query + * + * @return string Error message ('' if no error) + */ + public static function errorMessage() { + return self::$error; + } + + /** + * @brief Closes the current statement + * + * @param object $stmt statement object + * @return boolean was the close successful? + */ + public static function close($stmt) { + $a = get_app(); + + $stamp1 = microtime(true); + + if (!is_object($stmt)) { + return false; + } + + switch (self::$driver) { + case 'pdo': + $ret = $stmt->closeCursor(); + break; + case 'mysqli': + // MySQLi offers both a mysqli_stmt and a mysqli_result class. + // We should be careful not to assume the object type of $stmt + // because dba::p() has been able to return both types. + if ($stmt instanceof mysqli_stmt) { + $stmt->free_result(); + $ret = $stmt->close(); + } elseif ($stmt instanceof mysqli_result) { + $stmt->free(); + $ret = true; + } else { + $ret = false; + } + break; + } + + $a->save_timestamp($stamp1, 'database'); + + return $ret; + } +} From daa1177e3a1e42b4c95e0a8759f1610942b952c7 Mon Sep 17 00:00:00 2001 From: Hypolite Petovan Date: Thu, 19 Jul 2018 22:15:21 -0400 Subject: [PATCH 2/4] Update use statement lists with new Friendica\Database\dba class - Remove unused use statement - Remove superfluous use statements (classes in the same namespace) - Add missing use statements --- bin/daemon.php | 1 + include/api.php | 1 + include/conversation.php | 6 ++++-- include/enotify.php | 5 +++-- include/items.php | 1 + include/security.php | 1 + index.php | 1 + mod/acl.php | 1 + mod/admin.php | 3 ++- mod/allfriends.php | 2 ++ mod/attach.php | 2 ++ mod/cal.php | 1 + mod/common.php | 2 ++ mod/community.php | 1 + mod/contacts.php | 1 + mod/crepair.php | 2 ++ mod/delegate.php | 2 ++ mod/dfrn_confirm.php | 4 +--- mod/dfrn_notify.php | 1 + mod/dfrn_poll.php | 2 ++ mod/dfrn_request.php | 2 +- mod/directory.php | 2 ++ mod/dirfind.php | 4 +++- mod/display.php | 1 + mod/feedtest.php | 1 + mod/hovercard.php | 3 ++- mod/install.php | 3 ++- mod/item.php | 4 +++- mod/lostpass.php | 2 ++ mod/message.php | 1 + mod/network.php | 1 + mod/nodeinfo.php | 3 ++- mod/noscrape.php | 2 ++ mod/notes.php | 4 +++- mod/notifications.php | 2 ++ mod/photos.php | 1 + mod/profile.php | 1 + mod/profiles.php | 2 +- mod/proxy.php | 1 + mod/pubsub.php | 1 + mod/pubsubhubbub.php | 3 ++- mod/receive.php | 1 + mod/redir.php | 1 + mod/regmod.php | 1 + mod/removeme.php | 1 + mod/search.php | 2 ++ mod/settings.php | 1 + mod/suggest.php | 3 ++- mod/unfollow.php | 2 ++ mod/wall_attach.php | 1 + mod/worker.php | 1 + mod/xrd.php | 2 ++ src/App.php | 16 +++++++-------- src/Content/ContactSelector.php | 3 +-- src/Content/ForumManager.php | 5 ++--- src/Content/Nav.php | 2 +- src/Content/OEmbed.php | 20 +++++++++---------- src/Content/Widget.php | 2 +- src/Content/Widget/TagCloud.php | 2 +- src/Core/ACL.php | 16 +-------------- src/Core/Addon.php | 10 ++++------ src/Core/Cache/DatabaseCacheDriver.php | 2 +- src/Core/Config/JITConfigAdapter.php | 2 +- src/Core/Config/JITPConfigAdapter.php | 2 +- src/Core/Config/PreloadConfigAdapter.php | 3 +-- src/Core/Config/PreloadPConfigAdapter.php | 3 +-- src/Core/Console/ArchiveContact.php | 10 ++++++---- src/Core/Console/AutomaticInstallation.php | 2 +- src/Core/Console/Config.php | 9 +++++---- src/Core/Console/DatabaseStructure.php | 6 ++++-- src/Core/Console/GlobalCommunitySilence.php | 12 ++++++----- src/Core/Console/NewPassword.php | 18 ++++++++--------- src/Core/L10n.php | 6 +++--- src/Core/Lock/DatabaseLockDriver.php | 2 +- src/Core/NotificationsManager.php | 5 ----- src/Core/Session/DatabaseSessionHandler.php | 2 +- src/Core/UserImport.php | 7 +------ src/Core/Worker.php | 2 +- src/Database/DBM.php | 1 - src/Database/DBStructure.php | 7 ++++--- src/Database/PostUpdate.php | 2 -- src/Model/Contact.php | 7 ++----- src/Model/Conversation.php | 2 +- src/Model/Event.php | 3 +-- src/Model/GContact.php | 8 +++----- src/Model/Group.php | 2 +- src/Model/Item.php | 8 +++----- src/Model/Mail.php | 2 +- src/Model/OpenWebAuthToken.php | 12 +++++------ src/Model/PermissionSet.php | 2 +- src/Model/Photo.php | 2 +- src/Model/Process.php | 2 +- src/Model/Profile.php | 6 +----- src/Model/PushSubscriber.php | 4 ++-- src/Model/Queue.php | 2 +- src/Model/Term.php | 3 +-- src/Model/User.php | 7 ++----- src/Module/Hashtag.php | 2 +- src/Module/Login.php | 4 ++-- src/Module/Magic.php | 3 +-- src/Module/Owa.php | 7 +++---- src/Network/FKOAuth1.php | 3 +-- src/Network/FKOAuthDataStore.php | 2 +- src/Network/Probe.php | 10 ++++------ src/Object/Post.php | 2 +- src/Protocol/DFRN.php | 9 +++------ src/Protocol/Diaspora.php | 6 +++--- src/Protocol/Feed.php | 14 ++++++------- src/Protocol/OStatus.php | 2 +- src/Protocol/PortableContact.php | 9 ++++----- src/Util/ExAuth.php | 3 +-- src/Util/HTTPSignature.php | 20 +++++++++---------- src/Util/ParseUrl.php | 9 +++------ src/Worker/Cron.php | 5 +++-- src/Worker/CronJobs.php | 5 +++-- src/Worker/DBClean.php | 2 +- src/Worker/Delivery.php | 2 +- src/Worker/DiscoverPoCo.php | 2 +- src/Worker/Expire.php | 5 +++-- src/Worker/Notifier.php | 8 ++++---- src/Worker/OnePoll.php | 5 +++-- src/Worker/PubSubPublish.php | 8 ++++---- src/Worker/Queue.php | 4 ++-- src/Worker/RemoveContact.php | 3 +-- src/Worker/TagUpdate.php | 2 +- tests/DatabaseTest.php | 5 ++--- .../src/Core/Lock/DatabaseLockDriverTest.php | 6 +----- update.php | 3 ++- 128 files changed, 262 insertions(+), 259 deletions(-) diff --git a/bin/daemon.php b/bin/daemon.php index 65ae2a53b6..6ab2f76102 100755 --- a/bin/daemon.php +++ b/bin/daemon.php @@ -10,6 +10,7 @@ use Friendica\App; use Friendica\Core\Config; use Friendica\Core\Worker; +use Friendica\Database\dba; // Ensure that daemon.php is executed from the base path of the installation if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) { diff --git a/include/api.php b/include/api.php index b67c5a5650..a6196852bf 100644 --- a/include/api.php +++ b/include/api.php @@ -19,6 +19,7 @@ use Friendica\Core\PConfig; use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Group; diff --git a/include/conversation.php b/include/conversation.php index 54716cd687..9b37e32687 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -12,10 +12,12 @@ use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; -use Friendica\Model\Profile; use Friendica\Model\Item; +use Friendica\Model\Profile; +use Friendica\Model\Term; use Friendica\Object\Post; use Friendica\Object\Thread; use Friendica\Util\DateTimeFormat; @@ -578,7 +580,7 @@ function conversation(App $a, array $items, $mode, $update, $preview = false, $o $profile_name = $item['author-link']; } - $tags = \Friendica\Model\Term::populateTagsFromItem($item); + $tags = Term::populateTagsFromItem($item); $author = ['uid' => 0, 'id' => $item['author-id'], 'network' => $item['author-network'], 'url' => $item['author-link']]; diff --git a/include/enotify.php b/include/enotify.php index 2d4cbdadb5..30ebe5d1ac 100644 --- a/include/enotify.php +++ b/include/enotify.php @@ -8,10 +8,11 @@ use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; +use Friendica\Model\Item; use Friendica\Util\DateTimeFormat; use Friendica\Util\Emailer; -use Friendica\Model\Item; /** * @brief Creates a notification entry and possibly sends a mail @@ -679,7 +680,7 @@ function check_user_notification($itemid) { * * @param int $itemid ID of the item for which the check should be done * @param int $uid User ID - * @param str $defaulttype (Optional) Forces a notification with this type. + * @param string $defaulttype (Optional) Forces a notification with this type. */ function check_item_notification($itemid, $uid, $defaulttype = "") { $notification_data = ["uid" => $uid, "profiles" => []]; diff --git a/include/items.php b/include/items.php index e06df925e3..14a74c8e51 100644 --- a/include/items.php +++ b/include/items.php @@ -9,6 +9,7 @@ use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Item; use Friendica\Protocol\DFRN; diff --git a/include/security.php b/include/security.php index 768d7c82d4..64f32bd55e 100644 --- a/include/security.php +++ b/include/security.php @@ -8,6 +8,7 @@ use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Group; use Friendica\Util\DateTimeFormat; diff --git a/index.php b/index.php index a8098942c2..8cdef23ccb 100644 --- a/index.php +++ b/index.php @@ -17,6 +17,7 @@ use Friendica\Core\Session; use Friendica\Core\System; use Friendica\Core\Theme; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Profile; use Friendica\Module\Login; diff --git a/mod/acl.php b/mod/acl.php index dd5dd90281..32b86d90bb 100644 --- a/mod/acl.php +++ b/mod/acl.php @@ -6,6 +6,7 @@ use Friendica\App; use Friendica\Content\Widget; use Friendica\Core\ACL; use Friendica\Core\Addon; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Item; diff --git a/mod/admin.php b/mod/admin.php index 9fa54bc137..9a289dda5a 100644 --- a/mod/admin.php +++ b/mod/admin.php @@ -14,6 +14,7 @@ use Friendica\Core\L10n; use Friendica\Core\System; use Friendica\Core\Theme; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Database\DBStructure; use Friendica\Model\Contact; @@ -782,7 +783,7 @@ function admin_page_workerqueue(App $a) // get jobs from the workerqueue table $statement = dba::select('workerqueue', ['id', 'parameter', 'created', 'priority'], ['done' => 0], ['order'=> ['priority']]); $r = dba::inArray($statement); - + for($i = 0; $i < count($r); $i++) { $r[$i]['parameter'] = stripslashes(implode(': ', explode('","', $r[$i]['parameter']))); $r[$i]['parameter'] = substr($r[$i]['parameter'], 2, -2); diff --git a/mod/allfriends.php b/mod/allfriends.php index d85d3ec9b3..e9d964847c 100644 --- a/mod/allfriends.php +++ b/mod/allfriends.php @@ -2,10 +2,12 @@ /** * @file mod/allfriends.php */ + use Friendica\App; use Friendica\Content\ContactSelector; use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\GContact; diff --git a/mod/attach.php b/mod/attach.php index fd428286a6..0b88fe28fc 100644 --- a/mod/attach.php +++ b/mod/attach.php @@ -2,8 +2,10 @@ /** * @file mod/attach.php */ + use Friendica\App; use Friendica\Core\L10n; +use Friendica\Database\dba; use Friendica\Database\DBM; require_once 'include/dba.php'; diff --git a/mod/cal.php b/mod/cal.php index bf73408f42..246d8a6447 100644 --- a/mod/cal.php +++ b/mod/cal.php @@ -13,6 +13,7 @@ use Friendica\Content\Widget; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Event; diff --git a/mod/common.php b/mod/common.php index f45bbb0175..f6f826789b 100644 --- a/mod/common.php +++ b/mod/common.php @@ -2,9 +2,11 @@ /** * @file include/common.php */ + use Friendica\App; use Friendica\Content\ContactSelector; use Friendica\Core\L10n; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\GContact; diff --git a/mod/community.php b/mod/community.php index 1e6162fb8e..97ecf00831 100644 --- a/mod/community.php +++ b/mod/community.php @@ -9,6 +9,7 @@ use Friendica\Core\ACL; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\PConfig; +use Friendica\Database\dba; use Friendica\Database\DBM; function community_init(App $a) diff --git a/mod/contacts.php b/mod/contacts.php index a4caafe8f9..736d16dfb9 100644 --- a/mod/contacts.php +++ b/mod/contacts.php @@ -12,6 +12,7 @@ use Friendica\Core\Addon; use Friendica\Core\L10n; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\GContact; diff --git a/mod/crepair.php b/mod/crepair.php index 29b00b4e3a..e23e082240 100644 --- a/mod/crepair.php +++ b/mod/crepair.php @@ -2,9 +2,11 @@ /** * @file mod/crepair.php */ + use Friendica\App; use Friendica\Core\Config; use Friendica\Core\L10n; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Profile; diff --git a/mod/delegate.php b/mod/delegate.php index 510fc0ec8f..60cf130464 100644 --- a/mod/delegate.php +++ b/mod/delegate.php @@ -2,9 +2,11 @@ /** * @file mod/delegate.php */ + use Friendica\App; use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\User; diff --git a/mod/dfrn_confirm.php b/mod/dfrn_confirm.php index 0bcf137857..32a9d59f9e 100644 --- a/mod/dfrn_confirm.php +++ b/mod/dfrn_confirm.php @@ -20,13 +20,11 @@ use Friendica\App; use Friendica\Core\Config; use Friendica\Core\L10n; -use Friendica\Core\PConfig; use Friendica\Core\System; -use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Group; -use Friendica\Model\Item; use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Protocol\Diaspora; diff --git a/mod/dfrn_notify.php b/mod/dfrn_notify.php index bfbf4c657a..e356996572 100644 --- a/mod/dfrn_notify.php +++ b/mod/dfrn_notify.php @@ -9,6 +9,7 @@ use Friendica\App; use Friendica\Core\Config; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Protocol\DFRN; diff --git a/mod/dfrn_poll.php b/mod/dfrn_poll.php index d6bc1727e7..32a8013c31 100644 --- a/mod/dfrn_poll.php +++ b/mod/dfrn_poll.php @@ -3,10 +3,12 @@ /** * @file mod/dfrn_poll.php */ + use Friendica\App; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Module\Login; use Friendica\Protocol\DFRN; diff --git a/mod/dfrn_request.php b/mod/dfrn_request.php index b7a0dd7487..8713785ad4 100644 --- a/mod/dfrn_request.php +++ b/mod/dfrn_request.php @@ -15,8 +15,8 @@ use Friendica\App; use Friendica\Core\Config; use Friendica\Core\L10n; -use Friendica\Core\PConfig; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Group; diff --git a/mod/directory.php b/mod/directory.php index a83b1b76ce..85bcbf8130 100644 --- a/mod/directory.php +++ b/mod/directory.php @@ -2,12 +2,14 @@ /** * @file mod/directory.php */ + use Friendica\App; use Friendica\Content\Nav; use Friendica\Content\Widget; use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\L10n; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Profile; diff --git a/mod/dirfind.php b/mod/dirfind.php index d72c2d43d4..257c8b11aa 100644 --- a/mod/dirfind.php +++ b/mod/dirfind.php @@ -2,6 +2,7 @@ /** * @file mod/dirfind.php */ + use Friendica\App; use Friendica\Content\ContactSelector; use Friendica\Content\Widget; @@ -9,12 +10,13 @@ use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; +use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\GContact; use Friendica\Network\Probe; use Friendica\Protocol\PortableContact; use Friendica\Util\Network; -use Friendica\Database\DBM; require_once 'mod/contacts.php'; diff --git a/mod/display.php b/mod/display.php index 2600dfd26d..3775d263c8 100644 --- a/mod/display.php +++ b/mod/display.php @@ -11,6 +11,7 @@ use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\Protocol; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Group; diff --git a/mod/feedtest.php b/mod/feedtest.php index 9217b85d54..a96b1f5d03 100644 --- a/mod/feedtest.php +++ b/mod/feedtest.php @@ -6,6 +6,7 @@ use Friendica\App; use Friendica\Core\L10n; +use Friendica\Database\dba; use Friendica\Model\Contact; use Friendica\Protocol\Feed; use Friendica\Util\Network; diff --git a/mod/hovercard.php b/mod/hovercard.php index 0e8cc80f27..dfec168541 100644 --- a/mod/hovercard.php +++ b/mod/hovercard.php @@ -7,12 +7,13 @@ * Author: Rabuzarus * License: GNU AFFERO GENERAL PUBLIC LICENSE (Version 3) */ + use Friendica\App; use Friendica\Core\Config; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Model\Contact; use Friendica\Model\GContact; -use Friendica\Model\Profile; function hovercard_init(App $a) { diff --git a/mod/install.php b/mod/install.php index 55a7cdd7fd..59dcf92c56 100644 --- a/mod/install.php +++ b/mod/install.php @@ -4,9 +4,10 @@ */ use Friendica\App; -use Friendica\Core\L10n; use Friendica\Core\Install; +use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Util\Temporal; diff --git a/mod/item.php b/mod/item.php index 2359b79c58..7bcfdfbe35 100644 --- a/mod/item.php +++ b/mod/item.php @@ -17,11 +17,13 @@ use Friendica\App; use Friendica\Content\Text\BBCode; +use Friendica\Content\Text\HTML; use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Item; @@ -812,7 +814,7 @@ function item_post(App $a) { 'replyTo' => $a->user['email'], 'messageSubject' => $subject, 'htmlVersion' => $message, - 'textVersion' => Friendica\Content\Text\HTML::toPlaintext($html.$disclaimer) + 'textVersion' => HTML::toPlaintext($html.$disclaimer) ]; Emailer::send($params); } diff --git a/mod/lostpass.php b/mod/lostpass.php index 0d22252bdc..07c24f1580 100644 --- a/mod/lostpass.php +++ b/mod/lostpass.php @@ -4,8 +4,10 @@ */ use Friendica\App; +use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\User; use Friendica\Util\DateTimeFormat; diff --git a/mod/message.php b/mod/message.php index b414fe0e49..ccdb377b2f 100644 --- a/mod/message.php +++ b/mod/message.php @@ -10,6 +10,7 @@ use Friendica\Content\Text\BBCode; use Friendica\Core\ACL; use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Mail; diff --git a/mod/network.php b/mod/network.php index 67dd651e22..af9e111c9f 100644 --- a/mod/network.php +++ b/mod/network.php @@ -15,6 +15,7 @@ use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Group; diff --git a/mod/nodeinfo.php b/mod/nodeinfo.php index fad7246075..57b083a761 100644 --- a/mod/nodeinfo.php +++ b/mod/nodeinfo.php @@ -7,8 +7,9 @@ use Friendica\App; use Friendica\Core\Addon; -use Friendica\Core\System; use Friendica\Core\Config; +use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Util\Network; require_once 'include/dba.php'; diff --git a/mod/noscrape.php b/mod/noscrape.php index 20936929dd..d17937ff5d 100644 --- a/mod/noscrape.php +++ b/mod/noscrape.php @@ -2,8 +2,10 @@ /** * @file mod/noscrape.php */ + use Friendica\App; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Profile; diff --git a/mod/notes.php b/mod/notes.php index 69a5280f7e..af7bd71793 100644 --- a/mod/notes.php +++ b/mod/notes.php @@ -2,12 +2,14 @@ /** * @file mod/notes.php */ + use Friendica\App; use Friendica\Content\Nav; use Friendica\Core\L10n; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Model\Profile; use Friendica\Model\Item; +use Friendica\Model\Profile; function notes_init(App $a) { diff --git a/mod/notifications.php b/mod/notifications.php index b113be030d..0b7ac14d45 100644 --- a/mod/notifications.php +++ b/mod/notifications.php @@ -3,12 +3,14 @@ * @file mod/notifications.php * @brief The notifications module */ + use Friendica\App; use Friendica\Content\ContactSelector; use Friendica\Content\Nav; use Friendica\Core\L10n; use Friendica\Core\NotificationsManager; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; function notifications_post(App $a) diff --git a/mod/photos.php b/mod/photos.php index bd1de938c8..4058ac5c18 100644 --- a/mod/photos.php +++ b/mod/photos.php @@ -13,6 +13,7 @@ use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Group; diff --git a/mod/profile.php b/mod/profile.php index 08c0dfdb86..6ac7d41fe0 100644 --- a/mod/profile.php +++ b/mod/profile.php @@ -12,6 +12,7 @@ use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Group; use Friendica\Model\Item; diff --git a/mod/profiles.php b/mod/profiles.php index 3ceb8c6645..db4a7deae5 100644 --- a/mod/profiles.php +++ b/mod/profiles.php @@ -13,10 +13,10 @@ use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\GContact; -use Friendica\Model\Item; use Friendica\Model\Profile; use Friendica\Network\Probe; use Friendica\Util\DateTimeFormat; diff --git a/mod/proxy.php b/mod/proxy.php index ca8ced3cd6..6dc3967876 100644 --- a/mod/proxy.php +++ b/mod/proxy.php @@ -7,6 +7,7 @@ use Friendica\App; use Friendica\Core\Config; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Photo; use Friendica\Object\Image; diff --git a/mod/pubsub.php b/mod/pubsub.php index a68b222ec4..fb6de40523 100644 --- a/mod/pubsub.php +++ b/mod/pubsub.php @@ -1,6 +1,7 @@ mode |= App::MODE_LOCALCONFIGPRESENT; - if (!\dba::connected()) { + if (!dba::connected()) { return; } $this->mode |= App::MODE_DBAVAILABLE; - if (\dba::fetch_first("SHOW TABLES LIKE 'config'") === false) { + if (dba::fetch_first("SHOW TABLES LIKE 'config'") === false) { return; } @@ -513,7 +511,7 @@ class App public function loadDatabase() { - if (\dba::connected()) { + if (dba::connected()) { return; } @@ -544,7 +542,7 @@ class App $stamp1 = microtime(true); - \dba::connect($db_host, $db_user, $db_pass, $db_data, $charset); + dba::connect($db_host, $db_user, $db_pass, $db_data, $charset); unset($db_host, $db_user, $db_pass, $db_data, $charset); $this->save_timestamp($stamp1, 'network'); diff --git a/src/Content/ContactSelector.php b/src/Content/ContactSelector.php index 06972c36d9..47df84f7a6 100644 --- a/src/Content/ContactSelector.php +++ b/src/Content/ContactSelector.php @@ -6,9 +6,8 @@ namespace Friendica\Content; use Friendica\Core\Addon; use Friendica\Core\L10n; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Protocol\Diaspora; -use dba; /** * @brief ContactSelector class diff --git a/src/Content/ForumManager.php b/src/Content/ForumManager.php index e45dd0c421..edbe0b64e9 100644 --- a/src/Content/ForumManager.php +++ b/src/Content/ForumManager.php @@ -5,13 +5,12 @@ */ namespace Friendica\Content; -use Friendica\App; use Friendica\Content\Feature; use Friendica\Core\L10n; use Friendica\Core\System; -use Friendica\Model\Contact; +use Friendica\Database\dba; use Friendica\Database\DBM; -use dba; +use Friendica\Model\Contact; require_once 'include/dba.php'; diff --git a/src/Content/Nav.php b/src/Content/Nav.php index 92ca714df8..5f47875098 100644 --- a/src/Content/Nav.php +++ b/src/Content/Nav.php @@ -10,9 +10,9 @@ use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Profile; -use dba; require_once 'boot.php'; require_once 'dba.php'; diff --git a/src/Content/OEmbed.php b/src/Content/OEmbed.php index 390f3ea868..70556839e9 100644 --- a/src/Content/OEmbed.php +++ b/src/Content/OEmbed.php @@ -5,21 +5,21 @@ */ namespace Friendica\Content; -use Friendica\Core\Addon; -use Friendica\Core\Cache; -use Friendica\Core\Config; -use Friendica\Core\L10n; -use Friendica\Core\System; -use Friendica\Database\DBM; -use Friendica\Util\DateTimeFormat; -use Friendica\Util\Network; -use Friendica\Util\ParseUrl; -use dba; use DOMDocument; use DOMNode; use DOMText; use DOMXPath; use Exception; +use Friendica\Core\Addon; +use Friendica\Core\Cache; +use Friendica\Core\Config; +use Friendica\Core\L10n; +use Friendica\Core\System; +use Friendica\Database\dba; +use Friendica\Database\DBM; +use Friendica\Util\DateTimeFormat; +use Friendica\Util\Network; +use Friendica\Util\ParseUrl; use stdClass; require_once 'include/dba.php'; diff --git a/src/Content/Widget.php b/src/Content/Widget.php index ba57520124..76d51961c6 100644 --- a/src/Content/Widget.php +++ b/src/Content/Widget.php @@ -11,11 +11,11 @@ use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\GContact; use Friendica\Model\Profile; -use dba; require_once 'boot.php'; require_once 'include/dba.php'; diff --git a/src/Content/Widget/TagCloud.php b/src/Content/Widget/TagCloud.php index 53c4daae45..9160dd579f 100644 --- a/src/Content/Widget/TagCloud.php +++ b/src/Content/Widget/TagCloud.php @@ -6,9 +6,9 @@ namespace Friendica\Content\Widget; -use dba; use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; require_once 'include/dba.php'; diff --git a/src/Core/ACL.php b/src/Core/ACL.php index 4e8bf6abde..95948af293 100644 --- a/src/Core/ACL.php +++ b/src/Core/ACL.php @@ -6,27 +6,13 @@ namespace Friendica\Core; -use dba; use Friendica\BaseObject; use Friendica\Content\Feature; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\GContact; use Friendica\Util\Network; -use const CONTACT_IS_FRIEND; -use const NETWORK_DFRN; -use const NETWORK_DIASPORA; -use const NETWORK_FACEBOOK; -use const NETWORK_MAIL; -use const NETWORK_OSTATUS; -use const PHP_EOL; -use function dbesc; -use function defaults; -use function get_markup_template; -use function get_server; -use function local_user; -use function remote_user; -use function replace_macros; /** * Handle ACL management and display diff --git a/src/Core/Addon.php b/src/Core/Addon.php index 50247d240f..eb2b7d1aac 100644 --- a/src/Core/Addon.php +++ b/src/Core/Addon.php @@ -4,11 +4,9 @@ */ namespace Friendica\Core; -use Friendica\Core\Config; +use Friendica\App; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Core\Worker; - -use dba; require_once 'include/dba.php'; @@ -228,12 +226,12 @@ class Addon /** * @brief Calls a single hook. * - * @param \Friendica\App $a + * @param App $a * @param string $name of the hook to call * @param array $hook Hook data * @param string|array &$data to transmit to the callback handler */ - public static function callSingleHook(\Friendica\App $a, $name, $hook, &$data = null) + public static function callSingleHook(App $a, $name, $hook, &$data = null) { // Don't run a theme's hook if the user isn't using the theme if (strpos($hook[0], 'view/theme/') !== false && strpos($hook[0], 'view/theme/' . $a->getCurrentTheme()) === false) { diff --git a/src/Core/Cache/DatabaseCacheDriver.php b/src/Core/Cache/DatabaseCacheDriver.php index 059fef3290..2e14567704 100644 --- a/src/Core/Cache/DatabaseCacheDriver.php +++ b/src/Core/Cache/DatabaseCacheDriver.php @@ -2,8 +2,8 @@ namespace Friendica\Core\Cache; -use dba; use Friendica\Core\Cache; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Util\DateTimeFormat; diff --git a/src/Core/Config/JITConfigAdapter.php b/src/Core/Config/JITConfigAdapter.php index 527c718ae0..77902ffc82 100644 --- a/src/Core/Config/JITConfigAdapter.php +++ b/src/Core/Config/JITConfigAdapter.php @@ -1,8 +1,8 @@ mode === App::MODE_INSTALL) { - throw new \RuntimeException('Friendica isn\'t properly installed yet.'); + throw new RuntimeException('Friendica isn\'t properly installed yet.'); } $nurl = normalise_link($this->getArgument(0)); if (!dba::exists('contact', ['nurl' => $nurl, 'archive' => false])) { - throw new \RuntimeException(L10n::t('Could not find any unarchived contact entry for this URL (%s)', $nurl)); + throw new RuntimeException(L10n::t('Could not find any unarchived contact entry for this URL (%s)', $nurl)); } if (dba::update('contact', ['archive' => true], ['nurl' => $nurl])) { $condition = ["`cid` IN (SELECT `id` FROM `contact` WHERE `archive`)"]; dba::delete('queue', $condition); $this->out(L10n::t('The contact entries have been archived')); } else { - throw new \RuntimeException('The contact archival failed.'); + throw new RuntimeException('The contact archival failed.'); } return 0; diff --git a/src/Core/Console/AutomaticInstallation.php b/src/Core/Console/AutomaticInstallation.php index 4822368ab5..76735ec9ae 100644 --- a/src/Core/Console/AutomaticInstallation.php +++ b/src/Core/Console/AutomaticInstallation.php @@ -3,11 +3,11 @@ namespace Friendica\Core\Console; use Asika\SimpleConsole\Console; -use dba; use Friendica\App; use Friendica\Core\Config; use Friendica\Core\Install; use Friendica\Core\Theme; +use Friendica\Database\dba; use RuntimeException; require_once 'mod/install.php'; diff --git a/src/Core/Console/Config.php b/src/Core/Console/Config.php index c37dd26b15..daa0ba60a8 100644 --- a/src/Core/Console/Config.php +++ b/src/Core/Console/Config.php @@ -9,8 +9,9 @@ namespace Friendica\Core\Console; use Asika\SimpleConsole\CommandArgsException; -use dba; +use Friendica\App; use Friendica\Core; +use RuntimeException; require_once 'include/dba.php'; require_once 'include/text.php'; @@ -92,7 +93,7 @@ HELP; throw new CommandArgsException('Too many arguments'); } - if (!($a->mode & \Friendica\App::MODE_DBCONFIGAVAILABLE)) { + if (!($a->mode & App::MODE_DBCONFIGAVAILABLE)) { $this->out('Database isn\'t ready or populated yet, showing file config only'); } @@ -102,7 +103,7 @@ HELP; $value = $this->getArgument(2); if (is_array(Core\Config::get($cat, $key))) { - throw new \RuntimeException("$cat.$key is an array and can't be set using this command."); + throw new RuntimeException("$cat.$key is an array and can't be set using this command."); } $result = Core\Config::set($cat, $key, $value); @@ -151,7 +152,7 @@ HELP; if (count($this->args) == 0) { Core\Config::load(); - if (Core\Config::get('system', 'config_adapter') == 'jit' && $a->mode & \Friendica\App::MODE_DBCONFIGAVAILABLE) { + if (Core\Config::get('system', 'config_adapter') == 'jit' && $a->mode & App::MODE_DBCONFIGAVAILABLE) { $this->out('Warning: The JIT (Just In Time) Config adapter doesn\'t support loading the entire configuration, showing file config only'); } diff --git a/src/Core/Console/DatabaseStructure.php b/src/Core/Console/DatabaseStructure.php index 1190484310..8c26987d2c 100644 --- a/src/Core/Console/DatabaseStructure.php +++ b/src/Core/Console/DatabaseStructure.php @@ -3,7 +3,9 @@ namespace Friendica\Core\Console; use Friendica\Core; +use Friendica\Database\dba; use Friendica\Database\DBStructure; +use RuntimeException; require_once 'boot.php'; require_once 'include/dba.php'; @@ -56,8 +58,8 @@ HELP; throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments'); } - if (!\dba::connected()) { - throw new \RuntimeException('Unable to connect to database'); + if (!dba::connected()) { + throw new RuntimeException('Unable to connect to database'); } Core\Config::load(); diff --git a/src/Core/Console/GlobalCommunitySilence.php b/src/Core/Console/GlobalCommunitySilence.php index ccd6014e9c..6330d08a12 100644 --- a/src/Core/Console/GlobalCommunitySilence.php +++ b/src/Core/Console/GlobalCommunitySilence.php @@ -3,8 +3,10 @@ namespace Friendica\Core\Console; use Friendica\Core\Protocol; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Network\Probe; +use RuntimeException; require_once 'include/text.php'; @@ -65,7 +67,7 @@ HELP; } if ($a->isInstallMode()) { - throw new \RuntimeException('Database isn\'t ready or populated yet'); + throw new RuntimeException('Database isn\'t ready or populated yet'); } /** @@ -75,16 +77,16 @@ HELP; * */ $net = Probe::uri($this->getArgument(0)); if (in_array($net['network'], [Protocol::PHANTOM, Protocol::MAIL])) { - throw new \RuntimeException('This account seems not to exist.'); + throw new RuntimeException('This account seems not to exist.'); } $nurl = normalise_link($net['url']); - $contact = \dba::selectFirst("contact", ["id"], ["nurl" => $nurl, "uid" => 0]); + $contact = dba::selectFirst("contact", ["id"], ["nurl" => $nurl, "uid" => 0]); if (DBM::is_result($contact)) { - \dba::update("contact", ["hidden" => true], ["id" => $contact["id"]]); + dba::update("contact", ["hidden" => true], ["id" => $contact["id"]]); $this->out('NOTICE: The account should be silenced from the global community page'); } else { - throw new \RuntimeException('NOTICE: Could not find any entry for this URL (' . $nurl . ')'); + throw new RuntimeException('NOTICE: Could not find any entry for this URL (' . $nurl . ')'); } return 0; diff --git a/src/Core/Console/NewPassword.php b/src/Core/Console/NewPassword.php index 0035974727..cdf31422d1 100644 --- a/src/Core/Console/NewPassword.php +++ b/src/Core/Console/NewPassword.php @@ -2,12 +2,12 @@ namespace Friendica\Core\Console; -use Friendica\Core\L10n; -use Friendica\Model\Contact; -use Friendica\Model\User; use Friendica\Core\Config; +use Friendica\Core\L10n; +use Friendica\Database\dba; use Friendica\Database\DBM; -use dba; +use Friendica\Model\User; +use RuntimeException; /** * @brief tool to set a new password for a user @@ -59,14 +59,14 @@ HELP; } if ($a->isInstallMode()) { - throw new \RuntimeException('Database isn\'t ready or populated yet'); + throw new RuntimeException('Database isn\'t ready or populated yet'); } $nick = $this->getArgument(0); $user = dba::selectFirst('user', ['uid'], ['nickname' => $nick]); if (!DBM::is_result($user)) { - throw new \RuntimeException(L10n::t('User not found')); + throw new RuntimeException(L10n::t('User not found')); } $password = $this->getArgument(1); @@ -76,15 +76,15 @@ HELP; } if (!$password) { - throw new \RuntimeException(L10n::t('Password can\'t be empty')); + throw new RuntimeException(L10n::t('Password can\'t be empty')); } if (!Config::get('system', 'disable_password_exposed', false) && User::isPasswordExposed($password)) { - throw new \RuntimeException(L10n::t('The new password has been exposed in a public data dump, please choose another.')); + throw new RuntimeException(L10n::t('The new password has been exposed in a public data dump, please choose another.')); } if (!User::updatePassword($user['uid'], $password)) { - throw new \RuntimeException(L10n::t('Password update failed. Please try again.')); + throw new RuntimeException(L10n::t('Password update failed. Please try again.')); } $this->out(L10n::t('Password changed.')); diff --git a/src/Core/L10n.php b/src/Core/L10n.php index 2389817021..32f87a4703 100644 --- a/src/Core/L10n.php +++ b/src/Core/L10n.php @@ -4,8 +4,8 @@ */ namespace Friendica\Core; -use Friendica\Core\Config; -use dba; +use Friendica\BaseObject; +use Friendica\Database\dba; require_once 'boot.php'; require_once 'include/dba.php'; @@ -14,7 +14,7 @@ require_once 'include/dba.php'; * Provide Languange, Translation, and Localisation functions to the application * Localisation can be referred to by the numeronym L10N (as in: "L", followed by ten more letters, and then "N"). */ -class L10n extends \Friendica\BaseObject +class L10n extends BaseObject { /** * @brief get the prefered language from the HTTP_ACCEPT_LANGUAGE header diff --git a/src/Core/Lock/DatabaseLockDriver.php b/src/Core/Lock/DatabaseLockDriver.php index fc057c6b55..10612a91e4 100644 --- a/src/Core/Lock/DatabaseLockDriver.php +++ b/src/Core/Lock/DatabaseLockDriver.php @@ -2,8 +2,8 @@ namespace Friendica\Core\Lock; -use dba; use Friendica\Core\Cache; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Util\DateTimeFormat; diff --git a/src/Core/NotificationsManager.php b/src/Core/NotificationsManager.php index 6605abf79b..1154206d3c 100644 --- a/src/Core/NotificationsManager.php +++ b/src/Core/NotificationsManager.php @@ -9,17 +9,12 @@ namespace Friendica\Core; use Friendica\BaseObject; use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; -use Friendica\Core\L10n; -use Friendica\Core\PConfig; -use Friendica\Core\System; use Friendica\Database\DBM; use Friendica\Model\Contact; -use Friendica\Model\Profile; use Friendica\Model\Item; use Friendica\Util\DateTimeFormat; use Friendica\Util\Temporal; use Friendica\Util\XML; -use dba; require_once 'include/dba.php'; diff --git a/src/Core/Session/DatabaseSessionHandler.php b/src/Core/Session/DatabaseSessionHandler.php index f69531a888..82cb36aacb 100644 --- a/src/Core/Session/DatabaseSessionHandler.php +++ b/src/Core/Session/DatabaseSessionHandler.php @@ -4,9 +4,9 @@ namespace Friendica\Core\Session; use Friendica\BaseObject; use Friendica\Core\Session; +use Friendica\Database\dba; use Friendica\Database\DBM; use SessionHandlerInterface; -use dba; require_once 'boot.php'; require_once 'include/dba.php'; diff --git a/src/Core/UserImport.php b/src/Core/UserImport.php index 0832dae45a..1b25a66ba0 100644 --- a/src/Core/UserImport.php +++ b/src/Core/UserImport.php @@ -5,14 +5,9 @@ namespace Friendica\Core; use Friendica\App; -use Friendica\Core\L10n; -use Friendica\Core\System; -use Friendica\Core\PConfig; -use Friendica\Core\Worker; -use Friendica\Database\DBM; +use Friendica\Database\dba; use Friendica\Model\Photo; use Friendica\Object\Image; -use dba; require_once "include/dba.php"; diff --git a/src/Core/Worker.php b/src/Core/Worker.php index 897a80111d..fbd162615f 100644 --- a/src/Core/Worker.php +++ b/src/Core/Worker.php @@ -4,7 +4,7 @@ */ namespace Friendica\Core; -use dba; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Process; use Friendica\Util\DateTimeFormat; diff --git a/src/Database/DBM.php b/src/Database/DBM.php index 7daf6b545f..bbe60e0f2c 100644 --- a/src/Database/DBM.php +++ b/src/Database/DBM.php @@ -4,7 +4,6 @@ */ namespace Friendica\Database; -use dba; use Friendica\Util\DateTimeFormat; require_once 'include/dba.php'; diff --git a/src/Database/DBStructure.php b/src/Database/DBStructure.php index 67750c3479..bfecdba20e 100644 --- a/src/Database/DBStructure.php +++ b/src/Database/DBStructure.php @@ -4,7 +4,8 @@ */ namespace Friendica\Database; -use dba; +use Exception; +use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\L10n; @@ -629,7 +630,7 @@ class DBStructure private static function createIndex($indexname, $fieldnames, $method = "ADD") { $method = strtoupper(trim($method)); if ($method!="" && $method!="ADD") { - throw new \Exception("Invalid parameter 'method' in self::createIndex(): '$method'"); + throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'"); } if ($fieldnames[0] == "UNIQUE") { @@ -1941,7 +1942,7 @@ class DBStructure ] ]; - \Friendica\Core\Addon::callHooks('dbstructure_definition', $database); + Addon::callHooks('dbstructure_definition', $database); return $database; } diff --git a/src/Database/PostUpdate.php b/src/Database/PostUpdate.php index 5593d932a3..4ce89d49e5 100644 --- a/src/Database/PostUpdate.php +++ b/src/Database/PostUpdate.php @@ -5,11 +5,9 @@ namespace Friendica\Database; use Friendica\Core\Config; -use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Item; use Friendica\Model\PermissionSet; -use dba; require_once 'include/dba.php'; diff --git a/src/Model/Contact.php b/src/Model/Contact.php index 093ee0d91e..1328300937 100644 --- a/src/Model/Contact.php +++ b/src/Model/Contact.php @@ -11,19 +11,16 @@ use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Model\Photo; -use Friendica\Model\Profile; use Friendica\Network\Probe; -use Friendica\Protocol\DFRN; +use Friendica\Object\Image; use Friendica\Protocol\Diaspora; use Friendica\Protocol\OStatus; use Friendica\Protocol\PortableContact; use Friendica\Protocol\Salmon; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; -use Friendica\Object\Image; -use dba; require_once 'boot.php'; require_once 'include/dba.php'; diff --git a/src/Model/Conversation.php b/src/Model/Conversation.php index 69bbc3bb6d..4b1adc250f 100644 --- a/src/Model/Conversation.php +++ b/src/Model/Conversation.php @@ -4,8 +4,8 @@ */ namespace Friendica\Model; +use Friendica\Database\dba; use Friendica\Database\DBM; -use dba; require_once "include/dba.php"; diff --git a/src/Model/Event.php b/src/Model/Event.php index 47ec50aaa0..bd614f0bfb 100644 --- a/src/Model/Event.php +++ b/src/Model/Event.php @@ -5,15 +5,14 @@ namespace Friendica\Model; -use dba; use Friendica\BaseObject; use Friendica\Content\Text\BBCode; use Friendica\Core\Addon; use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Model\Item; use Friendica\Util\DateTimeFormat; use Friendica\Util\Map; diff --git a/src/Model/GContact.php b/src/Model/GContact.php index d77e81a4c7..52924b6416 100644 --- a/src/Model/GContact.php +++ b/src/Model/GContact.php @@ -6,18 +6,16 @@ */ namespace Friendica\Model; -use Friendica\Core\Config; +use Exception; +use Friendica\Core\Console\Config; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Model\Contact; -use Friendica\Model\Profile; use Friendica\Network\Probe; use Friendica\Protocol\PortableContact; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; -use dba; -use Exception; require_once 'include/dba.php'; diff --git a/src/Model/Group.php b/src/Model/Group.php index 79604e2ca0..5247a05569 100644 --- a/src/Model/Group.php +++ b/src/Model/Group.php @@ -6,8 +6,8 @@ namespace Friendica\Model; use Friendica\BaseObject; use Friendica\Core\L10n; +use Friendica\Database\dba; use Friendica\Database\DBM; -use dba; require_once 'boot.php'; require_once 'include/dba.php'; diff --git a/src/Model/Item.php b/src/Model/Item.php index 74a4ebba5f..4f9f1cf904 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -6,18 +6,16 @@ namespace Friendica\Model; -use dba; use Friendica\BaseObject; -use Friendica\Content\Text; +use Friendica\Content\Text\BBCode; use Friendica\Core\Addon; use Friendica\Core\Config; -use Friendica\Core\L10n; use Friendica\Core\Lock; use Friendica\Core\PConfig; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Model\PermissionSet; use Friendica\Object\Image; use Friendica\Protocol\Diaspora; use Friendica\Protocol\OStatus; @@ -2219,7 +2217,7 @@ class Item extends BaseObject */ private static function addLanguageToItemArray(&$item) { - $naked_body = Text\BBCode::toPlaintext($item['body'], false); + $naked_body = BBCode::toPlaintext($item['body'], false); $ld = new Text_LanguageDetect(); $ld->setNameMode(2); diff --git a/src/Model/Mail.php b/src/Model/Mail.php index f10ad368ba..1e5c864872 100644 --- a/src/Model/Mail.php +++ b/src/Model/Mail.php @@ -8,10 +8,10 @@ namespace Friendica\Model; use Friendica\Core\L10n; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Network\Probe; use Friendica\Util\DateTimeFormat; -use dba; require_once 'include/dba.php'; diff --git a/src/Model/OpenWebAuthToken.php b/src/Model/OpenWebAuthToken.php index 5c405b27d3..336f4ab069 100644 --- a/src/Model/OpenWebAuthToken.php +++ b/src/Model/OpenWebAuthToken.php @@ -5,9 +5,9 @@ */ namespace Friendica\Model; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Util\DateTimeFormat; -use dba; /** * Methods to deal with entries of the 'openwebauth-token' table. @@ -16,12 +16,12 @@ class OpenWebAuthToken { /** * Create an entry in the 'openwebauth-token' table. - * + * * @param string $type Verify type. * @param int $uid The user ID. * @param string $token * @param string $meta - * + * * @return boolean */ public static function create($type, $uid, $token, $meta) @@ -38,11 +38,11 @@ class OpenWebAuthToken /** * Get the "meta" field of an entry in the openwebauth-token table. - * + * * @param string $type Verify type. * @param int $uid The user ID. * @param string $token - * + * * @return string|boolean The meta enry or false if not found. */ public static function getMeta($type, $uid, $token) @@ -60,7 +60,7 @@ class OpenWebAuthToken /** * Purge entries of a verify-type older than interval. - * + * * @param string $type Verify type. * @param string $interval SQL compatible time interval */ diff --git a/src/Model/PermissionSet.php b/src/Model/PermissionSet.php index c31e88bf17..983261fd61 100644 --- a/src/Model/PermissionSet.php +++ b/src/Model/PermissionSet.php @@ -5,8 +5,8 @@ namespace Friendica\Model; use Friendica\BaseObject; +use Friendica\Database\dba; use Friendica\Database\DBM; -use dba; require_once 'include/dba.php'; diff --git a/src/Model/Photo.php b/src/Model/Photo.php index b08c6f0459..2d740c3933 100644 --- a/src/Model/Photo.php +++ b/src/Model/Photo.php @@ -10,11 +10,11 @@ use Friendica\Core\Cache; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Object\Image; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; -use dba; require_once 'include/dba.php'; diff --git a/src/Model/Process.php b/src/Model/Process.php index 75d898065c..d459597651 100644 --- a/src/Model/Process.php +++ b/src/Model/Process.php @@ -5,8 +5,8 @@ namespace Friendica\Model; use Friendica\BaseObject; +use Friendica\Database\dba; use Friendica\Util\DateTimeFormat; -use dba; require_once 'include/dba.php'; diff --git a/src/Model/Profile.php b/src/Model/Profile.php index 92355b216e..79f3262410 100644 --- a/src/Model/Profile.php +++ b/src/Model/Profile.php @@ -15,16 +15,12 @@ use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Model\Contact; -use Friendica\Model\OpenWebAuthToken; use Friendica\Protocol\Diaspora; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; use Friendica\Util\Temporal; -use dba; - -use InvalidArgumentException; require_once 'include/dba.php'; require_once 'mod/proxy.php'; diff --git a/src/Model/PushSubscriber.php b/src/Model/PushSubscriber.php index 925a461e2a..fc08ca6cbb 100644 --- a/src/Model/PushSubscriber.php +++ b/src/Model/PushSubscriber.php @@ -5,9 +5,9 @@ namespace Friendica\Model; use Friendica\Core\Worker; -use Friendica\Util\DateTimeFormat; +use Friendica\Database\dba; use Friendica\Database\DBM; -use dba; +use Friendica\Util\DateTimeFormat; require_once 'include/dba.php'; diff --git a/src/Model/Queue.php b/src/Model/Queue.php index 8b9e801c3f..8e9ed40d03 100644 --- a/src/Model/Queue.php +++ b/src/Model/Queue.php @@ -5,9 +5,9 @@ namespace Friendica\Model; use Friendica\Core\Config; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Util\DateTimeFormat; -use dba; require_once 'include/dba.php'; diff --git a/src/Model/Term.php b/src/Model/Term.php index e9918c23b8..9f0b595014 100644 --- a/src/Model/Term.php +++ b/src/Model/Term.php @@ -5,9 +5,8 @@ namespace Friendica\Model; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Model\Item; -use dba; require_once 'boot.php'; require_once 'include/conversation.php'; diff --git a/src/Model/User.php b/src/Model/User.php index 57a3ecb50d..4dca908b61 100644 --- a/src/Model/User.php +++ b/src/Model/User.php @@ -6,22 +6,19 @@ namespace Friendica\Model; use DivineOmega\PasswordExposed\PasswordStatus; +use Exception; use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Model\Contact; -use Friendica\Model\Group; -use Friendica\Model\Photo; use Friendica\Object\Image; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; -use dba; -use Exception; use LightOpenID; use function password_exposed; diff --git a/src/Module/Hashtag.php b/src/Module/Hashtag.php index c35a6440c0..a53585c284 100644 --- a/src/Module/Hashtag.php +++ b/src/Module/Hashtag.php @@ -6,7 +6,7 @@ namespace Friendica\Module; use Friendica\BaseModule; use Friendica\Core\System; -use dba; +use Friendica\Database\dba; require_once 'include/dba.php'; require_once 'include/text.php'; diff --git a/src/Module/Login.php b/src/Module/Login.php index 06d724bb2a..fb7a60613d 100644 --- a/src/Module/Login.php +++ b/src/Module/Login.php @@ -4,16 +4,16 @@ */ namespace Friendica\Module; +use Exception; use Friendica\BaseModule; use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\L10n; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\User; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; -use dba; -use Exception; use LightOpenID; require_once 'boot.php'; diff --git a/src/Module/Magic.php b/src/Module/Magic.php index d55e8f93bc..c1e2a7c978 100644 --- a/src/Module/Magic.php +++ b/src/Module/Magic.php @@ -5,12 +5,11 @@ namespace Friendica\Module; use Friendica\BaseModule; +use Friendica\Database\dba; use Friendica\Model\Contact; use Friendica\Util\HTTPSignature; use Friendica\Util\Network; -use dba; - /** * Magic Auth (remote authentication) module. * diff --git a/src/Module/Owa.php b/src/Module/Owa.php index 306c525c06..84f2502447 100644 --- a/src/Module/Owa.php +++ b/src/Module/Owa.php @@ -6,23 +6,22 @@ namespace Friendica\Module; use Friendica\BaseModule; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\OpenWebAuthToken; use Friendica\Util\HTTPSignature; -use dba; - /** * @brief OpenWebAuth verifier and token generator - * + * * See https://macgirvin.com/wiki/mike/OpenWebAuth/Home * Requests to this endpoint should be signed using HTTP Signatures * using the 'Authorization: Signature' authentication method * If the signature verifies a token is returned. * * This token may be exchanged for an authenticated cookie. - * + * * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Module/Owa.php */ class Owa extends BaseModule diff --git a/src/Network/FKOAuth1.php b/src/Network/FKOAuth1.php index 8af267be3d..addaeae115 100644 --- a/src/Network/FKOAuth1.php +++ b/src/Network/FKOAuth1.php @@ -7,10 +7,9 @@ namespace Friendica\Network; use Friendica\Core\Addon; use Friendica\Core\PConfig; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Network\FKOAuthDataStore; use Friendica\Util\DateTimeFormat; -use dba; use OAuthServer; use OAuthSignatureMethod_HMAC_SHA1; use OAuthSignatureMethod_PLAINTEXT; diff --git a/src/Network/FKOAuthDataStore.php b/src/Network/FKOAuthDataStore.php index 7a3329776a..154d63b72f 100644 --- a/src/Network/FKOAuthDataStore.php +++ b/src/Network/FKOAuthDataStore.php @@ -10,8 +10,8 @@ namespace Friendica\Network; use Friendica\Core\Config; +use Friendica\Database\dba; use Friendica\Database\DBM; -use dba; use OAuthConsumer; use OAuthDataStore; use OAuthToken; diff --git a/src/Network/Probe.php b/src/Network/Probe.php index 6b278a965f..1a5ccbfae1 100644 --- a/src/Network/Probe.php +++ b/src/Network/Probe.php @@ -9,21 +9,19 @@ namespace Friendica\Network; * @brief Functions for probing URL */ -use Friendica\App; -use Friendica\Core\System; +use DOMDocument; use Friendica\Core\Cache; use Friendica\Core\Config; +use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Profile; use Friendica\Protocol\Email; use Friendica\Protocol\Feed; use Friendica\Util\Crypto; +use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; use Friendica\Util\XML; -use Friendica\Util\DateTimeFormat; -use dba; -use DOMXPath; -use DOMDocument; require_once 'include/dba.php'; diff --git a/src/Object/Post.php b/src/Object/Post.php index 8b05abc566..71431b10db 100644 --- a/src/Object/Post.php +++ b/src/Object/Post.php @@ -11,12 +11,12 @@ use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\PConfig; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Item; use Friendica\Util\DateTimeFormat; use Friendica\Util\Temporal; -use dba; require_once 'include/dba.php'; require_once 'include/text.php'; diff --git a/src/Protocol/DFRN.php b/src/Protocol/DFRN.php index 5326e49ac9..0769d3b1d9 100644 --- a/src/Protocol/DFRN.php +++ b/src/Protocol/DFRN.php @@ -8,6 +8,8 @@ */ namespace Friendica\Protocol; +use DOMDocument; +use DOMXPath; use Friendica\App; use Friendica\Content\OEmbed; use Friendica\Content\Text\BBCode; @@ -16,7 +18,7 @@ use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\System; -use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Event; @@ -26,15 +28,10 @@ use Friendica\Model\Item; use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Object\Image; -use Friendica\Protocol\OStatus; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; use Friendica\Util\XML; -use Friendica\Protocol\Diaspora; -use dba; -use DOMDocument; -use DOMXPath; use HTMLPurifier; use HTMLPurifier_Config; diff --git a/src/Protocol/Diaspora.php b/src/Protocol/Diaspora.php index 6b6e75cda4..40caa4f06d 100644 --- a/src/Protocol/Diaspora.php +++ b/src/Protocol/Diaspora.php @@ -18,6 +18,7 @@ use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\System; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\GContact; @@ -29,12 +30,11 @@ use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; +use Friendica\Util\Map; use Friendica\Util\Network; use Friendica\Util\XML; -use Friendica\Util\Map; -use dba; -use stdClass; use SimpleXMLElement; +use stdClass; require_once 'include/dba.php'; require_once 'include/items.php'; diff --git a/src/Protocol/Feed.php b/src/Protocol/Feed.php index d989b99622..3ebf37e4c7 100644 --- a/src/Protocol/Feed.php +++ b/src/Protocol/Feed.php @@ -6,16 +6,14 @@ */ namespace Friendica\Protocol; -use Friendica\Database\DBM; -use Friendica\Core\System; -use Friendica\Model\Item; -use Friendica\Util\Network; -use Friendica\Content\Text\HTML; -use Friendica\Util\XML; - -use dba; use DOMDocument; use DOMXPath; +use Friendica\Content\Text\HTML; +use Friendica\Core\System; +use Friendica\Database\DBM; +use Friendica\Model\Item; +use Friendica\Util\Network; +use Friendica\Util\XML; require_once 'include/dba.php'; require_once 'include/items.php'; diff --git a/src/Protocol/OStatus.php b/src/Protocol/OStatus.php index f0f4bed01a..bd0defa32a 100644 --- a/src/Protocol/OStatus.php +++ b/src/Protocol/OStatus.php @@ -4,7 +4,6 @@ */ namespace Friendica\Protocol; -use dba; use DOMDocument; use DOMXPath; use Friendica\Content\Text\BBCode; @@ -14,6 +13,7 @@ use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\Lock; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Conversation; diff --git a/src/Protocol/PortableContact.php b/src/Protocol/PortableContact.php index a9e06d19a8..848662538b 100644 --- a/src/Protocol/PortableContact.php +++ b/src/Protocol/PortableContact.php @@ -9,21 +9,20 @@ namespace Friendica\Protocol; +use DOMDocument; +use DOMXPath; +use Exception; use Friendica\Content\Text\HTML; use Friendica\Core\Config; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\GContact; use Friendica\Model\Profile; use Friendica\Network\Probe; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; -use Friendica\Protocol\Diaspora; use Friendica\Util\XML; -use dba; -use DOMDocument; -use DOMXPath; -use Exception; require_once 'include/dba.php'; diff --git a/src/Util/ExAuth.php b/src/Util/ExAuth.php index d4436e32af..a01a7c721e 100644 --- a/src/Util/ExAuth.php +++ b/src/Util/ExAuth.php @@ -36,10 +36,9 @@ namespace Friendica\Util; use Friendica\Core\Config; use Friendica\Core\PConfig; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\User; -use Friendica\Util\Network; -use dba; require_once 'include/dba.php'; diff --git a/src/Util/HTTPSignature.php b/src/Util/HTTPSignature.php index a91b6b37e3..c3a45205c3 100644 --- a/src/Util/HTTPSignature.php +++ b/src/Util/HTTPSignature.php @@ -6,16 +6,14 @@ namespace Friendica\Util; use Friendica\Core\Config; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Util\Crypto; -use Friendica\Util\HTTPHeaders; -use dba; /** * @brief Implements HTTP Signatures per draft-cavage-http-signatures-07. * * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/Zotlabs/Web/HTTPSig.php - * + * * @see https://tools.ietf.org/html/draft-cavage-http-signatures-07 */ @@ -26,13 +24,13 @@ class HTTPSignature * * Disabled until Friendica's ActivityPub implementation * is ready. - * + * * @see https://tools.ietf.org/html/rfc5843 * * @param string $body The value to create the digest for * @param boolean $set (optional, default true) * If set send a Digest HTTP header - * + * * @return string The generated digest of $body */ // public static function generateDigest($body, $set = true) @@ -174,7 +172,7 @@ class HTTPSignature /** * Fetch the public key for Activity Pub contact. - * + * * @param string|int The identifier (contact addr or contact ID). * @return string|boolean The public key or false on failure. */ @@ -222,7 +220,7 @@ class HTTPSignature * @param string $alg (optional, default 'sha256') * @param string $crypt_key (optional, default null) * @param string $crypt_algo (optional, default 'aes256ctr') - * + * * @return array */ public static function createSig($request, $head, $prvkey, $keyid = 'Key', $send_headers = false, $auth = false, $alg = 'sha256', $crypt_key = null, $crypt_algo = 'aes256ctr') @@ -285,7 +283,7 @@ class HTTPSignature * @param array $head * @param string $prvkey * @param string $alg (optional) default 'sha256' - * + * * @return array */ private static function sign($request, $head, $prvkey, $alg = 'sha256') @@ -315,7 +313,7 @@ class HTTPSignature $ret['headers'] = $fields; $ret['signature'] = $sig; - + return $ret; } @@ -367,7 +365,7 @@ class HTTPSignature * * @param string $header * @param string $prvkey (optional), if not set use site private key - * + * * @return array|string associative array, empty string if failue * - \e string \b iv * - \e string \b key diff --git a/src/Util/ParseUrl.php b/src/Util/ParseUrl.php index 8fff3bcd87..80761032e9 100644 --- a/src/Util/ParseUrl.php +++ b/src/Util/ParseUrl.php @@ -5,15 +5,12 @@ */ namespace Friendica\Util; +use DOMDocument; +use DOMXPath; use Friendica\Content\OEmbed; use Friendica\Core\Addon; +use Friendica\Database\dba; use Friendica\Object\Image; -use Friendica\Util\Network; -use Friendica\Util\XML; - -use dba; -use DOMXPath; -use DOMDocument; require_once 'include/dba.php'; diff --git a/src/Worker/Cron.php b/src/Worker/Cron.php index a0dfda3309..df7a18a179 100644 --- a/src/Worker/Cron.php +++ b/src/Worker/Cron.php @@ -4,12 +4,13 @@ */ namespace Friendica\Worker; +use Friendica\BaseObject; use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Util\DateTimeFormat; -use dba; require_once 'include/dba.php'; @@ -17,7 +18,7 @@ class Cron { public static function execute($parameter = '', $generation = 0) { - $a = \Friendica\BaseObject::getApp(); + $a = BaseObject::getApp(); // Poll contacts with specific parameters if (!empty($parameter)) { diff --git a/src/Worker/CronJobs.php b/src/Worker/CronJobs.php index 8b9d3b9bcf..6454be3e58 100644 --- a/src/Worker/CronJobs.php +++ b/src/Worker/CronJobs.php @@ -5,8 +5,10 @@ namespace Friendica\Worker; use Friendica\App; +use Friendica\BaseObject; use Friendica\Core\Cache; use Friendica\Core\Config; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Database\PostUpdate; use Friendica\Model\Contact; @@ -15,7 +17,6 @@ use Friendica\Model\Photo; use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Protocol\PortableContact; -use dba; require_once 'include/dba.php'; require_once 'mod/nodeinfo.php'; @@ -24,7 +25,7 @@ class CronJobs { public static function execute($command = '') { - $a = \Friendica\BaseObject::getApp(); + $a = BaseObject::getApp(); // No parameter set? So return if ($command == '') { diff --git a/src/Worker/DBClean.php b/src/Worker/DBClean.php index 7a0b1f8473..05955167f3 100644 --- a/src/Worker/DBClean.php +++ b/src/Worker/DBClean.php @@ -8,7 +8,7 @@ namespace Friendica\Worker; use Friendica\Core\Config; use Friendica\Core\Worker; -use dba; +use Friendica\Database\dba; require_once 'include/dba.php'; diff --git a/src/Worker/Delivery.php b/src/Worker/Delivery.php index b2781d5874..13ecc3ad44 100644 --- a/src/Worker/Delivery.php +++ b/src/Worker/Delivery.php @@ -8,6 +8,7 @@ use Friendica\BaseObject; use Friendica\Core\Config; use Friendica\Core\L10n; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Item; @@ -16,7 +17,6 @@ use Friendica\Model\User; use Friendica\Protocol\DFRN; use Friendica\Protocol\Diaspora; use Friendica\Protocol\Email; -use dba; require_once 'include/items.php'; diff --git a/src/Worker/DiscoverPoCo.php b/src/Worker/DiscoverPoCo.php index c77830d60a..2e36ab514d 100644 --- a/src/Worker/DiscoverPoCo.php +++ b/src/Worker/DiscoverPoCo.php @@ -7,13 +7,13 @@ namespace Friendica\Worker; use Friendica\Core\Cache; use Friendica\Core\Config; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\GContact; use Friendica\Network\Probe; use Friendica\Protocol\PortableContact; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; -use dba; class DiscoverPoCo { diff --git a/src/Worker/Expire.php b/src/Worker/Expire.php index a4342722d5..1d4efb29cd 100644 --- a/src/Worker/Expire.php +++ b/src/Worker/Expire.php @@ -6,12 +6,13 @@ namespace Friendica\Worker; +use Friendica\BaseObject; use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Item; -use dba; require_once 'include/dba.php'; @@ -19,7 +20,7 @@ class Expire { public static function execute($param = '', $hook_name = '') { - $a = \Friendica\BaseObject::getApp(); + $a = BaseObject::getApp(); require_once 'include/items.php'; diff --git a/src/Worker/Notifier.php b/src/Worker/Notifier.php index 385892f991..986ade27bf 100644 --- a/src/Worker/Notifier.php +++ b/src/Worker/Notifier.php @@ -4,21 +4,21 @@ */ namespace Friendica\Worker; +use Friendica\BaseObject; use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Group; use Friendica\Model\Item; -use Friendica\Model\User; use Friendica\Model\PushSubscriber; +use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Protocol\Diaspora; use Friendica\Protocol\OStatus; use Friendica\Protocol\Salmon; -use Friendica\Worker\Delivery; -use dba; require_once 'include/dba.php'; require_once 'include/items.php'; @@ -52,7 +52,7 @@ class Notifier { public static function execute($cmd, $item_id) { - $a = \Friendica\BaseObject::getApp(); + $a = BaseObject::getApp(); logger('notifier: invoked: '.$cmd.': '.$item_id, LOGGER_DEBUG); diff --git a/src/Worker/OnePoll.php b/src/Worker/OnePoll.php index 951a20b012..7704c3826a 100644 --- a/src/Worker/OnePoll.php +++ b/src/Worker/OnePoll.php @@ -4,9 +4,11 @@ */ namespace Friendica\Worker; +use Friendica\BaseObject; use Friendica\Content\Text\BBCode; use Friendica\Core\Config; use Friendica\Core\PConfig; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Item; @@ -15,7 +17,6 @@ use Friendica\Protocol\PortableContact; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; use Friendica\Util\XML; -use dba; require_once 'include/dba.php'; @@ -23,7 +24,7 @@ class OnePoll { public static function execute($contact_id = 0, $command = '') { - $a = \Friendica\BaseObject::getApp(); + $a = BaseObject::getApp(); require_once 'include/items.php'; diff --git a/src/Worker/PubSubPublish.php b/src/Worker/PubSubPublish.php index b90fc11a49..50f01e294e 100644 --- a/src/Worker/PubSubPublish.php +++ b/src/Worker/PubSubPublish.php @@ -5,13 +5,13 @@ namespace Friendica\Worker; -use Friendica\App; +use Friendica\BaseObject; use Friendica\Core\System; +use Friendica\Database\dba; use Friendica\Database\DBM; +use Friendica\Model\PushSubscriber; use Friendica\Protocol\OStatus; use Friendica\Util\Network; -use Friendica\Model\PushSubscriber; -use dba; require_once 'include/items.php'; @@ -28,7 +28,7 @@ class PubSubPublish private static function publish($id) { - $a = \Friendica\BaseObject::getApp(); + $a = BaseObject::getApp(); $subscriber = dba::selectFirst('push_subscriber', [], ['id' => $id]); if (!DBM::is_result($subscriber)) { diff --git a/src/Worker/Queue.php b/src/Worker/Queue.php index 1ec4090565..53d93ba910 100644 --- a/src/Worker/Queue.php +++ b/src/Worker/Queue.php @@ -8,15 +8,15 @@ use Friendica\Core\Addon; use Friendica\Core\Cache; use Friendica\Core\Config; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; -use Friendica\Model\Queue as QueueModel; use Friendica\Model\PushSubscriber; +use Friendica\Model\Queue as QueueModel; use Friendica\Model\User; use Friendica\Protocol\DFRN; use Friendica\Protocol\Diaspora; use Friendica\Protocol\PortableContact; use Friendica\Protocol\Salmon; -use dba; require_once 'include/dba.php'; require_once 'include/items.php'; diff --git a/src/Worker/RemoveContact.php b/src/Worker/RemoveContact.php index 9a7a257770..aa2325d549 100644 --- a/src/Worker/RemoveContact.php +++ b/src/Worker/RemoveContact.php @@ -5,8 +5,7 @@ */ namespace Friendica\Worker; -use Friendica\Core\Config; -use dba; +use Friendica\Database\dba; require_once 'include/dba.php'; diff --git a/src/Worker/TagUpdate.php b/src/Worker/TagUpdate.php index 1ecc4b5e9b..6db06380c8 100644 --- a/src/Worker/TagUpdate.php +++ b/src/Worker/TagUpdate.php @@ -2,7 +2,7 @@ namespace Friendica\Worker; -use dba; +use Friendica\Database\dba; class TagUpdate { diff --git a/tests/DatabaseTest.php b/tests/DatabaseTest.php index 579e45084d..9f0990a72d 100644 --- a/tests/DatabaseTest.php +++ b/tests/DatabaseTest.php @@ -5,12 +5,11 @@ namespace Friendica\Test; -use dba; -use Friendica\Database\DBStructure; -use PHPUnit_Extensions_Database_DB_IDatabaseConnection; +use Friendica\Database\dba; use PHPUnit\DbUnit\DataSet\YamlDataSet; use PHPUnit\DbUnit\TestCaseTrait; use PHPUnit\Framework\TestCase; +use PHPUnit_Extensions_Database_DB_IDatabaseConnection; /** * Abstract class used by tests that need a database. diff --git a/tests/src/Core/Lock/DatabaseLockDriverTest.php b/tests/src/Core/Lock/DatabaseLockDriverTest.php index f55ab0f9e2..1fd728888e 100644 --- a/tests/src/Core/Lock/DatabaseLockDriverTest.php +++ b/tests/src/Core/Lock/DatabaseLockDriverTest.php @@ -2,12 +2,8 @@ namespace Friendica\Test\src\Core\Lock; -use dba; use Friendica\Core\Lock\DatabaseLockDriver; -use Friendica\Database\DBStructure; -use PHPUnit\DbUnit\DataSet\YamlDataSet; -use PHPUnit\DbUnit\TestCaseTrait; -use PHPUnit_Extensions_Database_DB_IDatabaseConnection; +use Friendica\Database\dba; class DatabaseLockDriverTest extends LockTest { diff --git a/update.php b/update.php index ca427186d4..47055852ca 100644 --- a/update.php +++ b/update.php @@ -2,13 +2,14 @@ use Friendica\Core\Addon; use Friendica\Core\Config; +use Friendica\Core\L10n; use Friendica\Core\PConfig; use Friendica\Core\Worker; +use Friendica\Database\dba; use Friendica\Database\DBM; use Friendica\Model\Contact; use Friendica\Model\Item; use Friendica\Model\User; -use Friendica\Core\L10n; require_once 'include/dba.php'; From 72f32f90d1ac956ff379fab2773c33d1321433c0 Mon Sep 17 00:00:00 2001 From: Hypolite Petovan Date: Thu, 19 Jul 2018 22:15:57 -0400 Subject: [PATCH 3/4] Remove class \dba from include/dba --- include/dba.php | 1521 +---------------------------------------------- 1 file changed, 1 insertion(+), 1520 deletions(-) diff --git a/include/dba.php b/include/dba.php index 954c3a7cbb..a560c02312 100644 --- a/include/dba.php +++ b/include/dba.php @@ -1,1525 +1,6 @@ getConfigVariable() instead. -//use Friendica\Core\Config; - -use Friendica\Core\System; -use Friendica\Database\DBM; -use Friendica\Database\DBStructure; -use Friendica\Util\DateTimeFormat; - -/** - * @class MySQL database class - * - * This class is for the low level database stuff that does driver specific things. - */ - -class dba { - public static $connected = false; - - private static $_server_info = ''; - private static $db; - private static $driver; - private static $error = false; - private static $errorno = 0; - private static $affected_rows = 0; - private static $in_transaction = false; - private static $in_retrial = false; - private static $relation = []; - private static $db_serveraddr = ''; - private static $db_user = ''; - private static $db_pass = ''; - private static $db_name = ''; - private static $db_charset = ''; - - public static function connect($serveraddr, $user, $pass, $db, $charset = null) - { - if (!is_null(self::$db) && self::connected()) { - return true; - } - - // We are storing these values for being able to perform a reconnect - self::$db_serveraddr = $serveraddr; - self::$db_user = $user; - self::$db_pass = $pass; - self::$db_name = $db; - self::$db_charset = $charset; - - $serveraddr = trim($serveraddr); - - $serverdata = explode(':', $serveraddr); - $server = $serverdata[0]; - - if (count($serverdata) > 1) { - $port = trim($serverdata[1]); - } - - $server = trim($server); - $user = trim($user); - $pass = trim($pass); - $db = trim($db); - $charset = trim($charset); - - if (!(strlen($server) && strlen($user))) { - return false; - } - - if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) { - self::$driver = 'pdo'; - $connect = "mysql:host=".$server.";dbname=".$db; - - if (isset($port)) { - $connect .= ";port=".$port; - } - - if ($charset) { - $connect .= ";charset=".$charset; - } - - try { - self::$db = @new PDO($connect, $user, $pass); - self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); - self::$connected = true; - } catch (PDOException $e) { - } - } - - if (!self::$connected && class_exists('mysqli')) { - self::$driver = 'mysqli'; - self::$db = @new mysqli($server, $user, $pass, $db, $port); - if (!mysqli_connect_errno()) { - self::$connected = true; - - if ($charset) { - self::$db->set_charset($charset); - } - } - } - - // No suitable SQL driver was found. - if (!self::$connected) { - self::$driver = null; - self::$db = null; - } - - return self::$connected; - } - - /** - * Disconnects the current database connection - */ - public static function disconnect() - { - if (is_null(self::$db)) { - return; - } - - switch (self::$driver) { - case 'pdo': - self::$db = null; - break; - case 'mysqli': - self::$db->close(); - self::$db = null; - break; - } - } - - /** - * Perform a reconnect of an existing database connection - */ - public static function reconnect() { - self::disconnect(); - - $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name, self::$db_charset); - return $ret; - } - - /** - * Return the database object. - * @return PDO|mysqli - */ - public static function get_db() - { - return self::$db; - } - - /** - * @brief Returns the MySQL server version string - * - * This function discriminate between the deprecated mysql API and the current - * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1 - * - * @return string - */ - public static function server_info() { - if (self::$_server_info == '') { - switch (self::$driver) { - case 'pdo': - self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION); - break; - case 'mysqli': - self::$_server_info = self::$db->server_info; - break; - } - } - return self::$_server_info; - } - - /** - * @brief Returns the selected database name - * - * @return string - */ - public static function database_name() { - $ret = self::p("SELECT DATABASE() AS `db`"); - $data = self::inArray($ret); - return $data[0]['db']; - } - - /** - * @brief Analyze a database query and log this if some conditions are met. - * - * @param string $query The database query that will be analyzed - */ - private static function logIndex($query) { - $a = get_app(); - - if (!$a->getConfigVariable('system', 'db_log_index')) { - return; - } - - // Don't explain an explain statement - if (strtolower(substr($query, 0, 7)) == "explain") { - return; - } - - // Only do the explain on "select", "update" and "delete" - if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) { - return; - } - - $r = self::p("EXPLAIN ".$query); - if (!DBM::is_result($r)) { - return; - } - - $watchlist = explode(',', $a->getConfigVariable('system', 'db_log_index_watch')); - $blacklist = explode(',', $a->getConfigVariable('system', 'db_log_index_blacklist')); - - while ($row = dba::fetch($r)) { - if ((intval($a->getConfigVariable('system', 'db_loglimit_index')) > 0)) { - $log = (in_array($row['key'], $watchlist) && - ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index')))); - } else { - $log = false; - } - - if ((intval($a->getConfigVariable('system', 'db_loglimit_index_high')) > 0) && ($row['rows'] >= intval($a->getConfigVariable('system', 'db_loglimit_index_high')))) { - $log = true; - } - - if (in_array($row['key'], $blacklist) || ($row['key'] == "")) { - $log = false; - } - - if ($log) { - $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); - @file_put_contents($a->getConfigVariable('system', 'db_log_index'), DateTimeFormat::utcNow()."\t". - $row['key']."\t".$row['rows']."\t".$row['Extra']."\t". - basename($backtrace[1]["file"])."\t". - $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t". - substr($query, 0, 2000)."\n", FILE_APPEND); - } - } - } - - public static function escape($str) { - switch (self::$driver) { - case 'pdo': - return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1); - case 'mysqli': - return @self::$db->real_escape_string($str); - } - } - - public static function connected() { - $connected = false; - - if (is_null(self::$db)) { - return false; - } - - switch (self::$driver) { - case 'pdo': - $r = dba::p("SELECT 1"); - if (DBM::is_result($r)) { - $row = dba::inArray($r); - $connected = ($row[0]['1'] == '1'); - } - break; - case 'mysqli': - $connected = self::$db->ping(); - break; - } - return $connected; - } - - /** - * @brief Replaces ANY_VALUE() function by MIN() function, - * if the database server does not support ANY_VALUE(). - * - * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5). - * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html - * A standard fall-back is to use MIN(). - * - * @param string $sql An SQL string without the values - * @return string The input SQL string modified if necessary. - */ - public static function any_value_fallback($sql) { - $server_info = self::server_info(); - if (version_compare($server_info, '5.7.5', '<') || - (stripos($server_info, 'MariaDB') !== false)) { - $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql); - } - return $sql; - } - - /** - * @brief beautifies the query - useful for "SHOW PROCESSLIST" - * - * This is safe when we bind the parameters later. - * The parameter values aren't part of the SQL. - * - * @param string $sql An SQL string without the values - * @return string The input SQL string modified if necessary. - */ - public static function clean_query($sql) { - $search = ["\t", "\n", "\r", " "]; - $replace = [' ', ' ', ' ', ' ']; - do { - $oldsql = $sql; - $sql = str_replace($search, $replace, $sql); - } while ($oldsql != $sql); - - return $sql; - } - - - /** - * @brief Replaces the ? placeholders with the parameters in the $args array - * - * @param string $sql SQL query - * @param array $args The parameters that are to replace the ? placeholders - * @return string The replaced SQL query - */ - private static function replaceParameters($sql, $args) { - $offset = 0; - foreach ($args AS $param => $value) { - if (is_int($args[$param]) || is_float($args[$param])) { - $replace = intval($args[$param]); - } else { - $replace = "'".self::escape($args[$param])."'"; - } - - $pos = strpos($sql, '?', $offset); - if ($pos !== false) { - $sql = substr_replace($sql, $replace, $pos, 1); - } - $offset = $pos + strlen($replace); - } - return $sql; - } - - /** - * @brief Convert parameter array to an universal form - * @param array $args Parameter array - * @return array universalized parameter array - */ - private static function getParam($args) { - unset($args[0]); - - // When the second function parameter is an array then use this as the parameter array - if ((count($args) > 0) && (is_array($args[1]))) { - return $args[1]; - } else { - return $args; - } - } - - /** - * @brief Executes a prepared statement that returns data - * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid); - * - * Please only use it with complicated queries. - * For all regular queries please use dba::select or dba::exists - * - * @param string $sql SQL statement - * @return bool|object statement object or result object - */ - public static function p($sql) { - $a = get_app(); - - $stamp1 = microtime(true); - - $params = self::getParam(func_get_args()); - - // Renumber the array keys to be sure that they fit - $i = 0; - $args = []; - foreach ($params AS $param) { - // Avoid problems with some MySQL servers and boolean values. See issue #3645 - if (is_bool($param)) { - $param = (int)$param; - } - $args[++$i] = $param; - } - - if (!self::$connected) { - return false; - } - - if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) { - // Question: Should we continue or stop the query here? - logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG); - } - - $sql = self::clean_query($sql); - $sql = self::any_value_fallback($sql); - - $orig_sql = $sql; - - if ($a->getConfigValue('system', 'db_callstack')) { - $sql = "/*".System::callstack()." */ ".$sql; - } - - self::$error = ''; - self::$errorno = 0; - self::$affected_rows = 0; - - // We have to make some things different if this function is called from "e" - $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2); - - if (isset($trace[1])) { - $called_from = $trace[1]; - } else { - // We use just something that is defined to avoid warnings - $called_from = $trace[0]; - } - // We are having an own error logging in the function "e" - $called_from_e = ($called_from['function'] == 'e'); - - switch (self::$driver) { - case 'pdo': - // If there are no arguments we use "query" - if (count($args) == 0) { - if (!$retval = self::$db->query($sql)) { - $errorInfo = self::$db->errorInfo(); - self::$error = $errorInfo[2]; - self::$errorno = $errorInfo[1]; - $retval = false; - break; - } - self::$affected_rows = $retval->rowCount(); - break; - } - - if (!$stmt = self::$db->prepare($sql)) { - $errorInfo = self::$db->errorInfo(); - self::$error = $errorInfo[2]; - self::$errorno = $errorInfo[1]; - $retval = false; - break; - } - - foreach ($args AS $param => $value) { - if (is_int($args[$param])) { - $data_type = PDO::PARAM_INT; - } else { - $data_type = PDO::PARAM_STR; - } - $stmt->bindParam($param, $args[$param], $data_type); - } - - if (!$stmt->execute()) { - $errorInfo = $stmt->errorInfo(); - self::$error = $errorInfo[2]; - self::$errorno = $errorInfo[1]; - $retval = false; - } else { - $retval = $stmt; - self::$affected_rows = $retval->rowCount(); - } - break; - case 'mysqli': - // There are SQL statements that cannot be executed with a prepared statement - $parts = explode(' ', $orig_sql); - $command = strtolower($parts[0]); - $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']); - - // The fallback routine is called as well when there are no arguments - if (!$can_be_prepared || (count($args) == 0)) { - $retval = self::$db->query(self::replaceParameters($sql, $args)); - if (self::$db->errno) { - self::$error = self::$db->error; - self::$errorno = self::$db->errno; - $retval = false; - } else { - if (isset($retval->num_rows)) { - self::$affected_rows = $retval->num_rows; - } else { - self::$affected_rows = self::$db->affected_rows; - } - } - break; - } - - $stmt = self::$db->stmt_init(); - - if (!$stmt->prepare($sql)) { - self::$error = $stmt->error; - self::$errorno = $stmt->errno; - $retval = false; - break; - } - - $param_types = ''; - $values = []; - foreach ($args AS $param => $value) { - if (is_int($args[$param])) { - $param_types .= 'i'; - } elseif (is_float($args[$param])) { - $param_types .= 'd'; - } elseif (is_string($args[$param])) { - $param_types .= 's'; - } else { - $param_types .= 'b'; - } - $values[] = &$args[$param]; - } - - if (count($values) > 0) { - array_unshift($values, $param_types); - call_user_func_array([$stmt, 'bind_param'], $values); - } - - if (!$stmt->execute()) { - self::$error = self::$db->error; - self::$errorno = self::$db->errno; - $retval = false; - } else { - $stmt->store_result(); - $retval = $stmt; - self::$affected_rows = $retval->affected_rows; - } - break; - } - - // We are having an own error logging in the function "e" - if ((self::$errorno != 0) && !$called_from_e) { - // We have to preserve the error code, somewhere in the logging it get lost - $error = self::$error; - $errorno = self::$errorno; - - logger('DB Error '.self::$errorno.': '.self::$error."\n". - System::callstack(8)."\n".self::replaceParameters($sql, $args)); - - // On a lost connection we try to reconnect - but only once. - if ($errorno == 2006) { - if (self::$in_retrial || !self::reconnect()) { - // It doesn't make sense to continue when the database connection was lost - if (self::$in_retrial) { - logger('Giving up retrial because of database error '.$errorno.': '.$error); - } else { - logger("Couldn't reconnect after database error ".$errorno.': '.$error); - } - exit(1); - } else { - // We try it again - logger('Reconnected after database error '.$errorno.': '.$error); - self::$in_retrial = true; - $ret = self::p($sql, $args); - self::$in_retrial = false; - return $ret; - } - } - - self::$error = $error; - self::$errorno = $errorno; - } - - $a->save_timestamp($stamp1, 'database'); - - if ($a->getConfigValue('system', 'db_log')) { - $stamp2 = microtime(true); - $duration = (float)($stamp2 - $stamp1); - - if (($duration > $a->getConfigValue('system', 'db_loglimit'))) { - $duration = round($duration, 3); - $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); - - @file_put_contents($a->getConfigValue('system', 'db_log'), DateTimeFormat::utcNow()."\t".$duration."\t". - basename($backtrace[1]["file"])."\t". - $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t". - substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND); - } - } - return $retval; - } - - /** - * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data - * - * Please use dba::delete, dba::insert, dba::update, ... instead - * - * @param string $sql SQL statement - * @return boolean Was the query successfull? False is returned only if an error occurred - */ - public static function e($sql) { - $a = get_app(); - - $stamp = microtime(true); - - $params = self::getParam(func_get_args()); - - // In a case of a deadlock we are repeating the query 20 times - $timeout = 20; - - do { - $stmt = self::p($sql, $params); - - if (is_bool($stmt)) { - $retval = $stmt; - } elseif (is_object($stmt)) { - $retval = true; - } else { - $retval = false; - } - - self::close($stmt); - - } while ((self::$errorno == 1213) && (--$timeout > 0)); - - if (self::$errorno != 0) { - // We have to preserve the error code, somewhere in the logging it get lost - $error = self::$error; - $errorno = self::$errorno; - - logger('DB Error '.self::$errorno.': '.self::$error."\n". - System::callstack(8)."\n".self::replaceParameters($sql, $params)); - - // On a lost connection we simply quit. - // A reconnect like in self::p could be dangerous with modifications - if ($errorno == 2006) { - logger('Giving up because of database error '.$errorno.': '.$error); - exit(1); - } - - self::$error = $error; - self::$errorno = $errorno; - } - - $a->save_timestamp($stamp, "database_write"); - - return $retval; - } - - /** - * @brief Check if data exists - * - * @param string $table Table name - * @param array $condition array of fields for condition - * - * @return boolean Are there rows for that condition? - */ - public static function exists($table, $condition) { - if (empty($table)) { - return false; - } - - $fields = []; - - reset($condition); - $first_key = key($condition); - if (!is_int($first_key)) { - $fields = [$first_key]; - } - - $stmt = self::select($table, $fields, $condition, ['limit' => 1]); - - if (is_bool($stmt)) { - $retval = $stmt; - } else { - $retval = (self::num_rows($stmt) > 0); - } - - self::close($stmt); - - return $retval; - } - - /** - * Fetches the first row - * - * Please use dba::selectFirst or dba::exists whenever this is possible. - * - * @brief Fetches the first row - * @param string $sql SQL statement - * @return array first row of query - */ - public static function fetch_first($sql) { - $params = self::getParam(func_get_args()); - - $stmt = self::p($sql, $params); - - if (is_bool($stmt)) { - $retval = $stmt; - } else { - $retval = self::fetch($stmt); - } - - self::close($stmt); - - return $retval; - } - - /** - * @brief Returns the number of affected rows of the last statement - * - * @return int Number of rows - */ - public static function affected_rows() { - return self::$affected_rows; - } - - /** - * @brief Returns the number of columns of a statement - * - * @param object Statement object - * @return int Number of columns - */ - public static function columnCount($stmt) { - if (!is_object($stmt)) { - return 0; - } - switch (self::$driver) { - case 'pdo': - return $stmt->columnCount(); - case 'mysqli': - return $stmt->field_count; - } - return 0; - } - /** - * @brief Returns the number of rows of a statement - * - * @param PDOStatement|mysqli_result|mysqli_stmt Statement object - * @return int Number of rows - */ - public static function num_rows($stmt) { - if (!is_object($stmt)) { - return 0; - } - switch (self::$driver) { - case 'pdo': - return $stmt->rowCount(); - case 'mysqli': - return $stmt->num_rows; - } - return 0; - } - - /** - * @brief Fetch a single row - * - * @param mixed $stmt statement object - * @return array current row - */ - public static function fetch($stmt) { - $a = get_app(); - - $stamp1 = microtime(true); - - $columns = []; - - if (!is_object($stmt)) { - return false; - } - - switch (self::$driver) { - case 'pdo': - $columns = $stmt->fetch(PDO::FETCH_ASSOC); - break; - case 'mysqli': - if (get_class($stmt) == 'mysqli_result') { - $columns = $stmt->fetch_assoc(); - break; - } - - // This code works, but is slow - - // Bind the result to a result array - $cols = []; - - $cols_num = []; - for ($x = 0; $x < $stmt->field_count; $x++) { - $cols[] = &$cols_num[$x]; - } - - call_user_func_array([$stmt, 'bind_result'], $cols); - - if (!$stmt->fetch()) { - return false; - } - - // The slow part: - // We need to get the field names for the array keys - // It seems that there is no better way to do this. - $result = $stmt->result_metadata(); - $fields = $result->fetch_fields(); - - foreach ($cols_num AS $param => $col) { - $columns[$fields[$param]->name] = $col; - } - } - - $a->save_timestamp($stamp1, 'database'); - - return $columns; - } - - /** - * @brief Insert a row into a table - * - * @param string $table Table name - * @param array $param parameter array - * @param bool $on_duplicate_update Do an update on a duplicate entry - * - * @return boolean was the insert successfull? - */ - public static function insert($table, $param, $on_duplicate_update = false) { - - if (empty($table) || empty($param)) { - logger('Table and fields have to be set'); - return false; - } - - $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (". - substr(str_repeat("?, ", count($param)), 0, -2).")"; - - if ($on_duplicate_update) { - $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?"; - - $values = array_values($param); - $param = array_merge_recursive($values, $values); - } - - return self::e($sql, $param); - } - - /** - * @brief Fetch the id of the last insert command - * - * @return integer Last inserted id - */ - public static function lastInsertId() { - switch (self::$driver) { - case 'pdo': - $id = self::$db->lastInsertId(); - break; - case 'mysqli': - $id = self::$db->insert_id; - break; - } - return $id; - } - - /** - * @brief Locks a table for exclusive write access - * - * This function can be extended in the future to accept a table array as well. - * - * @param string $table Table name - * - * @return boolean was the lock successful? - */ - public static function lock($table) { - // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html - if (self::$driver == 'pdo') { - self::e("SET autocommit=0"); - self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); - } else { - self::$db->autocommit(false); - } - - $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE"); - - if (self::$driver == 'pdo') { - self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); - } - - if (!$success) { - if (self::$driver == 'pdo') { - self::e("SET autocommit=1"); - } else { - self::$db->autocommit(true); - } - } else { - self::$in_transaction = true; - } - return $success; - } - - /** - * @brief Unlocks all locked tables - * - * @return boolean was the unlock successful? - */ - public static function unlock() { - // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html - self::performCommit(); - - if (self::$driver == 'pdo') { - self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); - } - - $success = self::e("UNLOCK TABLES"); - - if (self::$driver == 'pdo') { - self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); - self::e("SET autocommit=1"); - } else { - self::$db->autocommit(true); - } - - self::$in_transaction = false; - return $success; - } - - /** - * @brief Starts a transaction - * - * @return boolean Was the command executed successfully? - */ - public static function transaction() { - if (!self::performCommit()) { - return false; - } - - switch (self::$driver) { - case 'pdo': - if (self::$db->inTransaction()) { - break; - } - if (!self::$db->beginTransaction()) { - return false; - } - break; - case 'mysqli': - if (!self::$db->begin_transaction()) { - return false; - } - break; - } - - self::$in_transaction = true; - return true; - } - - private static function performCommit() - { - switch (self::$driver) { - case 'pdo': - if (!self::$db->inTransaction()) { - return true; - } - return self::$db->commit(); - case 'mysqli': - return self::$db->commit(); - } - return true; - } - - /** - * @brief Does a commit - * - * @return boolean Was the command executed successfully? - */ - public static function commit() { - if (!self::performCommit()) { - return false; - } - self::$in_transaction = false; - return true; - } - - /** - * @brief Does a rollback - * - * @return boolean Was the command executed successfully? - */ - public static function rollback() { - $ret = false; - - switch (self::$driver) { - case 'pdo': - if (!self::$db->inTransaction()) { - $ret = true; - break; - } - $ret = self::$db->rollBack(); - break; - case 'mysqli': - $ret = self::$db->rollback(); - break; - } - self::$in_transaction = false; - return $ret; - } - - /** - * @brief Build the array with the table relations - * - * The array is build from the database definitions in DBStructure.php - * - * This process must only be started once, since the value is cached. - */ - private static function buildRelationData() { - $definition = DBStructure::definition(); - - foreach ($definition AS $table => $structure) { - foreach ($structure['fields'] AS $field => $field_struct) { - if (isset($field_struct['relation'])) { - foreach ($field_struct['relation'] AS $rel_table => $rel_field) { - self::$relation[$rel_table][$rel_field][$table][] = $field; - } - } - } - } - } - - /** - * @brief Delete a row from a table - * - * @param string $table Table name - * @param array $conditions Field condition(s) - * @param array $options - * - cascade: If true we delete records in other tables that depend on the one we're deleting through - * relations (default: true) - * @param boolean $in_process Internal use: Only do a commit after the last delete - * @param array $callstack Internal use: prevent endless loops - * - * @return boolean|array was the delete successful? When $in_process is set: deletion data - */ - public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = []) - { - if (empty($table) || empty($conditions)) { - logger('Table and conditions have to be set'); - return false; - } - - $commands = []; - - // Create a key for the loop prevention - $key = $table . ':' . json_encode($conditions); - - // We quit when this key already exists in the callstack. - if (isset($callstack[$key])) { - return $commands; - } - - $callstack[$key] = true; - - $table = self::escape($table); - - $commands[$key] = ['table' => $table, 'conditions' => $conditions]; - - $cascade = defaults($options, 'cascade', true); - - // To speed up the whole process we cache the table relations - if ($cascade && count(self::$relation) == 0) { - self::buildRelationData(); - } - - // Is there a relation entry for the table? - if ($cascade && isset(self::$relation[$table])) { - // We only allow a simple "one field" relation. - $field = array_keys(self::$relation[$table])[0]; - $rel_def = array_values(self::$relation[$table])[0]; - - // Create a key for preventing double queries - $qkey = $field . '-' . $table . ':' . json_encode($conditions); - - // When the search field is the relation field, we don't need to fetch the rows - // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend - if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) { - foreach ($rel_def AS $rel_table => $rel_fields) { - foreach ($rel_fields AS $rel_field) { - $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack); - $commands = array_merge($commands, $retval); - } - } - // We quit when this key already exists in the callstack. - } elseif (!isset($callstack[$qkey])) { - - $callstack[$qkey] = true; - - // Fetch all rows that are to be deleted - $data = self::select($table, [$field], $conditions); - - while ($row = self::fetch($data)) { - // Now we accumulate the delete commands - $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack); - $commands = array_merge($commands, $retval); - } - - self::close($data); - - // Since we had split the delete command we don't need the original command anymore - unset($commands[$key]); - } - } - - if (!$in_process) { - // Now we finalize the process - $do_transaction = !self::$in_transaction; - - if ($do_transaction) { - self::transaction(); - } - - $compacted = []; - $counter = []; - - foreach ($commands AS $command) { - $conditions = $command['conditions']; - reset($conditions); - $first_key = key($conditions); - - $condition_string = self::buildCondition($conditions); - - if ((count($command['conditions']) > 1) || is_int($first_key)) { - $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string; - logger(self::replaceParameters($sql, $conditions), LOGGER_DATA); - - if (!self::e($sql, $conditions)) { - if ($do_transaction) { - self::rollback(); - } - return false; - } - } else { - $key_table = $command['table']; - $key_condition = array_keys($command['conditions'])[0]; - $value = array_values($command['conditions'])[0]; - - // Split the SQL queries in chunks of 100 values - // We do the $i stuff here to make the code better readable - $i = isset($counter[$key_table][$key_condition]) ? $counter[$key_table][$key_condition] : 0; - if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) { - ++$i; - } - - $compacted[$key_table][$key_condition][$i][$value] = $value; - $counter[$key_table][$key_condition] = $i; - } - } - foreach ($compacted AS $table => $values) { - foreach ($values AS $field => $field_value_list) { - foreach ($field_value_list AS $field_values) { - $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" . - substr(str_repeat("?, ", count($field_values)), 0, -2) . ");"; - - logger(self::replaceParameters($sql, $field_values), LOGGER_DATA); - - if (!self::e($sql, $field_values)) { - if ($do_transaction) { - self::rollback(); - } - return false; - } - } - } - } - if ($do_transaction) { - self::commit(); - } - return true; - } - - return $commands; - } - - /** - * @brief Updates rows - * - * Updates rows in the database. When $old_fields is set to an array, - * the system will only do an update if the fields in that array changed. - * - * Attention: - * Only the values in $old_fields are compared. - * This is an intentional behaviour. - * - * Example: - * We include the timestamp field in $fields but not in $old_fields. - * Then the row will only get the new timestamp when the other fields had changed. - * - * When $old_fields is set to a boolean value the system will do this compare itself. - * When $old_fields is set to "true" the system will do an insert if the row doesn't exists. - * - * Attention: - * Only set $old_fields to a boolean value when you are sure that you will update a single row. - * When you set $old_fields to "true" then $fields must contain all relevant fields! - * - * @param string $table Table name - * @param array $fields contains the fields that are updated - * @param array $condition condition array with the key values - * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate) - * - * @return boolean was the update successfull? - */ - public static function update($table, $fields, $condition, $old_fields = []) { - - if (empty($table) || empty($fields) || empty($condition)) { - logger('Table, fields and condition have to be set'); - return false; - } - - $table = self::escape($table); - - $condition_string = self::buildCondition($condition); - - if (is_bool($old_fields)) { - $do_insert = $old_fields; - - $old_fields = self::selectFirst($table, [], $condition); - - if (is_bool($old_fields)) { - if ($do_insert) { - $values = array_merge($condition, $fields); - return self::insert($table, $values, $do_insert); - } - $old_fields = []; - } - } - - $do_update = (count($old_fields) == 0); - - foreach ($old_fields AS $fieldname => $content) { - if (isset($fields[$fieldname])) { - if ($fields[$fieldname] == $content) { - unset($fields[$fieldname]); - } else { - $do_update = true; - } - } - } - - if (!$do_update || (count($fields) == 0)) { - return true; - } - - $sql = "UPDATE `".$table."` SET `". - implode("` = ?, `", array_keys($fields))."` = ?".$condition_string; - - $params1 = array_values($fields); - $params2 = array_values($condition); - $params = array_merge_recursive($params1, $params2); - - return self::e($sql, $params); - } - - /** - * Retrieve a single record from a table and returns it in an associative array - * - * @brief Retrieve a single record from a table - * @param string $table - * @param array $fields - * @param array $condition - * @param array $params - * @return bool|array - * @see dba::select - */ - public static function selectFirst($table, array $fields = [], array $condition = [], $params = []) - { - $params['limit'] = 1; - $result = self::select($table, $fields, $condition, $params); - - if (is_bool($result)) { - return $result; - } else { - $row = self::fetch($result); - self::close($result); - return $row; - } - } - - /** - * @brief Select rows from a table - * - * @param string $table Table name - * @param array $fields Array of selected fields, empty for all - * @param array $condition Array of fields for condition - * @param array $params Array of several parameters - * - * @return boolean|object - * - * Example: - * $table = "item"; - * $fields = array("id", "uri", "uid", "network"); - * - * $condition = array("uid" => 1, "network" => 'dspr'); - * or: - * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'); - * - * $params = array("order" => array("id", "received" => true), "limit" => 10); - * - * $data = dba::select($table, $fields, $condition, $params); - */ - public static function select($table, array $fields = [], array $condition = [], array $params = []) - { - if ($table == '') { - return false; - } - - $table = self::escape($table); - - if (count($fields) > 0) { - $select_fields = "`" . implode("`, `", array_values($fields)) . "`"; - } else { - $select_fields = "*"; - } - - $condition_string = self::buildCondition($condition); - - $param_string = self::buildParameter($params); - - $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string; - - $result = self::p($sql, $condition); - - return $result; - } - - /** - * @brief Counts the rows from a table satisfying the provided condition - * - * @param string $table Table name - * @param array $condition array of fields for condition - * - * @return int - * - * Example: - * $table = "item"; - * - * $condition = ["uid" => 1, "network" => 'dspr']; - * or: - * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr']; - * - * $count = dba::count($table, $condition); - */ - public static function count($table, array $condition = []) - { - if ($table == '') { - return false; - } - - $condition_string = self::buildCondition($condition); - - $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string; - - $row = self::fetch_first($sql, $condition); - - return $row['count']; - } - - /** - * @brief Returns the SQL condition string built from the provided condition array - * - * This function operates with two modes. - * - Supplied with a filed/value associative array, it builds simple strict - * equality conditions linked by AND. - * - Supplied with a flat list, the first element is the condition string and - * the following arguments are the values to be interpolated - * - * $condition = ["uid" => 1, "network" => 'dspr']; - * or: - * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr']; - * - * In either case, the provided array is left with the parameters only - * - * @param array $condition - * @return string - */ - public static function buildCondition(array &$condition = []) - { - $condition_string = ''; - if (count($condition) > 0) { - reset($condition); - $first_key = key($condition); - if (is_int($first_key)) { - $condition_string = " WHERE (" . array_shift($condition) . ")"; - } else { - $new_values = []; - $condition_string = ""; - foreach ($condition as $field => $value) { - if ($condition_string != "") { - $condition_string .= " AND "; - } - if (is_array($value)) { - /* Workaround for MySQL Bug #64791. - * Never mix data types inside any IN() condition. - * In case of mixed types, cast all as string. - * Logic needs to be consistent with dba::p() data types. - */ - $is_int = false; - $is_alpha = false; - foreach ($value as $single_value) { - if (is_int($single_value)) { - $is_int = true; - } else { - $is_alpha = true; - } - } - - if ($is_int && $is_alpha) { - foreach ($value as &$ref) { - if (is_int($ref)) { - $ref = (string)$ref; - } - } - unset($ref); //Prevent accidental re-use. - } - - $new_values = array_merge($new_values, array_values($value)); - $placeholders = substr(str_repeat("?, ", count($value)), 0, -2); - $condition_string .= "`" . $field . "` IN (" . $placeholders . ")"; - } else { - $new_values[$field] = $value; - $condition_string .= "`" . $field . "` = ?"; - } - } - $condition_string = " WHERE (" . $condition_string . ")"; - $condition = $new_values; - } - } - - return $condition_string; - } - - /** - * @brief Returns the SQL parameter string built from the provided parameter array - * - * @param array $params - * @return string - */ - public static function buildParameter(array $params = []) - { - $order_string = ''; - if (isset($params['order'])) { - $order_string = " ORDER BY "; - foreach ($params['order'] AS $fields => $order) { - if (!is_int($fields)) { - $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", "; - } else { - $order_string .= "`" . $order . "`, "; - } - } - $order_string = substr($order_string, 0, -2); - } - - $limit_string = ''; - if (isset($params['limit']) && is_int($params['limit'])) { - $limit_string = " LIMIT " . $params['limit']; - } - - if (isset($params['limit']) && is_array($params['limit'])) { - $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]); - } - - return $order_string.$limit_string; - } - - /** - * @brief Fills an array with data from a query - * - * @param object $stmt statement object - * @return array Data array - */ - public static function inArray($stmt, $do_close = true) { - if (is_bool($stmt)) { - return $stmt; - } - - $data = []; - while ($row = self::fetch($stmt)) { - $data[] = $row; - } - if ($do_close) { - self::close($stmt); - } - return $data; - } - - /** - * @brief Returns the error number of the last query - * - * @return string Error number (0 if no error) - */ - public static function errorNo() { - return self::$errorno; - } - - /** - * @brief Returns the error message of the last query - * - * @return string Error message ('' if no error) - */ - public static function errorMessage() { - return self::$error; - } - - /** - * @brief Closes the current statement - * - * @param object $stmt statement object - * @return boolean was the close successful? - */ - public static function close($stmt) { - $a = get_app(); - - $stamp1 = microtime(true); - - if (!is_object($stmt)) { - return false; - } - - switch (self::$driver) { - case 'pdo': - $ret = $stmt->closeCursor(); - break; - case 'mysqli': - // MySQLi offers both a mysqli_stmt and a mysqli_result class. - // We should be careful not to assume the object type of $stmt - // because dba::p() has been able to return both types. - if ($stmt instanceof mysqli_stmt) { - $stmt->free_result(); - $ret = $stmt->close(); - } elseif ($stmt instanceof mysqli_result) { - $stmt->free(); - $ret = true; - } else { - $ret = false; - } - break; - } - - $a->save_timestamp($stamp1, 'database'); - - return $ret; - } -} +use Friendica\Database\dba; function dbesc($str) { if (dba::$connected) { From 9c70a9458906f69db69301cefd78043b70478f89 Mon Sep 17 00:00:00 2001 From: Hypolite Petovan Date: Thu, 19 Jul 2018 22:24:03 -0400 Subject: [PATCH 4/4] Add missing PDO* use statements in Database\dba --- src/Database/DBA.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Database/DBA.php b/src/Database/DBA.php index 28eedec151..5635beb330 100644 --- a/src/Database/DBA.php +++ b/src/Database/DBA.php @@ -8,6 +8,9 @@ namespace Friendica\Database; use Friendica\Core\System; use Friendica\Util\DateTimeFormat; +use PDO; +use PDOException; +use PDOStatement; /** * @class MySQL database class