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)) {
133 * @brief Returns the MySQL server version string
135 * This function discriminate between the deprecated mysql API and the current
136 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
140 public function server_info() {
141 if ($this->_server_info == '') {
142 switch ($this->driver) {
144 $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
147 $this->_server_info = $this->db->server_info;
150 $this->_server_info = mysql_get_server_info($this->db);
154 return $this->_server_info;
158 * @brief Returns the selected database name
162 public function database_name() {
163 $r = $this->q("SELECT DATABASE() AS `db`");
169 * @brief Analyze a database query and log this if some conditions are met.
171 * @param string $query The database query that will be analyzed
173 public function log_index($query) {
176 if (empty($a->config["system"]["db_log_index"])) {
180 // Don't explain an explain statement
181 if (strtolower(substr($query, 0, 7)) == "explain") {
185 // Only do the explain on "select", "update" and "delete"
186 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
190 $r = $this->q("EXPLAIN ".$query);
191 if (!dbm::is_result($r)) {
195 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
196 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
198 foreach ($r AS $row) {
199 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
200 $log = (in_array($row['key'], $watchlist) &&
201 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
206 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
210 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
215 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
216 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
217 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
218 basename($backtrace[1]["file"])."\t".
219 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
220 substr($query, 0, 2000)."\n", FILE_APPEND);
226 * @brief execute SQL query - deprecated
228 * Please use the dba:: functions instead:
229 * dba::select, dba::exists, dba::insert
230 * dba::delete, dba::update, dba::p, dba::e
232 * @param string $sql SQL query
233 * @return array Query array
235 public function q($sql) {
236 $ret = self::p($sql);
242 $columns = self::columnCount($ret);
244 $data = self::inArray($ret);
246 if ((count($data) == 0) && ($columns == 0)) {
253 public function escape($str) {
254 if ($this->db && $this->connected) {
255 switch ($this->driver) {
257 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
259 return @$this->db->real_escape_string($str);
261 return @mysql_real_escape_string($str,$this->db);
266 function connected() {
267 switch ($this->driver) {
269 // Not sure if this really is working like expected
270 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
273 $connected = $this->db->ping();
276 $connected = mysql_ping($this->db);
282 function __destruct() {
284 switch ($this->driver) {
292 mysql_close($this->db);
299 * @brief Replaces ANY_VALUE() function by MIN() function,
300 * if the database server does not support ANY_VALUE().
302 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
303 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
304 * A standard fall-back is to use MIN().
306 * @param string $sql An SQL string without the values
307 * @return string The input SQL string modified if necessary.
309 public function any_value_fallback($sql) {
310 $server_info = $this->server_info();
311 if (version_compare($server_info, '5.7.5', '<') ||
312 (stripos($server_info, 'MariaDB') !== false)) {
313 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
319 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
321 * This is safe when we bind the parameters later.
322 * The parameter values aren't part of the SQL.
324 * @param string $sql An SQL string without the values
325 * @return string The input SQL string modified if necessary.
327 public function clean_query($sql) {
328 $search = array("\t", "\n", "\r", " ");
329 $replace = array(' ', ' ', ' ', ' ');
332 $sql = str_replace($search, $replace, $sql);
333 } while ($oldsql != $sql);
340 * @brief Replaces the ? placeholders with the parameters in the $args array
342 * @param string $sql SQL query
343 * @param array $args The parameters that are to replace the ? placeholders
344 * @return string The replaced SQL query
346 private static function replace_parameters($sql, $args) {
348 foreach ($args AS $param => $value) {
349 if (is_int($args[$param]) || is_float($args[$param])) {
350 $replace = intval($args[$param]);
352 $replace = "'".self::$dbo->escape($args[$param])."'";
355 $pos = strpos($sql, '?', $offset);
356 if ($pos !== false) {
357 $sql = substr_replace($sql, $replace, $pos, 1);
359 $offset = $pos + strlen($replace);
365 * @brief Convert parameter array to an universal form
366 * @param array $args Parameter array
367 * @return array universalized parameter array
369 private static function getParam($args) {
372 // When the second function parameter is an array then use this as the parameter array
373 if ((count($args) > 0) && (is_array($args[1]))) {
381 * @brief Executes a prepared statement that returns data
382 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
384 * Please only use it with complicated queries.
385 * For all regular queries please use dba::select or dba::exists
387 * @param string $sql SQL statement
388 * @return object statement object
390 public static function p($sql) {
395 $stamp1 = microtime(true);
397 $params = self::getParam(func_get_args());
399 // Renumber the array keys to be sure that they fit
402 foreach ($params AS $param) {
403 // Avoid problems with some MySQL servers and boolean values. See issue #3645
404 if (is_bool($param)) {
405 $param = (int)$param;
407 $args[++$i] = $param;
410 if (!self::$dbo || !self::$dbo->connected) {
414 if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
415 // Question: Should we continue or stop the query here?
416 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
419 $sql = self::$dbo->clean_query($sql);
420 $sql = self::$dbo->any_value_fallback($sql);
424 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
425 $sql = "/*".System::callstack()." */ ".$sql;
428 self::$dbo->error = '';
429 self::$dbo->errorno = 0;
430 self::$dbo->affected_rows = 0;
432 // We have to make some things different if this function is called from "e"
433 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
435 if (isset($trace[1])) {
436 $called_from = $trace[1];
438 // We use just something that is defined to avoid warnings
439 $called_from = $trace[0];
441 // We are having an own error logging in the function "e"
442 $called_from_e = ($called_from['function'] == 'e');
444 switch (self::$dbo->driver) {
446 // If there are no arguments we use "query"
447 if (count($args) == 0) {
448 if (!$retval = self::$dbo->db->query($sql)) {
449 $errorInfo = self::$dbo->db->errorInfo();
450 self::$dbo->error = $errorInfo[2];
451 self::$dbo->errorno = $errorInfo[1];
455 self::$dbo->affected_rows = $retval->rowCount();
459 if (!$stmt = self::$dbo->db->prepare($sql)) {
460 $errorInfo = self::$dbo->db->errorInfo();
461 self::$dbo->error = $errorInfo[2];
462 self::$dbo->errorno = $errorInfo[1];
467 foreach ($args AS $param => $value) {
468 $stmt->bindParam($param, $args[$param]);
471 if (!$stmt->execute()) {
472 $errorInfo = $stmt->errorInfo();
473 self::$dbo->error = $errorInfo[2];
474 self::$dbo->errorno = $errorInfo[1];
478 self::$dbo->affected_rows = $retval->rowCount();
482 // There are SQL statements that cannot be executed with a prepared statement
483 $parts = explode(' ', $orig_sql);
484 $command = strtolower($parts[0]);
485 $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
487 // The fallback routine is called as well when there are no arguments
488 if (!$can_be_prepared || (count($args) == 0)) {
489 $retval = self::$dbo->db->query(self::replace_parameters($sql, $args));
490 if (self::$dbo->db->errno) {
491 self::$dbo->error = self::$dbo->db->error;
492 self::$dbo->errorno = self::$dbo->db->errno;
495 if (isset($retval->num_rows)) {
496 self::$dbo->affected_rows = $retval->num_rows;
498 self::$dbo->affected_rows = self::$dbo->db->affected_rows;
504 $stmt = self::$dbo->db->stmt_init();
506 if (!$stmt->prepare($sql)) {
507 self::$dbo->error = $stmt->error;
508 self::$dbo->errorno = $stmt->errno;
515 foreach ($args AS $param => $value) {
516 if (is_int($args[$param])) {
518 } elseif (is_float($args[$param])) {
520 } elseif (is_string($args[$param])) {
525 $values[] = &$args[$param];
528 if (count($values) > 0) {
529 array_unshift($values, $params);
530 call_user_func_array(array($stmt, 'bind_param'), $values);
533 if (!$stmt->execute()) {
534 self::$dbo->error = self::$dbo->db->error;
535 self::$dbo->errorno = self::$dbo->db->errno;
538 $stmt->store_result();
540 self::$dbo->affected_rows = $retval->affected_rows;
544 // For the old "mysql" functions we cannot use prepared statements
545 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
546 if (mysql_errno(self::$dbo->db)) {
547 self::$dbo->error = mysql_error(self::$dbo->db);
548 self::$dbo->errorno = mysql_errno(self::$dbo->db);
550 self::$dbo->affected_rows = mysql_affected_rows($retval);
552 // Due to missing mysql_* support this here wasn't tested at all
553 // See here: http://php.net/manual/en/function.mysql-num-rows.php
554 if (self::$dbo->affected_rows <= 0) {
555 self::$dbo->affected_rows = mysql_num_rows($retval);
561 // We are having an own error logging in the function "e"
562 if ((self::$dbo->errorno != 0) && !$called_from_e) {
563 // We have to preserve the error code, somewhere in the logging it get lost
564 $error = self::$dbo->error;
565 $errorno = self::$dbo->errorno;
567 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
568 System::callstack(8)."\n".self::replace_parameters($sql, $params));
570 self::$dbo->error = $error;
571 self::$dbo->errorno = $errorno;
574 $a->save_timestamp($stamp1, 'database');
576 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
578 $stamp2 = microtime(true);
579 $duration = (float)($stamp2 - $stamp1);
581 if (($duration > $a->config["system"]["db_loglimit"])) {
582 $duration = round($duration, 3);
583 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
585 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
586 basename($backtrace[1]["file"])."\t".
587 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
588 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
595 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
597 * Please use dba::delete, dba::insert, dba::update, ... instead
599 * @param string $sql SQL statement
600 * @return boolean Was the query successfull? False is returned only if an error occurred
602 public static function e($sql) {
607 $stamp = microtime(true);
609 $params = self::getParam(func_get_args());
611 // In a case of a deadlock we are repeating the query 20 times
615 $stmt = self::p($sql, $params);
617 if (is_bool($stmt)) {
619 } elseif (is_object($stmt)) {
627 } while ((self::$dbo->errorno == 1213) && (--$timeout > 0));
629 if (self::$dbo->errorno != 0) {
630 // We have to preserve the error code, somewhere in the logging it get lost
631 $error = self::$dbo->error;
632 $errorno = self::$dbo->errorno;
634 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
635 System::callstack(8)."\n".self::replace_parameters($sql, $params));
637 self::$dbo->error = $error;
638 self::$dbo->errorno = $errorno;
641 $a->save_timestamp($stamp, "database_write");
647 * @brief Check if data exists
649 * @param string $table Table name
650 * @param array $condition array of fields for condition
652 * @return boolean Are there rows for that condition?
654 public static function exists($table, $condition) {
663 $array_element = each($condition);
664 $array_key = $array_element['key'];
665 if (!is_int($array_key)) {
666 $fields = array($array_key);
669 $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
671 if (is_bool($stmt)) {
674 $retval = (self::num_rows($stmt) > 0);
683 * @brief Fetches the first row
685 * Please use dba::select or dba::exists whenever this is possible.
687 * @param string $sql SQL statement
688 * @return array first row of query
690 public static function fetch_first($sql) {
693 $params = self::getParam(func_get_args());
695 $stmt = self::p($sql, $params);
697 if (is_bool($stmt)) {
700 $retval = self::fetch($stmt);
709 * @brief Returns the number of affected rows of the last statement
711 * @return int Number of rows
713 public static function affected_rows() {
716 return self::$dbo->affected_rows;
720 * @brief Returns the number of columns of a statement
722 * @param object Statement object
723 * @return int Number of columns
725 public static function columnCount($stmt) {
728 if (!is_object($stmt)) {
731 switch (self::$dbo->driver) {
733 return $stmt->columnCount();
735 return $stmt->field_count;
737 return mysql_affected_rows($stmt);
742 * @brief Returns the number of rows of a statement
744 * @param object Statement object
745 * @return int Number of rows
747 public static function num_rows($stmt) {
750 if (!is_object($stmt)) {
753 switch (self::$dbo->driver) {
755 return $stmt->rowCount();
757 return $stmt->num_rows;
759 return mysql_num_rows($stmt);
765 * @brief Fetch a single row
767 * @param object $stmt statement object
768 * @return array current row
770 public static function fetch($stmt) {
773 if (!is_object($stmt)) {
777 switch (self::$dbo->driver) {
779 return $stmt->fetch(PDO::FETCH_ASSOC);
781 if (get_class($stmt) == 'mysqli_result') {
782 return $stmt->fetch_assoc();
785 // This code works, but is slow
787 // Bind the result to a result array
791 for ($x = 0; $x < $stmt->field_count; $x++) {
792 $cols[] = &$cols_num[$x];
795 call_user_func_array(array($stmt, 'bind_result'), $cols);
797 if (!$stmt->fetch()) {
802 // We need to get the field names for the array keys
803 // It seems that there is no better way to do this.
804 $result = $stmt->result_metadata();
805 $fields = $result->fetch_fields();
808 foreach ($cols_num AS $param => $col) {
809 $columns[$fields[$param]->name] = $col;
813 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
818 * @brief Insert a row into a table
820 * @param string $table Table name
821 * @param array $param parameter array
822 * @param bool $on_duplicate_update Do an update on a duplicate entry
824 * @return boolean was the insert successfull?
826 public static function insert($table, $param, $on_duplicate_update = false) {
829 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
830 substr(str_repeat("?, ", count($param)), 0, -2).")";
832 if ($on_duplicate_update) {
833 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
835 $values = array_values($param);
836 $param = array_merge_recursive($values, $values);
839 return self::e($sql, $param);
843 * @brief Fetch the id of the last insert command
845 * @return integer Last inserted id
847 public static function lastInsertId() {
850 switch (self::$dbo->driver) {
852 $id = self::$dbo->db->lastInsertId();
855 $id = self::$dbo->db->insert_id;
858 $id = mysql_insert_id(self::$dbo);
865 * @brief Locks a table for exclusive write access
867 * This function can be extended in the future to accept a table array as well.
869 * @param string $table Table name
871 * @return boolean was the lock successful?
873 public static function lock($table) {
876 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
877 self::e("SET autocommit=0");
878 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
880 self::e("SET autocommit=1");
882 self::$in_transaction = true;
888 * @brief Unlocks all locked tables
890 * @return boolean was the unlock successful?
892 public static function unlock() {
895 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
897 $success = self::e("UNLOCK TABLES");
898 self::e("SET autocommit=1");
899 self::$in_transaction = false;
904 * @brief Starts a transaction
906 * @return boolean Was the command executed successfully?
908 public static function transaction() {
911 if (!self::e('COMMIT')) {
914 if (!self::e('START TRANSACTION')) {
917 self::$in_transaction = true;
922 * @brief Does a commit
924 * @return boolean Was the command executed successfully?
926 public static function commit() {
929 if (!self::e('COMMIT')) {
932 self::$in_transaction = false;
937 * @brief Does a rollback
939 * @return boolean Was the command executed successfully?
941 public static function rollback() {
944 if (!self::e('ROLLBACK')) {
947 self::$in_transaction = false;
952 * @brief Build the array with the table relations
954 * The array is build from the database definitions in dbstructure.php
956 * This process must only be started once, since the value is cached.
958 private static function build_relation_data() {
959 $definition = db_definition();
961 foreach ($definition AS $table => $structure) {
962 foreach ($structure['fields'] AS $field => $field_struct) {
963 if (isset($field_struct['relation'])) {
964 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
965 self::$relation[$rel_table][$rel_field][$table][] = $field;
973 * @brief Delete a row from a table
975 * @param string $table Table name
976 * @param array $param parameter array
977 * @param boolean $in_process Internal use: Only do a commit after the last delete
978 * @param array $callstack Internal use: prevent endless loops
980 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
982 public static function delete($table, $param, $in_process = false, &$callstack = array()) {
987 // Create a key for the loop prevention
988 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
990 // We quit when this key already exists in the callstack.
991 if (isset($callstack[$key])) {
995 $callstack[$key] = true;
997 $table = self::$dbo->escape($table);
999 $commands[$key] = array('table' => $table, 'param' => $param);
1001 // To speed up the whole process we cache the table relations
1002 if (count(self::$relation) == 0) {
1003 self::build_relation_data();
1006 // Is there a relation entry for the table?
1007 if (isset(self::$relation[$table])) {
1008 // We only allow a simple "one field" relation.
1009 $field = array_keys(self::$relation[$table])[0];
1010 $rel_def = array_values(self::$relation[$table])[0];
1012 // Create a key for preventing double queries
1013 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
1015 // When the search field is the relation field, we don't need to fetch the rows
1016 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1017 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
1018 foreach ($rel_def AS $rel_table => $rel_fields) {
1019 foreach ($rel_fields AS $rel_field) {
1020 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
1021 $commands = array_merge($commands, $retval);
1024 // We quit when this key already exists in the callstack.
1025 } elseif (!isset($callstack[$qkey])) {
1027 $callstack[$qkey] = true;
1029 // Fetch all rows that are to be deleted
1030 $data = self::select($table, array($field), $param);
1032 while ($row = self::fetch($data)) {
1033 // Now we accumulate the delete commands
1034 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
1035 $commands = array_merge($commands, $retval);
1040 // Since we had split the delete command we don't need the original command anymore
1041 unset($commands[$key]);
1046 // Now we finalize the process
1047 $do_transaction = !self::$in_transaction;
1049 if ($do_transaction) {
1050 self::transaction();
1053 $compacted = array();
1056 foreach ($commands AS $command) {
1057 $condition = $command['param'];
1058 $array_element = each($condition);
1059 $array_key = $array_element['key'];
1060 if (is_int($array_key)) {
1061 $condition_string = " WHERE ".array_shift($condition);
1063 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1066 if ((count($command['param']) > 1) || is_int($array_key)) {
1067 $sql = "DELETE FROM `".$command['table']."`".$condition_string;
1068 logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
1070 if (!self::e($sql, $condition)) {
1071 if ($do_transaction) {
1077 $key_table = $command['table'];
1078 $key_param = array_keys($command['param'])[0];
1079 $value = array_values($command['param'])[0];
1081 // Split the SQL queries in chunks of 100 values
1082 // We do the $i stuff here to make the code better readable
1083 $i = $counter[$key_table][$key_param];
1084 if (count($compacted[$key_table][$key_param][$i]) > 100) {
1088 $compacted[$key_table][$key_param][$i][$value] = $value;
1089 $counter[$key_table][$key_param] = $i;
1092 foreach ($compacted AS $table => $values) {
1093 foreach ($values AS $field => $field_value_list) {
1094 foreach ($field_value_list AS $field_values) {
1095 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1096 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1098 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
1100 if (!self::e($sql, $field_values)) {
1101 if ($do_transaction) {
1109 if ($do_transaction) {
1119 * @brief Updates rows
1121 * Updates rows in the database. When $old_fields is set to an array,
1122 * the system will only do an update if the fields in that array changed.
1125 * Only the values in $old_fields are compared.
1126 * This is an intentional behaviour.
1129 * We include the timestamp field in $fields but not in $old_fields.
1130 * Then the row will only get the new timestamp when the other fields had changed.
1132 * When $old_fields is set to a boolean value the system will do this compare itself.
1133 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1136 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1137 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1139 * @param string $table Table name
1140 * @param array $fields contains the fields that are updated
1141 * @param array $condition condition array with the key values
1142 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1144 * @return boolean was the update successfull?
1146 public static function update($table, $fields, $condition, $old_fields = array()) {
1149 $table = self::$dbo->escape($table);
1151 if (count($condition) > 0) {
1152 $array_element = each($condition);
1153 $array_key = $array_element['key'];
1154 if (is_int($array_key)) {
1155 $condition_string = " WHERE ".array_shift($condition);
1157 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1160 $condition_string = "";
1163 if (is_bool($old_fields)) {
1164 $do_insert = $old_fields;
1166 $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1168 if (is_bool($old_fields)) {
1170 $values = array_merge($condition, $fields);
1171 return self::insert($table, $values, $do_insert);
1173 $old_fields = array();
1177 $do_update = (count($old_fields) == 0);
1179 foreach ($old_fields AS $fieldname => $content) {
1180 if (isset($fields[$fieldname])) {
1181 if ($fields[$fieldname] == $content) {
1182 unset($fields[$fieldname]);
1189 if (!$do_update || (count($fields) == 0)) {
1193 $sql = "UPDATE `".$table."` SET `".
1194 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1196 $params1 = array_values($fields);
1197 $params2 = array_values($condition);
1198 $params = array_merge_recursive($params1, $params2);
1200 return self::e($sql, $params);
1204 * @brief Select rows from a table
1206 * @param string $table Table name
1207 * @param array $fields array of selected fields
1208 * @param array $condition array of fields for condition
1209 * @param array $params array of several parameters
1211 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1215 * $fields = array("id", "uri", "uid", "network");
1217 * $condition = array("uid" => 1, "network" => 'dspr');
1219 * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1221 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1223 * $data = dba::select($table, $fields, $condition, $params);
1225 public static function select($table, $fields = array(), $condition = array(), $params = array()) {
1232 if (count($fields) > 0) {
1233 $select_fields = "`".implode("`, `", array_values($fields))."`";
1235 $select_fields = "*";
1238 if (count($condition) > 0) {
1239 $array_element = each($condition);
1240 $array_key = $array_element['key'];
1241 if (is_int($array_key)) {
1242 $condition_string = " WHERE ".array_shift($condition);
1244 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1247 $condition_string = "";
1251 $single_row = false;
1253 if (isset($params['order'])) {
1254 $param_string .= " ORDER BY ";
1255 foreach ($params['order'] AS $fields => $order) {
1256 if (!is_int($fields)) {
1257 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1259 $param_string .= "`".$order."`, ";
1262 $param_string = substr($param_string, 0, -2);
1265 if (isset($params['limit']) && is_int($params['limit'])) {
1266 $param_string .= " LIMIT ".$params['limit'];
1267 $single_row = ($params['limit'] == 1);
1270 if (isset($params['only_query']) && $params['only_query']) {
1271 $single_row = !$params['only_query'];
1274 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1276 $result = self::p($sql, $condition);
1278 if (is_bool($result) || !$single_row) {
1281 $row = self::fetch($result);
1282 self::close($result);
1289 * @brief Fills an array with data from a query
1291 * @param object $stmt statement object
1292 * @return array Data array
1294 public static function inArray($stmt, $do_close = true) {
1297 if (is_bool($stmt)) {
1302 while ($row = self::fetch($stmt)) {
1312 * @brief Returns the error number of the last query
1314 * @return string Error number (0 if no error)
1316 public static function errorNo() {
1319 return self::$dbo->errorno;
1323 * @brief Returns the error message of the last query
1325 * @return string Error message ('' if no error)
1327 public static function errorMessage() {
1330 return self::$dbo->error;
1334 * @brief Closes the current statement
1336 * @param object $stmt statement object
1337 * @return boolean was the close successfull?
1339 public static function close($stmt) {
1342 if (!is_object($stmt)) {
1346 switch (self::$dbo->driver) {
1348 return $stmt->closeCursor();
1350 return $stmt->free_result();
1351 return $stmt->close();
1353 return mysql_free_result($stmt);
1358 function dbesc($str) {
1361 if ($db && $db->connected) {
1362 return($db->escape($str));
1364 return(str_replace("'","\\'",$str));
1369 * @brief execute SQL query with printf style args - deprecated
1371 * Please use the dba:: functions instead:
1372 * dba::select, dba::exists, dba::insert
1373 * dba::delete, dba::update, dba::p, dba::e
1375 * @param $args Query parameters (1 to N parameters of different types)
1376 * @return array Query array
1381 $args = func_get_args();
1384 if (!$db || !$db->connected) {
1388 $sql = $db->clean_query($sql);
1389 $sql = $db->any_value_fallback($sql);
1391 $stmt = @vsprintf($sql, $args);
1393 $ret = dba::p($stmt);
1395 if (is_bool($ret)) {
1399 $columns = dba::columnCount($ret);
1401 $data = dba::inArray($ret);
1403 if ((count($data) == 0) && ($columns == 0)) {
1410 function dba_timer() {
1411 return microtime(true);