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);
217 public function q($sql, $onlyquery = false) {
220 if (!$this->db || !$this->connected) {
226 $connstr = ($this->connected() ? "Connected" : "Disonnected");
228 $stamp1 = microtime(true);
232 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
233 $sql = "/*".System::callstack()." */ ".$sql;
238 switch ($this->driver) {
240 $result = @$this->db->query($sql);
241 // Is used to separate between queries that returning data - or not
242 if (!is_bool($result)) {
243 $columns = $result->columnCount();
247 $result = @$this->db->query($sql);
250 $result = @mysql_query($sql,$this->db);
253 $stamp2 = microtime(true);
254 $duration = (float)($stamp2 - $stamp1);
256 $a->save_timestamp($stamp1, "database");
258 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
259 $a->save_timestamp($stamp1, "database_write");
261 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
262 if (($duration > $a->config["system"]["db_loglimit"])) {
263 $duration = round($duration, 3);
264 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
265 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
266 basename($backtrace[1]["file"])."\t".
267 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
268 substr($sql, 0, 2000)."\n", FILE_APPEND);
272 switch ($this->driver) {
274 $errorInfo = $this->db->errorInfo();
276 $this->error = $errorInfo[2];
277 $this->errorno = $errorInfo[1];
281 if ($this->db->errno) {
282 $this->error = $this->db->error;
283 $this->errorno = $this->db->errno;
287 if (mysql_errno($this->db)) {
288 $this->error = mysql_error($this->db);
289 $this->errorno = mysql_errno($this->db);
293 if (strlen($this->error)) {
294 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
301 if ($result === false) {
303 } elseif ($result === true) {
306 switch ($this->driver) {
308 $mesg = $result->rowCount().' results'.EOL;
311 $mesg = $result->num_rows.' results'.EOL;
314 $mesg = mysql_num_rows($result).' results'.EOL;
319 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
320 . (($this->error) ? ' error: ' . $this->error : '')
323 logger('dba: ' . $str );
327 * If dbfail.out exists, we will write any failed calls directly to it,
328 * regardless of any logging that may or may nor be in effect.
329 * These usually indicate SQL syntax errors that need to be resolved.
332 if ($result === false) {
333 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
334 if (file_exists('dbfail.out')) {
335 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
339 if (is_bool($result)) {
343 $this->result = $result;
348 switch ($this->driver) {
350 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
353 $result->closeCursor();
356 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
359 $result->free_result();
362 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
365 mysql_free_result($result);
369 // PDO doesn't return "true" on successful operations - like mysqli does
370 // Emulate this behaviour by checking if the query returned data and had columns
371 // This should be reliable enough
372 if (($this->driver == 'pdo') && (count($r) == 0) && ($columns == 0)) {
376 //$a->save_timestamp($stamp1, "database");
379 logger('dba: ' . printable(print_r($r, true)));
384 public function dbg($dbg) {
388 public function escape($str) {
389 if ($this->db && $this->connected) {
390 switch ($this->driver) {
392 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
394 return @$this->db->real_escape_string($str);
396 return @mysql_real_escape_string($str,$this->db);
401 function connected() {
402 switch ($this->driver) {
404 // Not sure if this really is working like expected
405 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
408 $connected = $this->db->ping();
411 $connected = mysql_ping($this->db);
417 function __destruct() {
419 switch ($this->driver) {
427 mysql_close($this->db);
434 * @brief Replaces ANY_VALUE() function by MIN() function,
435 * if the database server does not support ANY_VALUE().
437 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
438 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
439 * A standard fall-back is to use MIN().
441 * @param string $sql An SQL string without the values
442 * @return string The input SQL string modified if necessary.
444 public function any_value_fallback($sql) {
445 $server_info = $this->server_info();
446 if (version_compare($server_info, '5.7.5', '<') ||
447 (stripos($server_info, 'MariaDB') !== false)) {
448 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
454 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
456 * This is safe when we bind the parameters later.
457 * The parameter values aren't part of the SQL.
459 * @param string $sql An SQL string without the values
460 * @return string The input SQL string modified if necessary.
462 public function clean_query($sql) {
463 $search = array("\t", "\n", "\r", " ");
464 $replace = array(' ', ' ', ' ', ' ');
467 $sql = str_replace($search, $replace, $sql);
468 } while ($oldsql != $sql);
475 * @brief Replaces the ? placeholders with the parameters in the $args array
477 * @param string $sql SQL query
478 * @param array $args The parameters that are to replace the ? placeholders
479 * @return string The replaced SQL query
481 private static function replace_parameters($sql, $args) {
483 foreach ($args AS $param => $value) {
484 if (is_int($args[$param]) || is_float($args[$param])) {
485 $replace = intval($args[$param]);
487 $replace = "'".self::$dbo->escape($args[$param])."'";
490 $pos = strpos($sql, '?', $offset);
491 if ($pos !== false) {
492 $sql = substr_replace($sql, $replace, $pos, 1);
494 $offset = $pos + strlen($replace);
500 * @brief Convert parameter array to an universal form
501 * @param array $args Parameter array
502 * @return array universalized parameter array
504 private static function getParam($args) {
507 // When the second function parameter is an array then use this as the parameter array
508 if ((count($args) > 0) && (is_array($args[1]))) {
516 * @brief Executes a prepared statement that returns data
517 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
518 * @param string $sql SQL statement
519 * @return object statement object
521 public static function p($sql) {
524 $stamp1 = microtime(true);
526 $params = self::getParam(func_get_args());
528 // Renumber the array keys to be sure that they fit
531 foreach ($params AS $param) {
532 // Avoid problems with some MySQL servers and boolean values. See issue #3645
533 if (is_bool($param)) {
534 $param = (int)$param;
536 $args[++$i] = $param;
539 if (!self::$dbo || !self::$dbo->connected) {
543 if (substr_count($sql, '?') != count($args)) {
544 // Question: Should we continue or stop the query here?
545 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
548 $sql = self::$dbo->clean_query($sql);
549 $sql = self::$dbo->any_value_fallback($sql);
553 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
554 $sql = "/*".System::callstack()." */ ".$sql;
557 self::$dbo->error = '';
558 self::$dbo->errorno = 0;
559 self::$dbo->affected_rows = 0;
561 // We have to make some things different if this function is called from "e"
562 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
564 if (isset($trace[1])) {
565 $called_from = $trace[1];
567 // We use just something that is defined to avoid warnings
568 $called_from = $trace[0];
570 // We are having an own error logging in the function "e"
571 $called_from_e = ($called_from['function'] == 'e');
573 switch (self::$dbo->driver) {
575 if (!$stmt = self::$dbo->db->prepare($sql)) {
576 $errorInfo = self::$dbo->db->errorInfo();
577 self::$dbo->error = $errorInfo[2];
578 self::$dbo->errorno = $errorInfo[1];
583 foreach ($args AS $param => $value) {
584 $stmt->bindParam($param, $args[$param]);
587 if (!$stmt->execute()) {
588 $errorInfo = $stmt->errorInfo();
589 self::$dbo->error = $errorInfo[2];
590 self::$dbo->errorno = $errorInfo[1];
594 self::$dbo->affected_rows = $retval->rowCount();
598 // There are SQL statements that cannot be executed with a prepared statement
599 $parts = explode(' ', $orig_sql);
600 $command = strtolower($parts[0]);
601 $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
603 // The fallback routine currently only works with statements that doesn't return values
604 if (!$can_be_prepared && $called_from_e) {
605 $retval = self::$dbo->db->query(self::replace_parameters($sql, $args));
606 if (self::$dbo->db->errno) {
607 self::$dbo->error = self::$dbo->db->error;
608 self::$dbo->errorno = self::$dbo->db->errno;
611 if (isset($retval->num_rows)) {
612 self::$dbo->affected_rows = $retval->num_rows;
614 self::$dbo->affected_rows = self::$dbo->db->affected_rows;
620 $stmt = self::$dbo->db->stmt_init();
622 if (!$stmt->prepare($sql)) {
623 self::$dbo->error = $stmt->error;
624 self::$dbo->errorno = $stmt->errno;
631 foreach ($args AS $param => $value) {
632 if (is_int($args[$param])) {
634 } elseif (is_float($args[$param])) {
636 } elseif (is_string($args[$param])) {
641 $values[] = &$args[$param];
644 if (count($values) > 0) {
645 array_unshift($values, $params);
646 call_user_func_array(array($stmt, 'bind_param'), $values);
649 if (!$stmt->execute()) {
650 self::$dbo->error = self::$dbo->db->error;
651 self::$dbo->errorno = self::$dbo->db->errno;
654 $stmt->store_result();
656 self::$dbo->affected_rows = $retval->affected_rows;
660 // For the old "mysql" functions we cannot use prepared statements
661 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
662 if (mysql_errno(self::$dbo->db)) {
663 self::$dbo->error = mysql_error(self::$dbo->db);
664 self::$dbo->errorno = mysql_errno(self::$dbo->db);
666 self::$dbo->affected_rows = mysql_affected_rows($retval);
668 // Due to missing mysql_* support this here wasn't tested at all
669 // See here: http://php.net/manual/en/function.mysql-num-rows.php
670 if (self::$dbo->affected_rows <= 0) {
671 self::$dbo->affected_rows = mysql_num_rows($retval);
677 // We are having an own error logging in the function "e"
678 if ((self::$dbo->errorno != 0) && !$called_from_e) {
679 // We have to preserve the error code, somewhere in the logging it get lost
680 $error = self::$dbo->error;
681 $errorno = self::$dbo->errorno;
683 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
684 System::callstack(8)."\n".self::replace_parameters($sql, $params));
686 self::$dbo->error = $error;
687 self::$dbo->errorno = $errorno;
690 $a->save_timestamp($stamp1, 'database');
692 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
694 $stamp2 = microtime(true);
695 $duration = (float)($stamp2 - $stamp1);
697 if (($duration > $a->config["system"]["db_loglimit"])) {
698 $duration = round($duration, 3);
699 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
701 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
702 basename($backtrace[1]["file"])."\t".
703 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
704 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
711 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
713 * @param string $sql SQL statement
714 * @return boolean Was the query successfull? False is returned only if an error occurred
716 public static function e($sql) {
719 $stamp = microtime(true);
721 $params = self::getParam(func_get_args());
723 // In a case of a deadlock we are repeating the query 20 times
727 $stmt = self::p($sql, $params);
729 if (is_bool($stmt)) {
731 } elseif (is_object($stmt)) {
739 } while ((self::$dbo->errorno == 1213) && (--$timeout > 0));
741 if (self::$dbo->errorno != 0) {
742 // We have to preserve the error code, somewhere in the logging it get lost
743 $error = self::$dbo->error;
744 $errorno = self::$dbo->errorno;
746 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
747 System::callstack(8)."\n".self::replace_parameters($sql, $params));
749 self::$dbo->error = $error;
750 self::$dbo->errorno = $errorno;
753 $a->save_timestamp($stamp, "database_write");
759 * @brief Check if data exists
761 * @param string $table Table name
762 * @param array $condition array of fields for condition
764 * @return boolean Are there rows for that condition?
766 public static function exists($table, $condition) {
773 $array_element = each($condition);
774 $array_key = $array_element['key'];
775 if (!is_int($array_key)) {
776 $fields = array($array_key);
779 $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
781 if (is_bool($stmt)) {
784 $retval = (self::num_rows($stmt) > 0);
793 * @brief Fetches the first row
795 * @param string $sql SQL statement
796 * @return array first row of query
798 public static function fetch_first($sql) {
799 $params = self::getParam(func_get_args());
801 $stmt = self::p($sql, $params);
803 if (is_bool($stmt)) {
806 $retval = self::fetch($stmt);
815 * @brief Returns the number of affected rows of the last statement
817 * @return int Number of rows
819 public static function affected_rows() {
820 return self::$dbo->affected_rows;
824 * @brief Returns the number of rows of a statement
826 * @param object Statement object
827 * @return int Number of rows
829 public static function num_rows($stmt) {
830 if (!is_object($stmt)) {
833 switch (self::$dbo->driver) {
835 return $stmt->rowCount();
837 return $stmt->num_rows;
839 return mysql_num_rows($stmt);
845 * @brief Fetch a single row
847 * @param object $stmt statement object
848 * @return array current row
850 public static function fetch($stmt) {
851 if (!is_object($stmt)) {
855 switch (self::$dbo->driver) {
857 return $stmt->fetch(PDO::FETCH_ASSOC);
859 // This code works, but is slow
861 // Bind the result to a result array
865 for ($x = 0; $x < $stmt->field_count; $x++) {
866 $cols[] = &$cols_num[$x];
869 call_user_func_array(array($stmt, 'bind_result'), $cols);
871 if (!$stmt->fetch()) {
876 // We need to get the field names for the array keys
877 // It seems that there is no better way to do this.
878 $result = $stmt->result_metadata();
879 $fields = $result->fetch_fields();
882 foreach ($cols_num AS $param => $col) {
883 $columns[$fields[$param]->name] = $col;
887 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
892 * @brief Insert a row into a table
894 * @param string $table Table name
895 * @param array $param parameter array
896 * @param bool $on_duplicate_update Do an update on a duplicate entry
898 * @return boolean was the insert successfull?
900 public static function insert($table, $param, $on_duplicate_update = false) {
901 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
902 substr(str_repeat("?, ", count($param)), 0, -2).")";
904 if ($on_duplicate_update) {
905 $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
907 $values = array_values($param);
908 $param = array_merge_recursive($values, $values);
911 return self::e($sql, $param);
915 * @brief Fetch the id of the last insert command
917 * @return integer Last inserted id
919 public static function lastInsertId() {
920 switch (self::$dbo->driver) {
922 $id = self::$dbo->db->lastInsertId();
925 $id = self::$dbo->db->insert_id;
928 $id = mysql_insert_id(self::$dbo);
935 * @brief Locks a table for exclusive write access
937 * This function can be extended in the future to accept a table array as well.
939 * @param string $table Table name
941 * @return boolean was the lock successful?
943 public static function lock($table) {
944 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
945 self::e("SET autocommit=0");
946 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
948 self::e("SET autocommit=1");
950 self::$in_transaction = true;
956 * @brief Unlocks all locked tables
958 * @return boolean was the unlock successful?
960 public static function unlock() {
961 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
963 $success = self::e("UNLOCK TABLES");
964 self::e("SET autocommit=1");
965 self::$in_transaction = false;
970 * @brief Starts a transaction
972 * @return boolean Was the command executed successfully?
974 public static function transaction() {
975 if (!self::e('COMMIT')) {
978 if (!self::e('START TRANSACTION')) {
981 self::$in_transaction = true;
986 * @brief Does a commit
988 * @return boolean Was the command executed successfully?
990 public static function commit() {
991 if (!self::e('COMMIT')) {
994 self::$in_transaction = false;
999 * @brief Does a rollback
1001 * @return boolean Was the command executed successfully?
1003 public static function rollback() {
1004 if (!self::e('ROLLBACK')) {
1007 self::$in_transaction = false;
1012 * @brief Build the array with the table relations
1014 * The array is build from the database definitions in dbstructure.php
1016 * This process must only be started once, since the value is cached.
1018 private static function build_relation_data() {
1019 $definition = db_definition();
1021 foreach ($definition AS $table => $structure) {
1022 foreach ($structure['fields'] AS $field => $field_struct) {
1023 if (isset($field_struct['relation'])) {
1024 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
1025 self::$relation[$rel_table][$rel_field][$table][] = $field;
1033 * @brief Delete a row from a table
1035 * @param string $table Table name
1036 * @param array $param parameter array
1037 * @param boolean $in_process Internal use: Only do a commit after the last delete
1038 * @param array $callstack Internal use: prevent endless loops
1040 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
1042 public static function delete($table, $param, $in_process = false, &$callstack = array()) {
1044 $commands = array();
1046 // Create a key for the loop prevention
1047 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
1049 // We quit when this key already exists in the callstack.
1050 if (isset($callstack[$key])) {
1054 $callstack[$key] = true;
1056 $table = self::$dbo->escape($table);
1058 $commands[$key] = array('table' => $table, 'param' => $param);
1060 // To speed up the whole process we cache the table relations
1061 if (count(self::$relation) == 0) {
1062 self::build_relation_data();
1065 // Is there a relation entry for the table?
1066 if (isset(self::$relation[$table])) {
1067 // We only allow a simple "one field" relation.
1068 $field = array_keys(self::$relation[$table])[0];
1069 $rel_def = array_values(self::$relation[$table])[0];
1071 // Create a key for preventing double queries
1072 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
1074 // When the search field is the relation field, we don't need to fetch the rows
1075 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1076 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
1077 foreach ($rel_def AS $rel_table => $rel_fields) {
1078 foreach ($rel_fields AS $rel_field) {
1079 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
1080 $commands = array_merge($commands, $retval);
1083 // We quit when this key already exists in the callstack.
1084 } elseif (!isset($callstack[$qkey])) {
1086 $callstack[$qkey] = true;
1088 // Fetch all rows that are to be deleted
1089 $data = self::select($table, array($field), $param);
1091 while ($row = self::fetch($data)) {
1092 // Now we accumulate the delete commands
1093 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
1094 $commands = array_merge($commands, $retval);
1099 // Since we had split the delete command we don't need the original command anymore
1100 unset($commands[$key]);
1105 // Now we finalize the process
1106 $do_transaction = !self::$in_transaction;
1108 if ($do_transaction) {
1109 self::transaction();
1112 $compacted = array();
1115 foreach ($commands AS $command) {
1116 $condition = $command['param'];
1117 $array_element = each($condition);
1118 $array_key = $array_element['key'];
1119 if (is_int($array_key)) {
1120 $condition_string = " WHERE ".array_shift($condition);
1122 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1125 if ((count($command['param']) > 1) || is_int($array_key)) {
1126 $sql = "DELETE FROM `".$command['table']."`".$condition_string;
1127 logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
1129 if (!self::e($sql, $condition)) {
1130 if ($do_transaction) {
1136 $key_table = $command['table'];
1137 $key_param = array_keys($command['param'])[0];
1138 $value = array_values($command['param'])[0];
1140 // Split the SQL queries in chunks of 100 values
1141 // We do the $i stuff here to make the code better readable
1142 $i = $counter[$key_table][$key_param];
1143 if (count($compacted[$key_table][$key_param][$i]) > 100) {
1147 $compacted[$key_table][$key_param][$i][$value] = $value;
1148 $counter[$key_table][$key_param] = $i;
1151 foreach ($compacted AS $table => $values) {
1152 foreach ($values AS $field => $field_value_list) {
1153 foreach ($field_value_list AS $field_values) {
1154 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1155 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1157 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
1159 if (!self::e($sql, $field_values)) {
1160 if ($do_transaction) {
1168 if ($do_transaction) {
1178 * @brief Updates rows
1180 * Updates rows in the database. When $old_fields is set to an array,
1181 * the system will only do an update if the fields in that array changed.
1184 * Only the values in $old_fields are compared.
1185 * This is an intentional behaviour.
1188 * We include the timestamp field in $fields but not in $old_fields.
1189 * Then the row will only get the new timestamp when the other fields had changed.
1191 * When $old_fields is set to a boolean value the system will do this compare itself.
1192 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1195 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1196 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1198 * @param string $table Table name
1199 * @param array $fields contains the fields that are updated
1200 * @param array $condition condition array with the key values
1201 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1203 * @return boolean was the update successfull?
1205 public static function update($table, $fields, $condition, $old_fields = array()) {
1207 $table = self::$dbo->escape($table);
1209 if (count($condition) > 0) {
1210 $array_element = each($condition);
1211 $array_key = $array_element['key'];
1212 if (is_int($array_key)) {
1213 $condition_string = " WHERE ".array_shift($condition);
1215 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1218 $condition_string = "";
1221 if (is_bool($old_fields)) {
1222 $do_insert = $old_fields;
1224 $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1226 if (is_bool($old_fields)) {
1228 $values = array_merge($condition, $fields);
1229 return self::insert($table, $values, $do_insert);
1231 $old_fields = array();
1235 $do_update = (count($old_fields) == 0);
1237 foreach ($old_fields AS $fieldname => $content) {
1238 if (isset($fields[$fieldname])) {
1239 if ($fields[$fieldname] == $content) {
1240 unset($fields[$fieldname]);
1247 if (!$do_update || (count($fields) == 0)) {
1251 $sql = "UPDATE `".$table."` SET `".
1252 implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1254 $params1 = array_values($fields);
1255 $params2 = array_values($condition);
1256 $params = array_merge_recursive($params1, $params2);
1258 return self::e($sql, $params);
1262 * @brief Select rows from a table
1264 * @param string $table Table name
1265 * @param array $fields array of selected fields
1266 * @param array $condition array of fields for condition
1267 * @param array $params array of several parameters
1269 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1273 * $fields = array("id", "uri", "uid", "network");
1274 * $condition = array("uid" => 1, "network" => 'dspr');
1275 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1277 * $data = dba::select($table, $fields, $condition, $params);
1279 public static function select($table, $fields = array(), $condition = array(), $params = array()) {
1284 if (count($fields) > 0) {
1285 $select_fields = "`".implode("`, `", array_values($fields))."`";
1287 $select_fields = "*";
1290 if (count($condition) > 0) {
1291 $array_element = each($condition);
1292 $array_key = $array_element['key'];
1293 if (is_int($array_key)) {
1294 $condition_string = " WHERE ".array_shift($condition);
1296 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1299 $condition_string = "";
1303 $single_row = false;
1305 if (isset($params['order'])) {
1306 $param_string .= " ORDER BY ";
1307 foreach ($params['order'] AS $fields => $order) {
1308 if (!is_int($fields)) {
1309 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1311 $param_string .= "`".$order."`, ";
1314 $param_string = substr($param_string, 0, -2);
1317 if (isset($params['limit']) && is_int($params['limit'])) {
1318 $param_string .= " LIMIT ".$params['limit'];
1319 $single_row = ($params['limit'] == 1);
1322 if (isset($params['only_query']) && $params['only_query']) {
1323 $single_row = !$params['only_query'];
1326 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1328 $result = self::p($sql, $condition);
1330 if (is_bool($result) || !$single_row) {
1333 $row = self::fetch($result);
1334 self::close($result);
1341 * @brief Fills an array with data from a query
1343 * @param object $stmt statement object
1344 * @return array Data array
1346 public static function inArray($stmt, $do_close = true) {
1347 if (is_bool($stmt)) {
1352 while ($row = self::fetch($stmt)) {
1362 * @brief Closes the current statement
1364 * @param object $stmt statement object
1365 * @return boolean was the close successfull?
1367 public static function close($stmt) {
1368 if (!is_object($stmt)) {
1372 switch (self::$dbo->driver) {
1374 return $stmt->closeCursor();
1376 return $stmt->free_result();
1377 return $stmt->close();
1379 return mysql_free_result($stmt);
1384 function printable($s) {
1385 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
1386 $s = str_replace("\x00",'.',$s);
1387 if (x($_SERVER,'SERVER_NAME')) {
1388 $s = escape_tags($s);
1393 // Procedural functions
1394 function dbg($state) {
1402 function dbesc($str) {
1405 if ($db && $db->connected) {
1406 return($db->escape($str));
1408 return(str_replace("'","\\'",$str));
1412 // Function: q($sql,$args);
1413 // Description: execute SQL query with printf style args.
1414 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
1418 $args = func_get_args();
1421 if ($db && $db->connected) {
1422 $sql = $db->clean_query($sql);
1423 $sql = $db->any_value_fallback($sql);
1424 $stmt = @vsprintf($sql,$args); // Disabled warnings
1425 //logger("dba: q: $stmt", LOGGER_ALL);
1426 if ($stmt === false)
1427 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1429 $db->log_index($stmt);
1431 return $db->q($stmt);
1436 * This will happen occasionally trying to store the
1437 * session data after abnormal program termination
1440 logger('dba: no database: ' . print_r($args,true));
1445 * @brief Performs a query with "dirty reads"
1447 * By doing dirty reads (reading uncommitted data) no locks are performed
1448 * This function can be used to fetch data that doesn't need to be reliable.
1450 * @param $args Query parameters (1 to N parameters of different types)
1451 * @return array Query array
1456 $args = func_get_args();
1459 if ($db && $db->connected) {
1460 $sql = $db->clean_query($sql);
1461 $sql = $db->any_value_fallback($sql);
1462 $stmt = @vsprintf($sql,$args); // Disabled warnings
1463 if ($stmt === false)
1464 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1466 $db->log_index($stmt);
1468 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
1469 $retval = $db->q($stmt);
1470 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
1476 * This will happen occasionally trying to store the
1477 * session data after abnormal program termination
1480 logger('dba: no database: ' . print_r($args,true));
1486 * Raw db query, no arguments
1489 function dbq($sql) {
1492 if ($db && $db->connected) {
1493 $ret = $db->q($sql);
1500 // Caller is responsible for ensuring that any integer arguments to
1501 // dbesc_array are actually integers and not malformed strings containing
1502 // SQL injection vectors. All integer array elements should be specifically
1503 // cast to int to avoid trouble.
1504 function dbesc_array_cb(&$item, $key) {
1505 if (is_string($item))
1506 $item = dbesc($item);
1509 function dbesc_array(&$arr) {
1510 if (is_array($arr) && count($arr)) {
1511 array_walk($arr,'dbesc_array_cb');
1515 function dba_timer() {
1516 return microtime(true);