Merge pull request #5418 from MrPetovan/task/5410-move-dba-to-src

Move \dba to \Friendica\Database\dba
This commit is contained in:
Michael Vogel 2018-07-20 06:50:36 +02:00 committed by GitHub
commit 4e44b07dfe
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
130 changed files with 1788 additions and 1779 deletions

View file

@ -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)) {

View file

@ -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;

View file

@ -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']];

View file

@ -1,1525 +1,6 @@
<?php
// Do not use Core\Config in this class at risk of infinite loop.
// Please use App->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) {

View file

@ -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" => []];

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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);

View file

@ -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;

View file

@ -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';

View file

@ -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;

View file

@ -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;

View file

@ -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)

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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';

View file

@ -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;

View file

@ -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;

View file

@ -7,12 +7,13 @@
* Author: Rabuzarus <https://github.com/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)
{

View file

@ -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;

View file

@ -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);
}

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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';

View file

@ -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;

View file

@ -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)
{

View file

@ -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)

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -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;

View file

@ -1,6 +1,7 @@
<?php
use Friendica\App;
use Friendica\Database\dba;
use Friendica\Database\DBM;
use Friendica\Protocol\OStatus;

View file

@ -3,9 +3,10 @@
use Friendica\App;
use Friendica\Core\Config;
use Friendica\Core\System;
use Friendica\Database\dba;
use Friendica\Database\DBM;
use Friendica\Util\Network;
use Friendica\Model\PushSubscriber;
use Friendica\Util\Network;
function post_var($name) {
return (x($_POST, $name)) ? notags(trim($_POST[$name])) : '';

View file

@ -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\Protocol\Diaspora;

View file

@ -3,6 +3,7 @@
use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Database\dba;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\Profile;

View file

@ -8,6 +8,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\User;
use Friendica\Module\Login;

View file

@ -7,6 +7,7 @@ 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;

View file

@ -2,6 +2,7 @@
/**
* @file mod/search.php
*/
use Friendica\App;
use Friendica\Content\Feature;
use Friendica\Content\Nav;
@ -9,6 +10,7 @@ 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\Model\Item;

View file

@ -14,6 +14,7 @@ use Friendica\Core\PConfig;
use Friendica\Core\System;
use Friendica\Core\Theme;
use Friendica\Core\Worker;
use Friendica\Database\dba;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\GContact;

View file

@ -2,15 +2,16 @@
/**
* @file mod/suggest.php
*/
use Friendica\App;
use Friendica\Content\ContactSelector;
use Friendica\Content\Widget;
use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Database\dba;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\GContact;
use Friendica\Model\Profile;
function suggest_init(App $a) {
if (! local_user()) {

View file

@ -2,9 +2,11 @@
/**
* @file mod/unfollow.php
*/
use Friendica\App;
use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Database\dba;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\Profile;

View file

@ -7,6 +7,7 @@ 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\Util\DateTimeFormat;
use Friendica\Util\Mimetype;

View file

@ -6,6 +6,7 @@
use Friendica\Core\Config;
use Friendica\Core\Worker;
use Friendica\Database\dba;
use Friendica\Util\DateTimeFormat;
function worker_init()

View file

@ -2,9 +2,11 @@
/**
* @file mod/xrd.php
*/
use Friendica\App;
use Friendica\Core\Addon;
use Friendica\Core\System;
use Friendica\Database\dba;
use Friendica\Database\DBM;
use Friendica\Protocol\Salmon;

View file

@ -4,16 +4,14 @@
*/
namespace Friendica;
use Detection\MobileDetect;
use Exception;
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 dba;
use Detection\MobileDetect;
use Exception;
require_once 'boot.php';
require_once 'include/dba.php';
@ -492,13 +490,13 @@ class App
$this->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');

View file

@ -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

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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

View file

@ -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) {

View file

@ -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;

View file

@ -1,8 +1,8 @@
<?php
namespace Friendica\Core\Config;
use dba;
use Friendica\BaseObject;
use Friendica\Database\dba;
use Friendica\Database\DBM;
require_once 'include/dba.php';

View file

@ -1,8 +1,8 @@
<?php
namespace Friendica\Core\Config;
use dba;
use Friendica\BaseObject;
use Friendica\Database\dba;
use Friendica\Database\DBM;
require_once 'include/dba.php';

View file

@ -2,10 +2,9 @@
namespace Friendica\Core\Config;
use dba;
use Exception;
use Friendica\App;
use Friendica\BaseObject;
use Friendica\Database\dba;
use Friendica\Database\DBM;
require_once 'include/dba.php';

View file

@ -2,10 +2,9 @@
namespace Friendica\Core\Config;
use dba;
use Exception;
use Friendica\App;
use Friendica\BaseObject;
use Friendica\Database\dba;
use Friendica\Database\DBM;
require_once 'include/dba.php';

View file

@ -2,8 +2,10 @@
namespace Friendica\Core\Console;
use Friendica\App;
use Friendica\Core\L10n;
use dba;
use Friendica\Database\dba;
use RuntimeException;
/**
* @brief tool to archive a contact on the server
@ -55,19 +57,19 @@ HELP;
}
if ($a->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;

View file

@ -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';

View file

@ -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');
}

View file

@ -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();

View file

@ -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;

View file

@ -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.'));

View file

@ -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

View file

@ -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;

View file

@ -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';

View file

@ -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';

View file

@ -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";

View file

@ -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;

1525
src/Database/DBA.php Normal file
View file

@ -0,0 +1,1525 @@
<?php
namespace Friendica\Database;
// Do not use Core\Config in this class at risk of infinite loop.
// Please use App->getConfigVariable() instead.
//use Friendica\Core\Config;
use Friendica\Core\System;
use Friendica\Util\DateTimeFormat;
use PDO;
use PDOException;
use PDOStatement;
/**
* @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;
}
}

View file

@ -4,7 +4,6 @@
*/
namespace Friendica\Database;
use dba;
use Friendica\Util\DateTimeFormat;
require_once 'include/dba.php';

View file

@ -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;
}

View file

@ -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';

View file

@ -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';

View file

@ -4,8 +4,8 @@
*/
namespace Friendica\Model;
use Friendica\Database\dba;
use Friendica\Database\DBM;
use dba;
require_once "include/dba.php";

View file

@ -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;

View file

@ -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';

View file

@ -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';

View file

@ -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);

View file

@ -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';

View file

@ -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
*/

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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;

View file

@ -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';

View file

@ -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';

View file

@ -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.
*

View file

@ -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

View file

@ -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;

View file

@ -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;

View file

@ -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';

View file

@ -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';

View file

@ -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;

View file

@ -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';

View file

@ -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';

View file

@ -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;

View file

@ -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';

View file

@ -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';

View file

@ -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

View file

@ -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';

View file

@ -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)) {

View file

@ -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 == '') {

View file

@ -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';

View file

@ -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';

View file

@ -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
{

View file

@ -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';

View file

@ -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);

View file

@ -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';

View file

@ -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)) {

View file

@ -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';

View file

@ -5,8 +5,7 @@
*/
namespace Friendica\Worker;
use Friendica\Core\Config;
use dba;
use Friendica\Database\dba;
require_once 'include/dba.php';

View file

@ -2,7 +2,7 @@
namespace Friendica\Worker;
use dba;
use Friendica\Database\dba;
class TagUpdate
{

View file

@ -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.

View file

@ -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
{

View file

@ -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';