friendica/include/dba.php

1383 lines
35 KiB
PHP
Raw Normal View History

2010-07-02 01:48:07 +02:00
<?php
use Friendica\App;
use Friendica\Core\L10n;
2017-12-14 22:13:02 +01:00
use Friendica\Core\System;
2017-11-08 04:57:46 +01:00
use Friendica\Database\DBM;
2017-12-14 22:13:02 +01:00
use Friendica\Database\DBStructure;
use Friendica\Util\DateTimeFormat;
2017-08-26 12:01:50 +02:00
/**
* @class MySQL database class
*
2017-04-25 18:05:26 +02:00
* This class is for the low level database stuff that does driver specific things.
*/
class dba {
public static $connected = false;
2017-10-11 14:56:36 +02:00
private static $_server_info = '';
private static $db;
private static $driver;
private static $error = false;
private static $errorno = 0;
private static $affected_rows = 0;
2017-05-11 22:19:43 +02:00
private static $in_transaction = false;
private static $relation = [];
public static function connect($serveraddr, $user, $pass, $db) {
2017-10-11 14:56:36 +02:00
if (!is_null(self::$db)) {
return true;
}
$a = get_app();
$stamp1 = microtime(true);
$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);
if (!(strlen($server) && strlen($user))) {
2017-10-11 14:56:36 +02:00
return false;
}
2012-05-20 00:11:32 +02:00
if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
2017-10-11 14:56:36 +02:00
self::$driver = 'pdo';
$connect = "mysql:host=".$server.";dbname=".$db;
if (isset($port)) {
$connect .= ";port=".$port;
}
if (isset($a->config["system"]["db_charset"])) {
$connect .= ";charset=".$a->config["system"]["db_charset"];
}
2017-08-04 11:01:29 +02:00
try {
2017-10-11 14:56:36 +02:00
self::$db = @new PDO($connect, $user, $pass);
self::$connected = true;
2017-08-04 11:01:29 +02:00
} catch (PDOException $e) {
}
}
2017-10-11 14:56:36 +02:00
if (!self::$connected && class_exists('mysqli')) {
self::$driver = 'mysqli';
self::$db = @new mysqli($server, $user, $pass, $db, $port);
if (!mysqli_connect_errno()) {
2017-10-11 14:56:36 +02:00
self::$connected = true;
if (isset($a->config["system"]["db_charset"])) {
2017-10-11 14:56:36 +02:00
self::$db->set_charset($a->config["system"]["db_charset"]);
}
}
}
// No suitable SQL driver was found.
2017-10-11 14:56:36 +02:00
if (!self::$connected) {
self::$driver = null;
2017-10-11 14:56:36 +02:00
self::$db = null;
}
$a->save_timestamp($stamp1, "network");
return self::$connected;
}
2018-04-09 21:23:41 +02:00
/**
* Return the database object.
* @return PDO|mysqli
*/
public static function get_db()
{
return self::$db;
}
2016-10-07 14:33:13 +02:00
/**
* @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
*/
2017-10-11 14:56:36 +02:00
public static function server_info() {
if (self::$_server_info == '') {
switch (self::$driver) {
case 'pdo':
2017-10-11 14:56:36 +02:00
self::$_server_info = self::$db->getAttribute(PDO::ATTR_SERVER_VERSION);
break;
case 'mysqli':
2017-10-11 14:56:36 +02:00
self::$_server_info = self::$db->server_info;
break;
}
}
2017-10-11 14:56:36 +02:00
return self::$_server_info;
}
/**
* @brief Returns the selected database name
*
* @return string
*/
2017-10-11 14:56:36 +02:00
public static function database_name() {
$ret = self::p("SELECT DATABASE() AS `db`");
$data = self::inArray($ret);
return $data[0]['db'];
}
2017-01-21 21:15:49 +01:00
/**
* @brief Analyze a database query and log this if some conditions are met.
*
* @param string $query The database query that will be analyzed
*/
2018-03-04 00:02:45 +01:00
private static function logIndex($query) {
$a = get_app();
if (empty($a->config["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;
}
2017-10-11 14:56:36 +02:00
$r = self::p("EXPLAIN ".$query);
2017-11-08 04:57:46 +01:00
if (!DBM::is_result($r)) {
return;
}
$watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
$blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
2017-10-11 14:56:36 +02:00
while ($row = dba::fetch($r)) {
if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
$log = (in_array($row['key'], $watchlist) &&
($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
} else {
$log = false;
}
if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["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->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
2017-01-15 13:36:06 +01:00
$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);
}
}
}
2017-10-11 14:56:36 +02:00
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);
}
}
2010-07-02 01:48:07 +02:00
2017-10-11 14:56:36 +02:00
public static function connected() {
$connected = false;
2017-10-11 14:56:36 +02:00
switch (self::$driver) {
case 'pdo':
$r = dba::p("SELECT 1");
2017-11-08 04:57:46 +01:00
if (DBM::is_result($r)) {
$row = dba::inArray($r);
$connected = ($row[0]['1'] == '1');
}
break;
case 'mysqli':
2017-10-11 14:56:36 +02:00
$connected = self::$db->ping();
break;
}
2016-09-22 04:57:40 +02:00
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.
*/
2017-10-11 14:56:36 +02:00
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;
}
/**
2017-05-16 08:00:01 +02:00
* @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.
*/
2017-10-11 14:56:36 +02:00
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;
}
2017-04-25 07:20:34 +02:00
/**
* @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
*/
2018-03-04 00:02:45 +01:00
private static function replaceParameters($sql, $args) {
2017-04-25 07:20:34 +02:00
$offset = 0;
foreach ($args AS $param => $value) {
if (is_int($args[$param]) || is_float($args[$param])) {
2017-04-25 07:20:34 +02:00
$replace = intval($args[$param]);
} else {
2017-10-11 14:56:36 +02:00
$replace = "'".self::escape($args[$param])."'";
2017-04-25 07:20:34 +02:00
}
$pos = strpos($sql, '?', $offset);
if ($pos !== false) {
$sql = substr_replace($sql, $replace, $pos, 1);
}
$offset = $pos + strlen($replace);
}
return $sql;
}
2017-08-10 14:38:32 +02:00
/**
* @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;
}
}
/**
2017-04-25 07:11:04 +02:00
* @brief Executes a prepared statement that returns data
* @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
2017-09-15 08:07:34 +02:00
*
* Please only use it with complicated queries.
* For all regular queries please use dba::select or dba::exists
*
* @param string $sql SQL statement
2018-01-10 04:20:58 +01:00
* @return bool|object statement object
*/
public static function p($sql) {
$a = get_app();
$stamp1 = microtime(true);
2017-08-10 14:38:32 +02:00
$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;
}
2017-10-11 14:56:36 +02:00
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);
}
2017-10-11 14:56:36 +02:00
$sql = self::clean_query($sql);
$sql = self::any_value_fallback($sql);
$orig_sql = $sql;
if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
2017-08-26 12:01:50 +02:00
$sql = "/*".System::callstack()." */ ".$sql;
}
2017-10-11 14:56:36 +02:00
self::$error = '';
self::$errorno = 0;
self::$affected_rows = 0;
// We have to make some things different if this function is called from "e"
2017-08-10 14:38:32 +02:00
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
2017-08-10 14:38:32 +02:00
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');
2017-10-11 14:56:36 +02:00
switch (self::$driver) {
case 'pdo':
// If there are no arguments we use "query"
if (count($args) == 0) {
2017-10-11 14:56:36 +02:00
if (!$retval = self::$db->query($sql)) {
$errorInfo = self::$db->errorInfo();
self::$error = $errorInfo[2];
self::$errorno = $errorInfo[1];
$retval = false;
break;
}
2017-10-11 14:56:36 +02:00
self::$affected_rows = $retval->rowCount();
break;
}
2017-10-11 14:56:36 +02:00
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) {
$stmt->bindParam($param, $args[$param]);
}
if (!$stmt->execute()) {
$errorInfo = $stmt->errorInfo();
2017-10-11 14:56:36 +02:00
self::$error = $errorInfo[2];
self::$errorno = $errorInfo[1];
$retval = false;
} else {
$retval = $stmt;
2017-10-11 14:56:36 +02:00
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)) {
2018-03-04 00:02:45 +01:00
$retval = self::$db->query(self::replaceParameters($sql, $args));
2017-10-11 14:56:36 +02:00
if (self::$db->errno) {
self::$error = self::$db->error;
self::$errorno = self::$db->errno;
$retval = false;
} else {
if (isset($retval->num_rows)) {
2017-10-11 14:56:36 +02:00
self::$affected_rows = $retval->num_rows;
} else {
2017-10-11 14:56:36 +02:00
self::$affected_rows = self::$db->affected_rows;
}
}
break;
}
2017-10-11 14:56:36 +02:00
$stmt = self::$db->stmt_init();
if (!$stmt->prepare($sql)) {
2017-10-11 14:56:36 +02:00
self::$error = $stmt->error;
self::$errorno = $stmt->errno;
$retval = false;
break;
}
$params = '';
$values = [];
foreach ($args AS $param => $value) {
if (is_int($args[$param])) {
$params .= 'i';
} elseif (is_float($args[$param])) {
$params .= 'd';
} elseif (is_string($args[$param])) {
$params .= 's';
} else {
$params .= 'b';
}
$values[] = &$args[$param];
}
if (count($values) > 0) {
array_unshift($values, $params);
call_user_func_array([$stmt, 'bind_param'], $values);
}
if (!$stmt->execute()) {
2017-10-11 14:56:36 +02:00
self::$error = self::$db->error;
self::$errorno = self::$db->errno;
$retval = false;
} else {
2017-04-24 22:32:35 +02:00
$stmt->store_result();
$retval = $stmt;
2017-10-11 14:56:36 +02:00
self::$affected_rows = $retval->affected_rows;
}
break;
}
// We are having an own error logging in the function "e"
2017-10-11 14:56:36 +02:00
if ((self::$errorno != 0) && !$called_from_e) {
// We have to preserve the error code, somewhere in the logging it get lost
2017-10-11 14:56:36 +02:00
$error = self::$error;
$errorno = self::$errorno;
2017-06-13 07:52:59 +02:00
2017-10-11 14:56:36 +02:00
logger('DB Error '.self::$errorno.': '.self::$error."\n".
2018-03-04 00:02:45 +01:00
System::callstack(8)."\n".self::replaceParameters($sql, $params));
2017-06-13 07:52:59 +02:00
2017-10-11 14:56:36 +02:00
self::$error = $error;
self::$errorno = $errorno;
}
$a->save_timestamp($stamp1, 'database');
2017-04-24 23:20:24 +02:00
if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
$stamp2 = microtime(true);
$duration = (float)($stamp2 - $stamp1);
2017-04-24 23:20:24 +02:00
if (($duration > $a->config["system"]["db_loglimit"])) {
$duration = round($duration, 3);
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
2017-04-25 07:20:34 +02:00
@file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
2017-04-24 23:20:24 +02:00
basename($backtrace[1]["file"])."\t".
$backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
2018-03-04 00:02:45 +01:00
substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
2017-04-24 23:20:24 +02:00
}
}
return $retval;
}
/**
2017-04-25 07:11:04 +02:00
* @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
*
2017-09-15 08:07:34 +02:00
* Please use dba::delete, dba::insert, dba::update, ... instead
*
* @param string $sql SQL statement
2017-04-25 07:11:04 +02:00
* @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);
2017-08-10 14:38:32 +02:00
$params = self::getParam(func_get_args());
2017-06-13 11:03:19 +02:00
// In a case of a deadlock we are repeating the query 20 times
$timeout = 20;
2017-06-13 07:52:59 +02:00
do {
2017-08-10 14:38:32 +02:00
$stmt = self::p($sql, $params);
2017-06-13 07:52:59 +02:00
if (is_bool($stmt)) {
$retval = $stmt;
} elseif (is_object($stmt)) {
$retval = true;
} else {
$retval = false;
}
self::close($stmt);
2017-10-11 14:56:36 +02:00
} while ((self::$errorno == 1213) && (--$timeout > 0));
2017-06-13 07:52:59 +02:00
2017-10-11 14:56:36 +02:00
if (self::$errorno != 0) {
2017-06-13 07:52:59 +02:00
// We have to preserve the error code, somewhere in the logging it get lost
2017-10-11 14:56:36 +02:00
$error = self::$error;
$errorno = self::$errorno;
2017-10-11 14:56:36 +02:00
logger('DB Error '.self::$errorno.': '.self::$error."\n".
2018-03-04 00:02:45 +01:00
System::callstack(8)."\n".self::replaceParameters($sql, $params));
2017-06-13 07:52:59 +02:00
2017-10-11 14:56:36 +02:00
self::$error = $error;
self::$errorno = $errorno;
2017-06-13 07:52:59 +02:00
}
$a->save_timestamp($stamp, "database_write");
return $retval;
}
/**
* @brief Check if data exists
*
2017-08-12 10:55:50 +02:00
* @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) {
2017-08-12 10:55:50 +02:00
if (empty($table)) {
return false;
}
$fields = [];
2018-03-04 00:02:45 +01:00
reset($condition);
$first_key = key($condition);
if (!is_int($first_key)) {
$fields = [$first_key];
}
2017-08-12 10:55:50 +02:00
$stmt = self::select($table, $fields, $condition, ['limit' => 1]);
if (is_bool($stmt)) {
$retval = $stmt;
} else {
2017-04-27 22:38:46 +02:00
$retval = (self::num_rows($stmt) > 0);
}
self::close($stmt);
return $retval;
}
/**
2018-01-10 04:20:58 +01:00
* Fetches the first row
*
* Please use dba::selectFirst or dba::exists whenever this is possible.
2017-09-15 08:07:34 +02:00
*
2018-01-10 04:20:58 +01:00
* @brief Fetches the first row
2017-04-27 22:38:46 +02:00
* @param string $sql SQL statement
* @return array first row of query
*/
public static function fetch_first($sql) {
2017-08-10 14:38:32 +02:00
$params = self::getParam(func_get_args());
2017-04-27 22:38:46 +02:00
2017-08-10 14:38:32 +02:00
$stmt = self::p($sql, $params);
2017-04-27 22:38:46 +02:00
if (is_bool($stmt)) {
$retval = $stmt;
} else {
$retval = self::fetch($stmt);
}
self::close($stmt);
return $retval;
}
2017-06-13 23:56:50 +02:00
/**
* @brief Returns the number of affected rows of the last statement
*
* @return int Number of rows
*/
public static function affected_rows() {
2017-10-11 14:56:36 +02:00
return self::$affected_rows;
2017-06-13 23:56:50 +02:00
}
/**
* @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;
}
2017-10-11 14:56:36 +02:00
switch (self::$driver) {
case 'pdo':
return $stmt->columnCount();
case 'mysqli':
return $stmt->field_count;
}
return 0;
}
2017-04-24 22:32:35 +02:00
/**
2017-04-24 23:23:00 +02:00
* @brief Returns the number of rows of a statement
2017-04-24 22:32:35 +02:00
*
2018-01-10 04:20:58 +01:00
* @param PDOStatement|mysqli_result|mysqli_stmt Statement object
2017-04-24 22:32:35 +02:00
* @return int Number of rows
*/
public static function num_rows($stmt) {
if (!is_object($stmt)) {
return 0;
}
2017-10-11 14:56:36 +02:00
switch (self::$driver) {
2017-04-24 22:32:35 +02:00
case 'pdo':
return $stmt->rowCount();
case 'mysqli':
return $stmt->num_rows;
}
return 0;
}
/**
* @brief Fetch a single row
*
* @param mixed $stmt statement object