2 use \Friendica\Core\System;
4 require_once("dbm.php");
5 require_once('include/datetime.php');
8 * @class MySQL database class
10 * For debugging, insert 'dbg(1);' anywhere in the program flow.
11 * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
12 * When logging, all binary info is converted to text and html entities are escaped so that
13 * the debugging stream is safe to view within both terminals and web pages.
15 * This class is for the low level database stuff that does driver specific things.
24 public $connected = false;
25 public $error = false;
27 public $affected_rows = 0;
28 private $_server_info = '';
29 private static $in_transaction = false;
31 private static $relation = array();
33 function __construct($serveraddr, $user, $pass, $db, $install = false) {
36 $stamp1 = microtime(true);
38 $serveraddr = trim($serveraddr);
40 $serverdata = explode(':', $serveraddr);
41 $server = $serverdata[0];
43 if (count($serverdata) > 1) {
44 $port = trim($serverdata[1]);
47 $server = trim($server);
52 if (!(strlen($server) && strlen($user))) {
53 $this->connected = false;
59 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
60 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
61 $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
62 $this->connected = false;
69 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
70 $this->driver = 'pdo';
71 $connect = "mysql:host=".$server.";dbname=".$db;
74 $connect .= ";port=".$port;
77 if (isset($a->config["system"]["db_charset"])) {
78 $connect .= ";charset=".$a->config["system"]["db_charset"];
81 $this->db = @new PDO($connect, $user, $pass);
82 $this->connected = true;
83 } catch (PDOException $e) {
84 $this->connected = false;
88 if (!$this->connected && class_exists('mysqli')) {
89 $this->driver = 'mysqli';
90 $this->db = @new mysqli($server, $user, $pass, $db, $port);
91 if (!mysqli_connect_errno()) {
92 $this->connected = true;
94 if (isset($a->config["system"]["db_charset"])) {
95 $this->db->set_charset($a->config["system"]["db_charset"]);
100 if (!$this->connected && function_exists('mysql_connect')) {
101 $this->driver = 'mysql';
102 $this->db = mysql_connect($serveraddr, $user, $pass);
103 if ($this->db && mysql_select_db($db, $this->db)) {
104 $this->connected = true;
106 if (isset($a->config["system"]["db_charset"])) {
107 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
112 // No suitable SQL driver was found.
113 if (!$this->connected) {
116 system_unavailable();
119 $a->save_timestamp($stamp1, "network");
125 * @brief Returns the MySQL server version string
127 * This function discriminate between the deprecated mysql API and the current
128 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
132 public function server_info() {
133 if ($this->_server_info == '') {
134 switch ($this->driver) {
136 $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
139 $this->_server_info = $this->db->server_info;
142 $this->_server_info = mysql_get_server_info($this->db);
146 return $this->_server_info;
150 * @brief Returns the selected database name
154 public function database_name() {
155 $r = $this->q("SELECT DATABASE() AS `db`");
161 * @brief Analyze a database query and log this if some conditions are met.
163 * @param string $query The database query that will be analyzed
165 public function log_index($query) {
168 if (empty($a->config["system"]["db_log_index"])) {
172 // Don't explain an explain statement
173 if (strtolower(substr($query, 0, 7)) == "explain") {
177 // Only do the explain on "select", "update" and "delete"
178 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
182 $r = $this->q("EXPLAIN ".$query);
183 if (!dbm::is_result($r)) {
187 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
188 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
190 foreach ($r AS $row) {
191 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
192 $log = (in_array($row['key'], $watchlist) &&
193 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
198 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
202 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
207 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
208 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
209 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
210 basename($backtrace[1]["file"])."\t".
211 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
212 substr($query, 0, 2000)."\n", FILE_APPEND);
218 * @brief execute SQL query - deprecated
220 * Please use the dba:: functions instead:
221 * dba::select, dba::exists, dba::insert
222 * dba::delete, dba::update, dba::p, dba::e
224 * @param string $sql SQL query
225 * @return array Query array
227 public function q($sql) {
228 $ret = self::p($sql);
234 $columns = self::columnCount($ret);
236 $data = self::inArray($ret);
238 if ((count($data) == 0) && ($columns == 0)) {
245 public function dbg($dbg) {
249 public function escape($str) {
250 if ($this->db && $this->connected) {
251 switch ($this->driver) {
253 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
255 return @$this->db->real_escape_string($str);
257 return @mysql_real_escape_string($str,$this->db);
262 function connected() {
263 switch ($this->driver) {
265 // Not sure if this really is working like expected
266 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
269 $connected = $this->db->ping();
272 $connected = mysql_ping($this->db);
278 function __destruct() {
280 switch ($this->driver) {
288 mysql_close($this->db);
295 * @brief Replaces ANY_VALUE() function by MIN() function,
296 * if the database server does not support ANY_VALUE().
298 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
299 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
300 * A standard fall-back is to use MIN().
302 * @param string $sql An SQL string without the values
303 * @return string The input SQL string modified if necessary.
305 public function any_value_fallback($sql) {
306 $server_info = $this->server_info();
307 if (version_compare($server_info, '5.7.5', '<') ||
308 (stripos($server_info, 'MariaDB') !== false)) {
309 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
315 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
317 * This is safe when we bind the parameters later.
318 * The parameter values aren't part of the SQL.
320 * @param string $sql An SQL string without the values
321 * @return string The input SQL string modified if necessary.
323 public function clean_query($sql) {
324 $search = array("\t", "\n", "\r", " ");
325 $replace = array(' ', ' ', ' ', ' ');
328 $sql = str_replace($search, $replace, $sql);
329 } while ($oldsql != $sql);
336 * @brief Replaces the ? placeholders with the parameters in the $args array
338 * @param string $sql SQL query
339 * @param array $args The parameters that are to replace the ? placeholders
340 * @return string The replaced SQL query
342 private static function replace_parameters($sql, $args) {
344 foreach ($args AS $param => $value) {
345 if (is_int($args[$param]) || is_float($args[$param])) {
346 $replace = intval($args[$param]);
348 $replace = "'".self::$dbo->escape($args[$param])."'";
351 $pos = strpos($sql, '?', $offset);
352 if ($pos !== false) {
353 $sql = substr_replace($sql, $replace, $pos, 1);
355 $offset = $pos + strlen($replace);
361 * @brief Convert parameter array to an universal form
362 * @param array $args Parameter array
363 * @return array universalized parameter array
365 private static function getParam($args) {
368 // When the second function parameter is an array then use this as the parameter array
369 if ((count($args) > 0) && (is_array($args[1]))) {
377 * @brief Executes a prepared statement that returns data
378 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
380 * Please only use it with complicated queries.
381 * For all regular queries please use dba::select or dba::exists
383 * @param string $sql SQL statement
384 * @return object statement object
386 public static function p($sql) {
389 $stamp1 = microtime(true);
391 $params = self::getParam(func_get_args());
393 // Renumber the array keys to be sure that they fit
396 foreach ($params AS $param) {
397 // Avoid problems with some MySQL servers and boolean values. See issue #3645
398 if (is_bool($param)) {
399 $param = (int)$param;
401 $args[++$i] = $param;
404 if (!self::$dbo || !self::$dbo->connected) {
408 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
409 // Question: Should we continue or stop the query here?
410 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
413 $sql = self::$dbo->clean_query($sql);
414 $sql = self::$dbo->any_value_fallback($sql);
418 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
419 $sql = "/*".System::callstack()." */ ".$sql;
422 self::$dbo->error = '';
423 self::$dbo->errorno = 0;
424 self::$dbo->affected_rows = 0;
426 // We have to make some things different if this function is called from "e"
427 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
429 if (isset($trace[1])) {
430 $called_from = $trace[1];
432 // We use just something that is defined to avoid warnings
433 $called_from = $trace[0];
435 // We are having an own error logging in the function "e"
436 $called_from_e = ($called_from['function'] == 'e');
438 switch (self::$dbo->driver) {
440 // If there are no arguments we use "query"
441 if (count($args) == 0) {
442 if (!$retval = self::$dbo->db->query($sql)) {
443 $errorInfo = self::$dbo->db->errorInfo();
444 self::$dbo->error = $errorInfo[2];
445 self::$dbo->errorno = $errorInfo[1];
449 self::$dbo->affected_rows = $retval->rowCount();
453 if (!$stmt = self::$dbo->db->prepare($sql)) {
454 $errorInfo = self::$dbo->db->errorInfo();
455 self::$dbo->error = $errorInfo[2];
456 self::$dbo->errorno = $errorInfo[1];
461 foreach ($args AS $param => $value) {
462 $stmt->bindParam($param, $args[$param]);
465 if (!$stmt->execute()) {
466 $errorInfo = $stmt->errorInfo();
467 self::$dbo->error = $errorInfo[2];
468 self::$dbo->errorno = $errorInfo[1];
472 self::$dbo->affected_rows = $retval->rowCount();
476 // There are SQL statements that cannot be executed with a prepared statement
477 $parts = explode(' ', $orig_sql);
478 $command = strtolower($parts[0]);
479 $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
481 // The fallback routine is called as well when there are no arguments
482 if (!$can_be_prepared || (count($args) == 0)) {
483 $retval = self::$dbo->db->query(self::replace_parameters($sql, $args));
484 if (self::$dbo->db->errno) {
485 self::$dbo->error = self::$dbo->db->error;
486 self::$dbo->errorno = self::$dbo->db->errno;
489 if (isset($retval->num_rows)) {
490 self::$dbo->affected_rows = $retval->num_rows;
492 self::$dbo->affected_rows = self::$dbo->db->affected_rows;
498 $stmt = self::$dbo->db->stmt_init();
500 if (!$stmt->prepare($sql)) {
501 self::$dbo->error = $stmt->error;
502 self::$dbo->errorno = $stmt->errno;
509 foreach ($args AS $param => $value) {
510 if (is_int($args[$param])) {
512 } elseif (is_float($args[$param])) {
514 } elseif (is_string($args[$param])) {
519 $values[] = &$args[$param];
522 if (count($values) > 0) {
523 array_unshift($values, $params);
524 call_user_func_array(array($stmt, 'bind_param'), $values);
527 if (!$stmt->execute()) {
528 self::$dbo->error = self::$dbo->db->error;
529 self::$dbo->errorno = self::$dbo->db->errno;
532 $stmt->store_result();
534 self::$dbo->affected_rows = $retval->affected_rows;
538 // For the old "mysql" functions we cannot use prepared statements
539 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
540 if (mysql_errno(self::$dbo->db)) {
541 self::$dbo->error = mysql_error(self::$dbo->db);
542 self::$dbo->errorno = mysql_errno(self::$dbo->db);
544 self::$dbo->affected_rows = mysql_affected_rows($retval);
546 // Due to missing mysql_* support this here wasn't tested at all
547 // See here: http://php.net/manual/en/function.mysql-num-rows.php
548 if (self::$dbo->affected_rows <= 0) {
549 self::$dbo->affected_rows = mysql_num_rows($retval);
555 // We are having an own error logging in the function "e"
556 if ((self::$dbo->errorno != 0) && !$called_from_e) {
557 // We have to preserve the error code, somewhere in the logging it get lost
558 $error = self::$dbo->error;
559 $errorno = self::$dbo->errorno;
561 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
562 System::callstack(8)."\n".self::replace_parameters($sql, $params));
564 self::$dbo->error = $error;
565 self::$dbo->errorno = $errorno;
568 $a->save_timestamp($stamp1, 'database');
570 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
572 $stamp2 = microtime(true);
573 $duration = (float)($stamp2 - $stamp1);
575 if (($duration > $a->config["system"]["db_loglimit"])) {
576 $duration = round($duration, 3);
577 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
579 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
580 basename($backtrace[1]["file"])."\t".
581 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
582 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
589 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
591 * Please use dba::delete, dba::insert, dba::update, ... instead
593 * @param string $sql SQL statement
594 * @return boolean Was the query successfull? False is returned only if an error occurred
596 public static function e($sql) {
599 $stamp = microtime(true);
601 $params = self::getParam(func_get_args());
603 // In a case of a deadlock we are repeating the query 20 times
607 $stmt = self::p($sql, $params);
609 if (is_bool($stmt)) {
611 } elseif (is_object($stmt)) {
619 } while ((self::$dbo->errorno == 1213) && (--$timeout > 0));
621 if (self::$dbo->errorno != 0) {
622 // We have to preserve the error code, somewhere in the logging it get lost
623 $error = self::$dbo->error;
624 $errorno = self::$dbo->errorno;
626 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
627 System::callstack(8)."\n".self::replace_parameters($sql, $params));
629 self::$dbo->error = $error;
630 self::$dbo->errorno = $errorno;
633 $a->save_timestamp($stamp, "database_write");
639 * @brief Check if data exists
641 * @param string $table Table name
642 * @param array $condition array of fields for condition
644 * @return boolean Are there rows for that condition?
646 public static function exists($table, $condition) {
653 $array_element = each($condition);
654 $array_key = $array_element['key'];
655 if (!is_int($array_key)) {
656 $fields = array($array_key);
659 $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
661 if (is_bool($stmt)) {
664 $retval = (self::num_rows($stmt) > 0);
673 * @brief Fetches the first row
675 * Please use dba::select or dba::exists whenever this is possible.
677 * @param string $sql SQL statement
678 * @return array first row of query
680 public static function fetch_first($sql) {
681 $params = self::getParam(func_get_args());
683 $stmt = self::p($sql, $params);
685 if (is_bool($stmt)) {
688 $retval = self::fetch($stmt);
697 * @brief Returns the number of affected rows of the last statement
699 * @return int Number of rows
701 public static function affected_rows() {
702 return self::$dbo->affected_rows;
706 * @brief Returns the number of columns of a statement
708 * @param object Statement object
709 * @return int Number of columns
711 public static function columnCount($stmt) {
712 if (!is_object($stmt)) {
715 switch (self::$dbo->driver) {
717 return $stmt->columnCount();
719 return $stmt->field_count;
721 return mysql_affected_rows($stmt);
726 * @brief Returns the number of rows of a statement
728 * @param object Statement object
729 * @return int Number of rows
731 public static function num_rows($stmt) {
732 if (!is_object($stmt)) {
735 switch (self::$dbo->driver) {
737 return $stmt->rowCount();
739 return $stmt->num_rows;
741 return mysql_num_rows($stmt);
747 * @brief Fetch a single row
749 * @param object $stmt statement object
750 * @return array current row
752 public static function fetch($stmt) {
753 if (!is_object($stmt)) {
757 switch (self::$dbo->driver) {
759 return $stmt->fetch(PDO::FETCH_ASSOC);
761 if (get_class($stmt) == 'mysqli_result') {
762 return $stmt->fetch_assoc();
765 // This code works, but is slow
767 // Bind the result to a result array
771 for ($x = 0; $x < $stmt->field_count; $x++) {
772 $cols[] = &$cols_num[$x];
775 call_user_func_array(array($stmt, 'bind_result'), $cols);
777 if (!$stmt->fetch()) {
782 // We need to get the field names for the array keys
783 // It seems that there is no better way to do this.
784 $result = $stmt->result_metadata();
785 $fields = $result->fetch_fields();
788 foreach ($cols_num AS $param => $col) {
789 $columns[$fields[$param]->name] = $col;
793 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
798 * @brief Insert a row into a table
800 * @param string $table Table name
801 * @param array $param parameter array
802 * @param bool $on_duplicate_update Do an update on a duplicate entry
804 * @return boolean was the insert successfull?
806 public static function insert($table, $param, $on_duplicate_update = false) {
807 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
808 substr(str_repeat("?, ", count($param)), 0, -2).")";
810 if ($on_duplicate_update) {
811 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
813 $values = array_values($param);
814 $param = array_merge_recursive($values, $values);
817 return self::e($sql, $param);
821 * @brief Fetch the id of the last insert command
823 * @return integer Last inserted id
825 public static function lastInsertId() {
826 switch (self::$dbo->driver) {
828 $id = self::$dbo->db->lastInsertId();
831 $id = self::$dbo->db->insert_id;
834 $id = mysql_insert_id(self::$dbo);
841 * @brief Locks a table for exclusive write access
843 * This function can be extended in the future to accept a table array as well.
845 * @param string $table Table name
847 * @return boolean was the lock successful?
849 public static function lock($table) {
850 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
851 self::e("SET autocommit=0");
852 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
854 self::e("SET autocommit=1");
856 self::$in_transaction = true;
862 * @brief Unlocks all locked tables
864 * @return boolean was the unlock successful?
866 public static function unlock() {
867 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
869 $success = self::e("UNLOCK TABLES");
870 self::e("SET autocommit=1");
871 self::$in_transaction = false;
876 * @brief Starts a transaction
878 * @return boolean Was the command executed successfully?
880 public static function transaction() {
881 if (!self::e('COMMIT')) {
884 if (!self::e('START TRANSACTION')) {
887 self::$in_transaction = true;
892 * @brief Does a commit
894 * @return boolean Was the command executed successfully?
896 public static function commit() {
897 if (!self::e('COMMIT')) {
900 self::$in_transaction = false;
905 * @brief Does a rollback
907 * @return boolean Was the command executed successfully?
909 public static function rollback() {
910 if (!self::e('ROLLBACK')) {
913 self::$in_transaction = false;
918 * @brief Build the array with the table relations
920 * The array is build from the database definitions in dbstructure.php
922 * This process must only be started once, since the value is cached.
924 private static function build_relation_data() {
925 $definition = db_definition();
927 foreach ($definition AS $table => $structure) {
928 foreach ($structure['fields'] AS $field => $field_struct) {
929 if (isset($field_struct['relation'])) {
930 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
931 self::$relation[$rel_table][$rel_field][$table][] = $field;
939 * @brief Delete a row from a table
941 * @param string $table Table name
942 * @param array $param parameter array
943 * @param boolean $in_process Internal use: Only do a commit after the last delete
944 * @param array $callstack Internal use: prevent endless loops
946 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
948 public static function delete($table, $param, $in_process = false, &$callstack = array()) {
952 // Create a key for the loop prevention
953 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
955 // We quit when this key already exists in the callstack.
956 if (isset($callstack[$key])) {
960 $callstack[$key] = true;
962 $table = self::$dbo->escape($table);
964 $commands[$key] = array('table' => $table, 'param' => $param);
966 // To speed up the whole process we cache the table relations
967 if (count(self::$relation) == 0) {
968 self::build_relation_data();
971 // Is there a relation entry for the table?
972 if (isset(self::$relation[$table])) {
973 // We only allow a simple "one field" relation.
974 $field = array_keys(self::$relation[$table])[0];
975 $rel_def = array_values(self::$relation[$table])[0];
977 // Create a key for preventing double queries
978 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
980 // When the search field is the relation field, we don't need to fetch the rows
981 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
982 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
983 foreach ($rel_def AS $rel_table => $rel_fields) {
984 foreach ($rel_fields AS $rel_field) {
985 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
986 $commands = array_merge($commands, $retval);
989 // We quit when this key already exists in the callstack.
990 } elseif (!isset($callstack[$qkey])) {
992 $callstack[$qkey] = true;
994 // Fetch all rows that are to be deleted
995 $data = self::select($table, array($field), $param);
997 while ($row = self::fetch($data)) {
998 // Now we accumulate the delete commands
999 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
1000 $commands = array_merge($commands, $retval);
1005 // Since we had split the delete command we don't need the original command anymore
1006 unset($commands[$key]);
1011 // Now we finalize the process
1012 $do_transaction = !self::$in_transaction;
1014 if ($do_transaction) {
1015 self::transaction();
1018 $compacted = array();
1021 foreach ($commands AS $command) {
1022 $condition = $command['param'];
1023 $array_element = each($condition);
1024 $array_key = $array_element['key'];
1025 if (is_int($array_key)) {
1026 $condition_string = " WHERE ".array_shift($condition);
1028 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1031 if ((count($command['param']) > 1) || is_int($array_key)) {
1032 $sql = "DELETE FROM `".$command['table']."`".$condition_string;
1033 logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
1035 if (!self::e($sql, $condition)) {
1036 if ($do_transaction) {
1042 $key_table = $command['table'];
1043 $key_param = array_keys($command['param'])[0];
1044 $value = array_values($command['param'])[0];
1046 // Split the SQL queries in chunks of 100 values
1047 // We do the $i stuff here to make the code better readable
1048 $i = $counter[$key_table][$key_param];
1049 if (count($compacted[$key_table][$key_param][$i]) > 100) {
1053 $compacted[$key_table][$key_param][$i][$value] = $value;
1054 $counter[$key_table][$key_param] = $i;
1057 foreach ($compacted AS $table => $values) {
1058 foreach ($values AS $field => $field_value_list) {
1059 foreach ($field_value_list AS $field_values) {
1060 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1061 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1063 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
1065 if (!self::e($sql, $field_values)) {
1066 if ($do_transaction) {
1074 if ($do_transaction) {
1084 * @brief Updates rows
1086 * Updates rows in the database. When $old_fields is set to an array,
1087 * the system will only do an update if the fields in that array changed.
1090 * Only the values in $old_fields are compared.
1091 * This is an intentional behaviour.
1094 * We include the timestamp field in $fields but not in $old_fields.
1095 * Then the row will only get the new timestamp when the other fields had changed.
1097 * When $old_fields is set to a boolean value the system will do this compare itself.
1098 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1101 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1102 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1104 * @param string $table Table name
1105 * @param array $fields contains the fields that are updated
1106 * @param array $condition condition array with the key values
1107 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1109 * @return boolean was the update successfull?
1111 public static function update($table, $fields, $condition, $old_fields = array()) {
1113 $table = self::$dbo->escape($table);
1115 if (count($condition) > 0) {
1116 $array_element = each($condition);
1117 $array_key = $array_element['key'];
1118 if (is_int($array_key)) {
1119 $condition_string = " WHERE ".array_shift($condition);
1121 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1124 $condition_string = "";
1127 if (is_bool($old_fields)) {
1128 $do_insert = $old_fields;
1130 $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1132 if (is_bool($old_fields)) {
1134 $values = array_merge($condition, $fields);
1135 return self::insert($table, $values, $do_insert);
1137 $old_fields = array();
1141 $do_update = (count($old_fields) == 0);
1143 foreach ($old_fields AS $fieldname => $content) {
1144 if (isset($fields[$fieldname])) {
1145 if ($fields[$fieldname] == $content) {
1146 unset($fields[$fieldname]);
1153 if (!$do_update || (count($fields) == 0)) {
1157 $sql = "UPDATE `".$table."` SET `".
1158 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1160 $params1 = array_values($fields);
1161 $params2 = array_values($condition);
1162 $params = array_merge_recursive($params1, $params2);
1164 return self::e($sql, $params);
1168 * @brief Select rows from a table
1170 * @param string $table Table name
1171 * @param array $fields array of selected fields
1172 * @param array $condition array of fields for condition
1173 * @param array $params array of several parameters
1175 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1179 * $fields = array("id", "uri", "uid", "network");
1181 * $condition = array("uid" => 1, "network" => 'dspr');
1183 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1185 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1187 * $data = dba::select($table, $fields, $condition, $params);
1189 public static function select($table, $fields = array(), $condition = array(), $params = array()) {
1194 if (count($fields) > 0) {
1195 $select_fields = "`".implode("`, `", array_values($fields))."`";
1197 $select_fields = "*";
1200 if (count($condition) > 0) {
1201 $array_element = each($condition);
1202 $array_key = $array_element['key'];
1203 if (is_int($array_key)) {
1204 $condition_string = " WHERE ".array_shift($condition);
1206 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1209 $condition_string = "";
1213 $single_row = false;
1215 if (isset($params['order'])) {
1216 $param_string .= " ORDER BY ";
1217 foreach ($params['order'] AS $fields => $order) {
1218 if (!is_int($fields)) {
1219 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1221 $param_string .= "`".$order."`, ";
1224 $param_string = substr($param_string, 0, -2);
1227 if (isset($params['limit']) && is_int($params['limit'])) {
1228 $param_string .= " LIMIT ".$params['limit'];
1229 $single_row = ($params['limit'] == 1);
1232 if (isset($params['only_query']) && $params['only_query']) {
1233 $single_row = !$params['only_query'];
1236 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1238 $result = self::p($sql, $condition);
1240 if (is_bool($result) || !$single_row) {
1243 $row = self::fetch($result);
1244 self::close($result);
1251 * @brief Fills an array with data from a query
1253 * @param object $stmt statement object
1254 * @return array Data array
1256 public static function inArray($stmt, $do_close = true) {
1257 if (is_bool($stmt)) {
1262 while ($row = self::fetch($stmt)) {
1272 * @brief Closes the current statement
1274 * @param object $stmt statement object
1275 * @return boolean was the close successfull?
1277 public static function close($stmt) {
1278 if (!is_object($stmt)) {
1282 switch (self::$dbo->driver) {
1284 return $stmt->closeCursor();
1286 return $stmt->free_result();
1287 return $stmt->close();
1289 return mysql_free_result($stmt);
1294 function printable($s) {
1295 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
1296 $s = str_replace("\x00",'.',$s);
1297 if (x($_SERVER,'SERVER_NAME')) {
1298 $s = escape_tags($s);
1303 // Procedural functions
1304 function dbg($state) {
1312 function dbesc($str) {
1315 if ($db && $db->connected) {
1316 return($db->escape($str));
1318 return(str_replace("'","\\'",$str));
1323 * @brief execute SQL query with printf style args - deprecated
1325 * Please use the dba:: functions instead:
1326 * dba::select, dba::exists, dba::insert
1327 * dba::delete, dba::update, dba::p, dba::e
1329 * @param $args Query parameters (1 to N parameters of different types)
1330 * @return array Query array
1335 $args = func_get_args();
1338 if (!$db || !$db->connected) {
1342 $sql = $db->clean_query($sql);
1343 $sql = $db->any_value_fallback($sql);
1345 $stmt = @vsprintf($sql, $args);
1347 $ret = dba::p($stmt);
1349 if (is_bool($ret)) {
1353 $columns = dba::columnCount($ret);
1355 $data = dba::inArray($ret);
1357 if ((count($data) == 0) && ($columns == 0)) {
1364 function dba_timer() {
1365 return microtime(true);