2 use \Friendica\Core\System;
4 require_once("dbm.php");
5 require_once('include/datetime.php');
8 * @class MySQL database class
10 * This class is for the low level database stuff that does driver specific things.
19 public $connected = false;
20 public $error = false;
22 public $affected_rows = 0;
23 private $_server_info = '';
24 private static $in_transaction = false;
26 private static $relation = array();
28 function __construct($serveraddr, $user, $pass, $db, $install = false) {
31 $stamp1 = microtime(true);
33 $serveraddr = trim($serveraddr);
35 $serverdata = explode(':', $serveraddr);
36 $server = $serverdata[0];
38 if (count($serverdata) > 1) {
39 $port = trim($serverdata[1]);
42 $server = trim($server);
47 if (!(strlen($server) && strlen($user))) {
48 $this->connected = false;
54 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
55 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
56 $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
57 $this->connected = false;
64 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
65 $this->driver = 'pdo';
66 $connect = "mysql:host=".$server.";dbname=".$db;
69 $connect .= ";port=".$port;
72 if (isset($a->config["system"]["db_charset"])) {
73 $connect .= ";charset=".$a->config["system"]["db_charset"];
76 $this->db = @new PDO($connect, $user, $pass);
77 $this->connected = true;
78 } catch (PDOException $e) {
79 $this->connected = false;
83 if (!$this->connected && class_exists('mysqli')) {
84 $this->driver = 'mysqli';
85 $this->db = @new mysqli($server, $user, $pass, $db, $port);
86 if (!mysqli_connect_errno()) {
87 $this->connected = true;
89 if (isset($a->config["system"]["db_charset"])) {
90 $this->db->set_charset($a->config["system"]["db_charset"]);
95 if (!$this->connected && function_exists('mysql_connect')) {
96 $this->driver = 'mysql';
97 $this->db = mysql_connect($serveraddr, $user, $pass);
98 if ($this->db && mysql_select_db($db, $this->db)) {
99 $this->connected = true;
101 if (isset($a->config["system"]["db_charset"])) {
102 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
107 // No suitable SQL driver was found.
108 if (!$this->connected) {
111 system_unavailable();
114 $a->save_timestamp($stamp1, "network");
120 * @brief Checks if the database object is initialized
122 * This is a possible bugfix for something that doesn't occur for me.
123 * There seems to be situations, where the object isn't initialized.
125 private static function initialize() {
126 if (!is_object(self::$dbo)) {
129 if (!is_object(self::$dbo)) {
130 die('Database is uninitialized!');
136 * @brief Returns the MySQL server version string
138 * This function discriminate between the deprecated mysql API and the current
139 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
143 public function server_info() {
144 if ($this->_server_info == '') {
145 switch ($this->driver) {
147 $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
150 $this->_server_info = $this->db->server_info;
153 $this->_server_info = mysql_get_server_info($this->db);
157 return $this->_server_info;
161 * @brief Returns the selected database name
165 public function database_name() {
166 $r = $this->q("SELECT DATABASE() AS `db`");
172 * @brief Analyze a database query and log this if some conditions are met.
174 * @param string $query The database query that will be analyzed
176 public function log_index($query) {
179 if (empty($a->config["system"]["db_log_index"])) {
183 // Don't explain an explain statement
184 if (strtolower(substr($query, 0, 7)) == "explain") {
188 // Only do the explain on "select", "update" and "delete"
189 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
193 $r = $this->q("EXPLAIN ".$query);
194 if (!dbm::is_result($r)) {
198 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
199 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
201 foreach ($r AS $row) {
202 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
203 $log = (in_array($row['key'], $watchlist) &&
204 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
209 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
213 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
218 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
219 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
220 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
221 basename($backtrace[1]["file"])."\t".
222 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
223 substr($query, 0, 2000)."\n", FILE_APPEND);
229 * @brief execute SQL query - deprecated
231 * Please use the dba:: functions instead:
232 * dba::select, dba::exists, dba::insert
233 * dba::delete, dba::update, dba::p, dba::e
235 * @param string $sql SQL query
236 * @return array Query array
238 public function q($sql) {
239 $ret = self::p($sql);
245 $columns = self::columnCount($ret);
247 $data = self::inArray($ret);
249 if ((count($data) == 0) && ($columns == 0)) {
256 public function escape($str) {
257 if ($this->db && $this->connected) {
258 switch ($this->driver) {
260 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
262 return @$this->db->real_escape_string($str);
264 return @mysql_real_escape_string($str,$this->db);
269 function connected() {
270 switch ($this->driver) {
272 // Not sure if this really is working like expected
273 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
276 $connected = $this->db->ping();
279 $connected = mysql_ping($this->db);
285 function __destruct() {
287 switch ($this->driver) {
295 mysql_close($this->db);
302 * @brief Replaces ANY_VALUE() function by MIN() function,
303 * if the database server does not support ANY_VALUE().
305 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
306 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
307 * A standard fall-back is to use MIN().
309 * @param string $sql An SQL string without the values
310 * @return string The input SQL string modified if necessary.
312 public function any_value_fallback($sql) {
313 $server_info = $this->server_info();
314 if (version_compare($server_info, '5.7.5', '<') ||
315 (stripos($server_info, 'MariaDB') !== false)) {
316 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
322 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
324 * This is safe when we bind the parameters later.
325 * The parameter values aren't part of the SQL.
327 * @param string $sql An SQL string without the values
328 * @return string The input SQL string modified if necessary.
330 public function clean_query($sql) {
331 $search = array("\t", "\n", "\r", " ");
332 $replace = array(' ', ' ', ' ', ' ');
335 $sql = str_replace($search, $replace, $sql);
336 } while ($oldsql != $sql);
343 * @brief Replaces the ? placeholders with the parameters in the $args array
345 * @param string $sql SQL query
346 * @param array $args The parameters that are to replace the ? placeholders
347 * @return string The replaced SQL query
349 private static function replace_parameters($sql, $args) {
351 foreach ($args AS $param => $value) {
352 if (is_int($args[$param]) || is_float($args[$param])) {
353 $replace = intval($args[$param]);
355 $replace = "'".self::$dbo->escape($args[$param])."'";
358 $pos = strpos($sql, '?', $offset);
359 if ($pos !== false) {
360 $sql = substr_replace($sql, $replace, $pos, 1);
362 $offset = $pos + strlen($replace);
368 * @brief Convert parameter array to an universal form
369 * @param array $args Parameter array
370 * @return array universalized parameter array
372 private static function getParam($args) {
375 // When the second function parameter is an array then use this as the parameter array
376 if ((count($args) > 0) && (is_array($args[1]))) {
384 * @brief Executes a prepared statement that returns data
385 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
387 * Please only use it with complicated queries.
388 * For all regular queries please use dba::select or dba::exists
390 * @param string $sql SQL statement
391 * @return object statement object
393 public static function p($sql) {
398 $stamp1 = microtime(true);
400 $params = self::getParam(func_get_args());
402 // Renumber the array keys to be sure that they fit
405 foreach ($params AS $param) {
406 // Avoid problems with some MySQL servers and boolean values. See issue #3645
407 if (is_bool($param)) {
408 $param = (int)$param;
410 $args[++$i] = $param;
413 if (!self::$dbo || !self::$dbo->connected) {
417 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
418 // Question: Should we continue or stop the query here?
419 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
422 $sql = self::$dbo->clean_query($sql);
423 $sql = self::$dbo->any_value_fallback($sql);
427 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
428 $sql = "/*".System::callstack()." */ ".$sql;
431 self::$dbo->error = '';
432 self::$dbo->errorno = 0;
433 self::$dbo->affected_rows = 0;
435 // We have to make some things different if this function is called from "e"
436 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
438 if (isset($trace[1])) {
439 $called_from = $trace[1];
441 // We use just something that is defined to avoid warnings
442 $called_from = $trace[0];
444 // We are having an own error logging in the function "e"
445 $called_from_e = ($called_from['function'] == 'e');
447 switch (self::$dbo->driver) {
449 // If there are no arguments we use "query"
450 if (count($args) == 0) {
451 if (!$retval = self::$dbo->db->query($sql)) {
452 $errorInfo = self::$dbo->db->errorInfo();
453 self::$dbo->error = $errorInfo[2];
454 self::$dbo->errorno = $errorInfo[1];
458 self::$dbo->affected_rows = $retval->rowCount();
462 if (!$stmt = self::$dbo->db->prepare($sql)) {
463 $errorInfo = self::$dbo->db->errorInfo();
464 self::$dbo->error = $errorInfo[2];
465 self::$dbo->errorno = $errorInfo[1];
470 foreach ($args AS $param => $value) {
471 $stmt->bindParam($param, $args[$param]);
474 if (!$stmt->execute()) {
475 $errorInfo = $stmt->errorInfo();
476 self::$dbo->error = $errorInfo[2];
477 self::$dbo->errorno = $errorInfo[1];
481 self::$dbo->affected_rows = $retval->rowCount();
485 // There are SQL statements that cannot be executed with a prepared statement
486 $parts = explode(' ', $orig_sql);
487 $command = strtolower($parts[0]);
488 $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
490 // The fallback routine is called as well when there are no arguments
491 if (!$can_be_prepared || (count($args) == 0)) {
492 $retval = self::$dbo->db->query(self::replace_parameters($sql, $args));
493 if (self::$dbo->db->errno) {
494 self::$dbo->error = self::$dbo->db->error;
495 self::$dbo->errorno = self::$dbo->db->errno;
498 if (isset($retval->num_rows)) {
499 self::$dbo->affected_rows = $retval->num_rows;
501 self::$dbo->affected_rows = self::$dbo->db->affected_rows;
507 $stmt = self::$dbo->db->stmt_init();
509 if (!$stmt->prepare($sql)) {
510 self::$dbo->error = $stmt->error;
511 self::$dbo->errorno = $stmt->errno;
518 foreach ($args AS $param => $value) {
519 if (is_int($args[$param])) {
521 } elseif (is_float($args[$param])) {
523 } elseif (is_string($args[$param])) {
528 $values[] = &$args[$param];
531 if (count($values) > 0) {
532 array_unshift($values, $params);
533 call_user_func_array(array($stmt, 'bind_param'), $values);
536 if (!$stmt->execute()) {
537 self::$dbo->error = self::$dbo->db->error;
538 self::$dbo->errorno = self::$dbo->db->errno;
541 $stmt->store_result();
543 self::$dbo->affected_rows = $retval->affected_rows;
547 // For the old "mysql" functions we cannot use prepared statements
548 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
549 if (mysql_errno(self::$dbo->db)) {
550 self::$dbo->error = mysql_error(self::$dbo->db);
551 self::$dbo->errorno = mysql_errno(self::$dbo->db);
553 self::$dbo->affected_rows = mysql_affected_rows($retval);
555 // Due to missing mysql_* support this here wasn't tested at all
556 // See here: http://php.net/manual/en/function.mysql-num-rows.php
557 if (self::$dbo->affected_rows <= 0) {
558 self::$dbo->affected_rows = mysql_num_rows($retval);
564 // We are having an own error logging in the function "e"
565 if ((self::$dbo->errorno != 0) && !$called_from_e) {
566 // We have to preserve the error code, somewhere in the logging it get lost
567 $error = self::$dbo->error;
568 $errorno = self::$dbo->errorno;
570 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
571 System::callstack(8)."\n".self::replace_parameters($sql, $params));
573 self::$dbo->error = $error;
574 self::$dbo->errorno = $errorno;
577 $a->save_timestamp($stamp1, 'database');
579 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
581 $stamp2 = microtime(true);
582 $duration = (float)($stamp2 - $stamp1);
584 if (($duration > $a->config["system"]["db_loglimit"])) {
585 $duration = round($duration, 3);
586 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
588 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
589 basename($backtrace[1]["file"])."\t".
590 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
591 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
598 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
600 * Please use dba::delete, dba::insert, dba::update, ... instead
602 * @param string $sql SQL statement
603 * @return boolean Was the query successfull? False is returned only if an error occurred
605 public static function e($sql) {
610 $stamp = microtime(true);
612 $params = self::getParam(func_get_args());
614 // In a case of a deadlock we are repeating the query 20 times
618 $stmt = self::p($sql, $params);
620 if (is_bool($stmt)) {
622 } elseif (is_object($stmt)) {
630 } while ((self::$dbo->errorno == 1213) && (--$timeout > 0));
632 if (self::$dbo->errorno != 0) {
633 // We have to preserve the error code, somewhere in the logging it get lost
634 $error = self::$dbo->error;
635 $errorno = self::$dbo->errorno;
637 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
638 System::callstack(8)."\n".self::replace_parameters($sql, $params));
640 self::$dbo->error = $error;
641 self::$dbo->errorno = $errorno;
644 $a->save_timestamp($stamp, "database_write");
650 * @brief Check if data exists
652 * @param string $table Table name
653 * @param array $condition array of fields for condition
655 * @return boolean Are there rows for that condition?
657 public static function exists($table, $condition) {
666 $array_element = each($condition);
667 $array_key = $array_element['key'];
668 if (!is_int($array_key)) {
669 $fields = array($array_key);
672 $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
674 if (is_bool($stmt)) {
677 $retval = (self::num_rows($stmt) > 0);
686 * @brief Fetches the first row
688 * Please use dba::select or dba::exists whenever this is possible.
690 * @param string $sql SQL statement
691 * @return array first row of query
693 public static function fetch_first($sql) {
696 $params = self::getParam(func_get_args());
698 $stmt = self::p($sql, $params);
700 if (is_bool($stmt)) {
703 $retval = self::fetch($stmt);
712 * @brief Returns the number of affected rows of the last statement
714 * @return int Number of rows
716 public static function affected_rows() {
719 return self::$dbo->affected_rows;
723 * @brief Returns the number of columns of a statement
725 * @param object Statement object
726 * @return int Number of columns
728 public static function columnCount($stmt) {
731 if (!is_object($stmt)) {
734 switch (self::$dbo->driver) {
736 return $stmt->columnCount();
738 return $stmt->field_count;
740 return mysql_affected_rows($stmt);
745 * @brief Returns the number of rows of a statement
747 * @param object Statement object
748 * @return int Number of rows
750 public static function num_rows($stmt) {
753 if (!is_object($stmt)) {
756 switch (self::$dbo->driver) {
758 return $stmt->rowCount();
760 return $stmt->num_rows;
762 return mysql_num_rows($stmt);
768 * @brief Fetch a single row
770 * @param object $stmt statement object
771 * @return array current row
773 public static function fetch($stmt) {
776 if (!is_object($stmt)) {
780 switch (self::$dbo->driver) {
782 return $stmt->fetch(PDO::FETCH_ASSOC);
784 if (get_class($stmt) == 'mysqli_result') {
785 return $stmt->fetch_assoc();
788 // This code works, but is slow
790 // Bind the result to a result array
794 for ($x = 0; $x < $stmt->field_count; $x++) {
795 $cols[] = &$cols_num[$x];
798 call_user_func_array(array($stmt, 'bind_result'), $cols);
800 if (!$stmt->fetch()) {
805 // We need to get the field names for the array keys
806 // It seems that there is no better way to do this.
807 $result = $stmt->result_metadata();
808 $fields = $result->fetch_fields();
811 foreach ($cols_num AS $param => $col) {
812 $columns[$fields[$param]->name] = $col;
816 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
821 * @brief Insert a row into a table
823 * @param string $table Table name
824 * @param array $param parameter array
825 * @param bool $on_duplicate_update Do an update on a duplicate entry
827 * @return boolean was the insert successfull?
829 public static function insert($table, $param, $on_duplicate_update = false) {
832 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
833 substr(str_repeat("?, ", count($param)), 0, -2).")";
835 if ($on_duplicate_update) {
836 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
838 $values = array_values($param);
839 $param = array_merge_recursive($values, $values);
842 return self::e($sql, $param);
846 * @brief Fetch the id of the last insert command
848 * @return integer Last inserted id
850 public static function lastInsertId() {
853 switch (self::$dbo->driver) {
855 $id = self::$dbo->db->lastInsertId();
858 $id = self::$dbo->db->insert_id;
861 $id = mysql_insert_id(self::$dbo);
868 * @brief Locks a table for exclusive write access
870 * This function can be extended in the future to accept a table array as well.
872 * @param string $table Table name
874 * @return boolean was the lock successful?
876 public static function lock($table) {
879 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
880 self::e("SET autocommit=0");
881 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
883 self::e("SET autocommit=1");
885 self::$in_transaction = true;
891 * @brief Unlocks all locked tables
893 * @return boolean was the unlock successful?
895 public static function unlock() {
898 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
900 $success = self::e("UNLOCK TABLES");
901 self::e("SET autocommit=1");
902 self::$in_transaction = false;
907 * @brief Starts a transaction
909 * @return boolean Was the command executed successfully?
911 public static function transaction() {
914 if (!self::e('COMMIT')) {
917 if (!self::e('START TRANSACTION')) {
920 self::$in_transaction = true;
925 * @brief Does a commit
927 * @return boolean Was the command executed successfully?
929 public static function commit() {
932 if (!self::e('COMMIT')) {
935 self::$in_transaction = false;
940 * @brief Does a rollback
942 * @return boolean Was the command executed successfully?
944 public static function rollback() {
947 if (!self::e('ROLLBACK')) {
950 self::$in_transaction = false;
955 * @brief Build the array with the table relations
957 * The array is build from the database definitions in dbstructure.php
959 * This process must only be started once, since the value is cached.
961 private static function build_relation_data() {
962 $definition = db_definition();
964 foreach ($definition AS $table => $structure) {
965 foreach ($structure['fields'] AS $field => $field_struct) {
966 if (isset($field_struct['relation'])) {
967 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
968 self::$relation[$rel_table][$rel_field][$table][] = $field;
976 * @brief Delete a row from a table
978 * @param string $table Table name
979 * @param array $param parameter array
980 * @param boolean $in_process Internal use: Only do a commit after the last delete
981 * @param array $callstack Internal use: prevent endless loops
983 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
985 public static function delete($table, $param, $in_process = false, &$callstack = array()) {
990 // Create a key for the loop prevention
991 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
993 // We quit when this key already exists in the callstack.
994 if (isset($callstack[$key])) {
998 $callstack[$key] = true;
1000 $table = self::$dbo->escape($table);
1002 $commands[$key] = array('table' => $table, 'param' => $param);
1004 // To speed up the whole process we cache the table relations
1005 if (count(self::$relation) == 0) {
1006 self::build_relation_data();
1009 // Is there a relation entry for the table?
1010 if (isset(self::$relation[$table])) {
1011 // We only allow a simple "one field" relation.
1012 $field = array_keys(self::$relation[$table])[0];
1013 $rel_def = array_values(self::$relation[$table])[0];
1015 // Create a key for preventing double queries
1016 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
1018 // When the search field is the relation field, we don't need to fetch the rows
1019 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1020 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
1021 foreach ($rel_def AS $rel_table => $rel_fields) {
1022 foreach ($rel_fields AS $rel_field) {
1023 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
1024 $commands = array_merge($commands, $retval);
1027 // We quit when this key already exists in the callstack.
1028 } elseif (!isset($callstack[$qkey])) {
1030 $callstack[$qkey] = true;
1032 // Fetch all rows that are to be deleted
1033 $data = self::select($table, array($field), $param);
1035 while ($row = self::fetch($data)) {
1036 // Now we accumulate the delete commands
1037 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
1038 $commands = array_merge($commands, $retval);
1043 // Since we had split the delete command we don't need the original command anymore
1044 unset($commands[$key]);
1049 // Now we finalize the process
1050 $do_transaction = !self::$in_transaction;
1052 if ($do_transaction) {
1053 self::transaction();
1056 $compacted = array();
1059 foreach ($commands AS $command) {
1060 $condition = $command['param'];
1061 $array_element = each($condition);
1062 $array_key = $array_element['key'];
1063 if (is_int($array_key)) {
1064 $condition_string = " WHERE ".array_shift($condition);
1066 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1069 if ((count($command['param']) > 1) || is_int($array_key)) {
1070 $sql = "DELETE FROM `".$command['table']."`".$condition_string;
1071 logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
1073 if (!self::e($sql, $condition)) {
1074 if ($do_transaction) {
1080 $key_table = $command['table'];
1081 $key_param = array_keys($command['param'])[0];
1082 $value = array_values($command['param'])[0];
1084 // Split the SQL queries in chunks of 100 values
1085 // We do the $i stuff here to make the code better readable
1086 $i = $counter[$key_table][$key_param];
1087 if (count($compacted[$key_table][$key_param][$i]) > 100) {
1091 $compacted[$key_table][$key_param][$i][$value] = $value;
1092 $counter[$key_table][$key_param] = $i;
1095 foreach ($compacted AS $table => $values) {
1096 foreach ($values AS $field => $field_value_list) {
1097 foreach ($field_value_list AS $field_values) {
1098 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1099 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1101 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
1103 if (!self::e($sql, $field_values)) {
1104 if ($do_transaction) {
1112 if ($do_transaction) {
1122 * @brief Updates rows
1124 * Updates rows in the database. When $old_fields is set to an array,
1125 * the system will only do an update if the fields in that array changed.
1128 * Only the values in $old_fields are compared.
1129 * This is an intentional behaviour.
1132 * We include the timestamp field in $fields but not in $old_fields.
1133 * Then the row will only get the new timestamp when the other fields had changed.
1135 * When $old_fields is set to a boolean value the system will do this compare itself.
1136 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1139 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1140 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1142 * @param string $table Table name
1143 * @param array $fields contains the fields that are updated
1144 * @param array $condition condition array with the key values
1145 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1147 * @return boolean was the update successfull?
1149 public static function update($table, $fields, $condition, $old_fields = array()) {
1152 $table = self::$dbo->escape($table);
1154 if (count($condition) > 0) {
1155 $array_element = each($condition);
1156 $array_key = $array_element['key'];
1157 if (is_int($array_key)) {
1158 $condition_string = " WHERE ".array_shift($condition);
1160 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1163 $condition_string = "";
1166 if (is_bool($old_fields)) {
1167 $do_insert = $old_fields;
1169 $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1171 if (is_bool($old_fields)) {
1173 $values = array_merge($condition, $fields);
1174 return self::insert($table, $values, $do_insert);
1176 $old_fields = array();
1180 $do_update = (count($old_fields) == 0);
1182 foreach ($old_fields AS $fieldname => $content) {
1183 if (isset($fields[$fieldname])) {
1184 if ($fields[$fieldname] == $content) {
1185 unset($fields[$fieldname]);
1192 if (!$do_update || (count($fields) == 0)) {
1196 $sql = "UPDATE `".$table."` SET `".
1197 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1199 $params1 = array_values($fields);
1200 $params2 = array_values($condition);
1201 $params = array_merge_recursive($params1, $params2);
1203 return self::e($sql, $params);
1207 * @brief Select rows from a table
1209 * @param string $table Table name
1210 * @param array $fields array of selected fields
1211 * @param array $condition array of fields for condition
1212 * @param array $params array of several parameters
1214 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1218 * $fields = array("id", "uri", "uid", "network");
1220 * $condition = array("uid" => 1, "network" => 'dspr');
1222 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1224 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1226 * $data = dba::select($table, $fields, $condition, $params);
1228 public static function select($table, $fields = array(), $condition = array(), $params = array()) {
1235 if (count($fields) > 0) {
1236 $select_fields = "`".implode("`, `", array_values($fields))."`";
1238 $select_fields = "*";
1241 if (count($condition) > 0) {
1242 $array_element = each($condition);
1243 $array_key = $array_element['key'];
1244 if (is_int($array_key)) {
1245 $condition_string = " WHERE ".array_shift($condition);
1247 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1250 $condition_string = "";
1254 $single_row = false;
1256 if (isset($params['order'])) {
1257 $param_string .= " ORDER BY ";
1258 foreach ($params['order'] AS $fields => $order) {
1259 if (!is_int($fields)) {
1260 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1262 $param_string .= "`".$order."`, ";
1265 $param_string = substr($param_string, 0, -2);
1268 if (isset($params['limit']) && is_int($params['limit'])) {
1269 $param_string .= " LIMIT ".$params['limit'];
1270 $single_row = ($params['limit'] == 1);
1273 if (isset($params['only_query']) && $params['only_query']) {
1274 $single_row = !$params['only_query'];
1277 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1279 $result = self::p($sql, $condition);
1281 if (is_bool($result) || !$single_row) {
1284 $row = self::fetch($result);
1285 self::close($result);
1292 * @brief Fills an array with data from a query
1294 * @param object $stmt statement object
1295 * @return array Data array
1297 public static function inArray($stmt, $do_close = true) {
1300 if (is_bool($stmt)) {
1305 while ($row = self::fetch($stmt)) {
1315 * @brief Returns the error number of the last query
1317 * @return string Error number (0 if no error)
1319 public static function errorNo() {
1322 return self::$dbo->errorno;
1326 * @brief Returns the error message of the last query
1328 * @return string Error message ('' if no error)
1330 public static function errorMessage() {
1333 return self::$dbo->error;
1337 * @brief Closes the current statement
1339 * @param object $stmt statement object
1340 * @return boolean was the close successfull?
1342 public static function close($stmt) {
1345 if (!is_object($stmt)) {
1349 switch (self::$dbo->driver) {
1351 return $stmt->closeCursor();
1353 return $stmt->free_result();
1354 return $stmt->close();
1356 return mysql_free_result($stmt);
1361 function dbesc($str) {
1364 if ($db && $db->connected) {
1365 return($db->escape($str));
1367 return(str_replace("'","\\'",$str));
1372 * @brief execute SQL query with printf style args - deprecated
1374 * Please use the dba:: functions instead:
1375 * dba::select, dba::exists, dba::insert
1376 * dba::delete, dba::update, dba::p, dba::e
1378 * @param $args Query parameters (1 to N parameters of different types)
1379 * @return array Query array
1384 $args = func_get_args();
1387 if (!$db || !$db->connected) {
1391 $sql = $db->clean_query($sql);
1392 $sql = $db->any_value_fallback($sql);
1394 $stmt = @vsprintf($sql, $args);
1396 $ret = dba::p($stmt);
1398 if (is_bool($ret)) {
1402 $columns = dba::columnCount($ret);
1404 $data = dba::inArray($ret);
1406 if ((count($data) == 0) && ($columns == 0)) {
1413 function dba_timer() {
1414 return microtime(true);