2 require_once("dbm.php");
3 require_once('include/datetime.php');
6 * @class MySQL database class
8 * For debugging, insert 'dbg(1);' anywhere in the program flow.
9 * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
10 * When logging, all binary info is converted to text and html entities are escaped so that
11 * the debugging stream is safe to view within both terminals and web pages.
13 * This class is for the low level database stuff that does driver specific things.
22 public $connected = false;
23 public $error = false;
25 public $affected_rows = 0;
26 private $_server_info = '';
27 private static $in_transaction = false;
29 private static $relation = array();
31 function __construct($serveraddr, $user, $pass, $db, $install = false) {
34 $stamp1 = microtime(true);
36 $serveraddr = trim($serveraddr);
38 $serverdata = explode(':', $serveraddr);
39 $server = $serverdata[0];
41 if (count($serverdata) > 1) {
42 $port = trim($serverdata[1]);
45 $server = trim($server);
50 if (!(strlen($server) && strlen($user))) {
51 $this->connected = false;
57 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
58 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
59 $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
60 $this->connected = false;
67 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
68 $this->driver = 'pdo';
69 $connect = "mysql:host=".$server.";dbname=".$db;
72 $connect .= ";port=".$port;
75 if (isset($a->config["system"]["db_charset"])) {
76 $connect .= ";charset=".$a->config["system"]["db_charset"];
79 $this->db = @new PDO($connect, $user, $pass);
80 $this->connected = true;
81 } catch (PDOException $e) {
82 $this->connected = false;
84 } elseif (class_exists('mysqli')) {
85 $this->driver = 'mysqli';
86 $this->db = @new mysqli($server, $user, $pass, $db, $port);
87 if (!mysqli_connect_errno()) {
88 $this->connected = true;
90 if (isset($a->config["system"]["db_charset"])) {
91 $this->db->set_charset($a->config["system"]["db_charset"]);
94 } elseif (function_exists('mysql_connect')) {
95 $this->driver = 'mysql';
96 $this->db = mysql_connect($serveraddr, $user, $pass);
97 if ($this->db && mysql_select_db($db, $this->db)) {
98 $this->connected = true;
100 if (isset($a->config["system"]["db_charset"])) {
101 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
105 // No suitable SQL driver was found.
107 system_unavailable();
111 if (!$this->connected) {
114 system_unavailable();
117 $a->save_timestamp($stamp1, "network");
123 * @brief Returns the MySQL server version string
125 * This function discriminate between the deprecated mysql API and the current
126 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
130 public function server_info() {
131 if ($this->_server_info == '') {
132 switch ($this->driver) {
134 $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
137 $this->_server_info = $this->db->server_info;
140 $this->_server_info = mysql_get_server_info($this->db);
144 return $this->_server_info;
148 * @brief Returns the selected database name
152 public function database_name() {
153 $r = $this->q("SELECT DATABASE() AS `db`");
159 * @brief Analyze a database query and log this if some conditions are met.
161 * @param string $query The database query that will be analyzed
163 public function log_index($query) {
166 if (empty($a->config["system"]["db_log_index"])) {
170 // Don't explain an explain statement
171 if (strtolower(substr($query, 0, 7)) == "explain") {
175 // Only do the explain on "select", "update" and "delete"
176 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
180 $r = $this->q("EXPLAIN ".$query);
181 if (!dbm::is_result($r)) {
185 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
186 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
188 foreach ($r AS $row) {
189 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
190 $log = (in_array($row['key'], $watchlist) &&
191 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
196 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
200 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
205 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
206 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
207 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
208 basename($backtrace[1]["file"])."\t".
209 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
210 substr($query, 0, 2000)."\n", FILE_APPEND);
215 public function q($sql, $onlyquery = false) {
218 if (!$this->db || !$this->connected) {
224 $connstr = ($this->connected() ? "Connected" : "Disonnected");
226 $stamp1 = microtime(true);
230 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
231 $sql = "/*".$a->callstack()." */ ".$sql;
236 switch ($this->driver) {
238 $result = @$this->db->query($sql);
239 // Is used to separate between queries that returning data - or not
240 if (!is_bool($result)) {
241 $columns = $result->columnCount();
245 $result = @$this->db->query($sql);
248 $result = @mysql_query($sql,$this->db);
251 $stamp2 = microtime(true);
252 $duration = (float)($stamp2 - $stamp1);
254 $a->save_timestamp($stamp1, "database");
256 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
257 $a->save_timestamp($stamp1, "database_write");
259 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
260 if (($duration > $a->config["system"]["db_loglimit"])) {
261 $duration = round($duration, 3);
262 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
263 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
264 basename($backtrace[1]["file"])."\t".
265 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
266 substr($sql, 0, 2000)."\n", FILE_APPEND);
270 switch ($this->driver) {
272 $errorInfo = $this->db->errorInfo();
274 $this->error = $errorInfo[2];
275 $this->errorno = $errorInfo[1];
279 if ($this->db->errno) {
280 $this->error = $this->db->error;
281 $this->errorno = $this->db->errno;
285 if (mysql_errno($this->db)) {
286 $this->error = mysql_error($this->db);
287 $this->errorno = mysql_errno($this->db);
291 if (strlen($this->error)) {
292 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
299 if ($result === false) {
301 } elseif ($result === true) {
304 switch ($this->driver) {
306 $mesg = $result->rowCount().' results'.EOL;
309 $mesg = $result->num_rows.' results'.EOL;
312 $mesg = mysql_num_rows($result).' results'.EOL;
317 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
318 . (($this->error) ? ' error: ' . $this->error : '')
321 logger('dba: ' . $str );
325 * If dbfail.out exists, we will write any failed calls directly to it,
326 * regardless of any logging that may or may nor be in effect.
327 * These usually indicate SQL syntax errors that need to be resolved.
330 if ($result === false) {
331 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
332 if (file_exists('dbfail.out')) {
333 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
337 if (is_bool($result)) {
341 $this->result = $result;
346 switch ($this->driver) {
348 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
351 $result->closeCursor();
354 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
357 $result->free_result();
360 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
363 mysql_free_result($result);
367 // PDO doesn't return "true" on successful operations - like mysqli does
368 // Emulate this behaviour by checking if the query returned data and had columns
369 // This should be reliable enough
370 if (($this->driver == 'pdo') && (count($r) == 0) && ($columns == 0)) {
374 //$a->save_timestamp($stamp1, "database");
377 logger('dba: ' . printable(print_r($r, true)));
382 public function dbg($dbg) {
386 public function escape($str) {
387 if ($this->db && $this->connected) {
388 switch ($this->driver) {
390 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
392 return @$this->db->real_escape_string($str);
394 return @mysql_real_escape_string($str,$this->db);
399 function connected() {
400 switch ($this->driver) {
402 // Not sure if this really is working like expected
403 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
406 $connected = $this->db->ping();
409 $connected = mysql_ping($this->db);
415 function insert_id() {
416 switch ($this->driver) {
418 $id = $this->db->lastInsertId();
421 $id = $this->db->insert_id;
424 $id = mysql_insert_id($this->db);
430 function __destruct() {
432 switch ($this->driver) {
440 mysql_close($this->db);
447 * @brief Replaces ANY_VALUE() function by MIN() function,
448 * if the database server does not support ANY_VALUE().
450 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
451 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
452 * A standard fall-back is to use MIN().
454 * @param string $sql An SQL string without the values
455 * @return string The input SQL string modified if necessary.
457 public function any_value_fallback($sql) {
458 $server_info = $this->server_info();
459 if (version_compare($server_info, '5.7.5', '<') ||
460 (stripos($server_info, 'MariaDB') !== false)) {
461 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
467 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
469 * This is safe when we bind the parameters later.
470 * The parameter values aren't part of the SQL.
472 * @param string $sql An SQL string without the values
473 * @return string The input SQL string modified if necessary.
475 public function clean_query($sql) {
476 $search = array("\t", "\n", "\r", " ");
477 $replace = array(' ', ' ', ' ', ' ');
480 $sql = str_replace($search, $replace, $sql);
481 } while ($oldsql != $sql);
488 * @brief Replaces the ? placeholders with the parameters in the $args array
490 * @param string $sql SQL query
491 * @param array $args The parameters that are to replace the ? placeholders
492 * @return string The replaced SQL query
494 static private function replace_parameters($sql, $args) {
496 foreach ($args AS $param => $value) {
497 if (is_int($args[$param]) || is_float($args[$param])) {
498 $replace = intval($args[$param]);
500 $replace = "'".self::$dbo->escape($args[$param])."'";
503 $pos = strpos($sql, '?', $offset);
504 if ($pos !== false) {
505 $sql = substr_replace($sql, $replace, $pos, 1);
507 $offset = $pos + strlen($replace);
513 * @brief Executes a prepared statement that returns data
514 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
515 * @param string $sql SQL statement
516 * @return object statement object
518 static public function p($sql) {
521 $stamp1 = microtime(true);
523 $args = func_get_args();
526 // When the second function parameter is an array then use this as the parameter array
527 if ((count($args) > 0) && (is_array($args[1]))) {
533 // Renumber the array keys to be sure that they fit
536 foreach ($params AS $param) {
537 $args[++$i] = $param;
540 if (!self::$dbo || !self::$dbo->connected) {
544 if (substr_count($sql, '?') != count($args)) {
545 // Question: Should we continue or stop the query here?
546 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
549 $sql = self::$dbo->clean_query($sql);
550 $sql = self::$dbo->any_value_fallback($sql);
552 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
553 $sql = "/*".$a->callstack()." */ ".$sql;
556 self::$dbo->error = '';
557 self::$dbo->errorno = 0;
558 self::$dbo->affected_rows = 0;
560 switch (self::$dbo->driver) {
562 if (!$stmt = self::$dbo->db->prepare($sql)) {
563 $errorInfo = self::$dbo->db->errorInfo();
564 self::$dbo->error = $errorInfo[2];
565 self::$dbo->errorno = $errorInfo[1];
570 foreach ($args AS $param => $value) {
571 $stmt->bindParam($param, $args[$param]);
574 if (!$stmt->execute()) {
575 $errorInfo = $stmt->errorInfo();
576 self::$dbo->error = $errorInfo[2];
577 self::$dbo->errorno = $errorInfo[1];
581 self::$dbo->affected_rows = $retval->rowCount();
585 $stmt = self::$dbo->db->stmt_init();
587 if (!$stmt->prepare($sql)) {
588 self::$dbo->error = $stmt->error;
589 self::$dbo->errorno = $stmt->errno;
596 foreach ($args AS $param => $value) {
597 if (is_int($args[$param])) {
599 } elseif (is_float($args[$param])) {
601 } elseif (is_string($args[$param])) {
606 $values[] = &$args[$param];
609 if (count($values) > 0) {
610 array_unshift($values, $params);
611 call_user_func_array(array($stmt, 'bind_param'), $values);
614 if (!$stmt->execute()) {
615 self::$dbo->error = self::$dbo->db->error;
616 self::$dbo->errorno = self::$dbo->db->errno;
619 $stmt->store_result();
621 self::$dbo->affected_rows = $retval->affected_rows;
625 // For the old "mysql" functions we cannot use prepared statements
626 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
627 if (mysql_errno(self::$dbo->db)) {
628 self::$dbo->error = mysql_error(self::$dbo->db);
629 self::$dbo->errorno = mysql_errno(self::$dbo->db);
631 self::$dbo->affected_rows = mysql_affected_rows($retval);
633 // Due to missing mysql_* support this here wasn't tested at all
634 // See here: http://php.net/manual/en/function.mysql-num-rows.php
635 if (self::$dbo->affected_rows <= 0) {
636 self::$dbo->affected_rows = mysql_num_rows($retval);
642 if (self::$dbo->errorno != 0) {
643 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
645 if (isset($trace[2])) {
646 $called_from = $trace[2];
648 // We use just something that is defined to avoid warnings
649 $called_from = $trace[0];
651 // We are having an own error logging in the function "e"
652 if ($called_from['function'] != 'e') {
653 // We have to preserve the error code, somewhere in the logging it get lost
654 $error = self::$dbo->error;
655 $errorno = self::$dbo->errorno;
657 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
658 $a->callstack(8)."\n".self::replace_parameters($sql, $params));
660 self::$dbo->error = $error;
661 self::$dbo->errorno = $errorno;
665 $a->save_timestamp($stamp1, 'database');
667 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
669 $stamp2 = microtime(true);
670 $duration = (float)($stamp2 - $stamp1);
672 if (($duration > $a->config["system"]["db_loglimit"])) {
673 $duration = round($duration, 3);
674 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
676 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
677 basename($backtrace[1]["file"])."\t".
678 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
679 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
686 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
688 * @param string $sql SQL statement
689 * @return boolean Was the query successfull? False is returned only if an error occurred
691 static public function e($sql) {
694 $stamp = microtime(true);
696 $args = func_get_args();
698 // In a case of a deadlock we are repeating the query 20 times
702 $stmt = call_user_func_array('self::p', $args);
704 if (is_bool($stmt)) {
706 } elseif (is_object($stmt)) {
714 } while ((self::$dbo->errorno == 1213) && (--$timeout > 0));
716 if (self::$dbo->errorno != 0) {
717 // We have to preserve the error code, somewhere in the logging it get lost
718 $error = self::$dbo->error;
719 $errorno = self::$dbo->errorno;
723 // When the second function parameter is an array then use this as the parameter array
724 if ((count($args) > 0) && (is_array($args[0]))) {
730 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
731 $a->callstack(8)."\n".self::replace_parameters($sql, $params));
733 self::$dbo->error = $error;
734 self::$dbo->errorno = $errorno;
737 $a->save_timestamp($stamp, "database_write");
743 * @brief Check if data exists
745 * @param string $sql SQL statement
746 * @return boolean Are there rows for that query?
748 static public function exists($sql) {
749 $args = func_get_args();
751 $stmt = call_user_func_array('self::p', $args);
753 if (is_bool($stmt)) {
756 $retval = (self::num_rows($stmt) > 0);
765 * @brief Fetches the first row
767 * @param string $sql SQL statement
768 * @return array first row of query
770 static public function fetch_first($sql) {
771 $args = func_get_args();
773 $stmt = call_user_func_array('self::p', $args);
775 if (is_bool($stmt)) {
778 $retval = self::fetch($stmt);
787 * @brief Returns the number of affected rows of the last statement
789 * @return int Number of rows
791 static public function affected_rows() {
792 return self::$dbo->affected_rows;
796 * @brief Returns the number of rows of a statement
798 * @param object Statement object
799 * @return int Number of rows
801 static public function num_rows($stmt) {
802 if (!is_object($stmt)) {
805 switch (self::$dbo->driver) {
807 return $stmt->rowCount();
809 return $stmt->num_rows;
811 return mysql_num_rows($stmt);
817 * @brief Fetch a single row
819 * @param object $stmt statement object
820 * @return array current row
822 static public function fetch($stmt) {
823 if (!is_object($stmt)) {
827 switch (self::$dbo->driver) {
829 return $stmt->fetch(PDO::FETCH_ASSOC);
831 // This code works, but is slow
833 // Bind the result to a result array
837 for ($x = 0; $x < $stmt->field_count; $x++) {
838 $cols[] = &$cols_num[$x];
841 call_user_func_array(array($stmt, 'bind_result'), $cols);
843 if (!$stmt->fetch()) {
848 // We need to get the field names for the array keys
849 // It seems that there is no better way to do this.
850 $result = $stmt->result_metadata();
851 $fields = $result->fetch_fields();
854 foreach ($cols_num AS $param => $col) {
855 $columns[$fields[$param]->name] = $col;
859 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
864 * @brief Insert a row into a table
866 * @param string $table Table name
867 * @param array $param parameter array
869 * @return boolean was the insert successfull?
871 static public function insert($table, $param) {
872 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
873 substr(str_repeat("?, ", count($param)), 0, -2).");";
875 return self::e($sql, $param);
879 * @brief Locks a table for exclusive write access
881 * This function can be extended in the future to accept a table array as well.
883 * @param string $table Table name
885 * @return boolean was the lock successful?
887 static public function lock($table) {
888 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
889 self::e("SET autocommit=0");
890 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
892 self::e("SET autocommit=1");
894 self::$in_transaction = true;
900 * @brief Unlocks all locked tables
902 * @return boolean was the unlock successful?
904 static public function unlock() {
905 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
907 $success = self::e("UNLOCK TABLES");
908 self::e("SET autocommit=1");
909 self::$in_transaction = false;
914 * @brief Starts a transaction
916 * @return boolean Was the command executed successfully?
918 static public function transaction() {
919 if (!self::e('COMMIT')) {
922 if (!self::e('START TRANSACTION')) {
925 self::$in_transaction = true;
930 * @brief Does a commit
932 * @return boolean Was the command executed successfully?
934 static public function commit() {
935 if (!self::e('COMMIT')) {
938 self::$in_transaction = false;
943 * @brief Does a rollback
945 * @return boolean Was the command executed successfully?
947 static public function rollback() {
948 if (!self::e('ROLLBACK')) {
951 self::$in_transaction = false;
956 * @brief Build the array with the table relations
958 * The array is build from the database definitions in dbstructure.php
960 * This process must only be started once, since the value is cached.
962 static private function build_relation_data() {
963 $definition = db_definition();
965 foreach ($definition AS $table => $structure) {
966 foreach ($structure['fields'] AS $field => $field_struct) {
967 if (isset($field_struct['relation'])) {
968 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
969 self::$relation[$rel_table][$rel_field][$table][] = $field;
977 * @brief Delete a row from a table
979 * @param string $table Table name
980 * @param array $param parameter array
981 * @param boolean $in_process Internal use: Only do a commit after the last delete
982 * @param array $callstack Internal use: prevent endless loops
984 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
986 static public function delete($table, $param, $in_process = false, &$callstack = array()) {
990 // Create a key for the loop prevention
991 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
993 // We quit when this key already exists in the callstack.
994 if (isset($callstack[$key])) {
998 $callstack[$key] = true;
1000 $table = self::$dbo->escape($table);
1002 $commands[$key] = array('table' => $table, 'param' => $param);
1004 // To speed up the whole process we cache the table relations
1005 if (count(self::$relation) == 0) {
1006 self::build_relation_data();
1009 // Is there a relation entry for the table?
1010 if (isset(self::$relation[$table])) {
1011 // We only allow a simple "one field" relation.
1012 $field = array_keys(self::$relation[$table])[0];
1013 $rel_def = array_values(self::$relation[$table])[0];
1015 // Create a key for preventing double queries
1016 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
1018 // When the search field is the relation field, we don't need to fetch the rows
1019 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1020 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
1021 foreach ($rel_def AS $rel_table => $rel_fields) {
1022 foreach ($rel_fields AS $rel_field) {
1023 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
1024 $commands = array_merge($commands, $retval);
1027 // We quit when this key already exists in the callstack.
1028 } elseif (!isset($callstack[$qkey])) {
1030 $callstack[$qkey] = true;
1032 // Fetch all rows that are to be deleted
1033 $sql = "SELECT ".self::$dbo->escape($field)." FROM `".$table."` WHERE `".
1034 implode("` = ? AND `", array_keys($param))."` = ?";
1036 $data = self::p($sql, $param);
1037 while ($row = self::fetch($data)) {
1038 // Now we accumulate the delete commands
1039 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
1040 $commands = array_merge($commands, $retval);
1043 // Since we had split the delete command we don't need the original command anymore
1044 unset($commands[$key]);
1049 // Now we finalize the process
1050 $do_transaction = !self::$in_transaction;
1052 if ($do_transaction) {
1053 self::transaction();
1056 $compacted = array();
1058 foreach ($commands AS $command) {
1059 if (count($command['param']) > 1) {
1060 $sql = "DELETE FROM `".$command['table']."` WHERE `".
1061 implode("` = ? AND `", array_keys($command['param']))."` = ?";
1063 logger(self::replace_parameters($sql, $command['param']), LOGGER_DATA);
1065 if (!self::e($sql, $command['param'])) {
1066 if ($do_transaction) {
1072 $key_table = $command['table'];
1073 $key_param = array_keys($command['param'])[0];
1074 $value = array_values($command['param'])[0];
1076 // Split the SQL queries in chunks of 100 values
1077 // We do the $i stuff here to make the code better readable
1078 $i = $counter[$key_table][$key_param];
1079 if (count($compacted[$key_table][$key_param][$i]) > 100) {
1083 $compacted[$key_table][$key_param][$i][$value] = $value;
1084 $counter[$key_table][$key_param] = $i;
1087 foreach ($compacted AS $table => $values) {
1088 foreach ($values AS $field => $field_value_list) {
1089 foreach ($field_value_list AS $field_values) {
1090 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1091 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1093 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
1095 if (!self::e($sql, $field_values)) {
1096 if ($do_transaction) {
1104 if ($do_transaction) {
1114 * @brief Updates rows
1116 * Updates rows in the database. When $old_fields is set to an array,
1117 * the system will only do an update if the fields in that array changed.
1120 * Only the values in $old_fields are compared.
1121 * This is an intentional behaviour.
1124 * We include the timestamp field in $fields but not in $old_fields.
1125 * Then the row will only get the new timestamp when the other fields had changed.
1127 * When $old_fields is set to a boolean value the system will do this compare itself.
1128 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1131 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1132 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1134 * @param string $table Table name
1135 * @param array $fields contains the fields that are updated
1136 * @param array $condition condition array with the key values
1137 * @param array|boolean $old_fields array with the old field values that are about to be replaced
1139 * @return boolean was the update successfull?
1141 static public function update($table, $fields, $condition, $old_fields = array()) {
1143 /** @todo We may use MySQL specific functions here:
1144 * INSERT INTO `config` (`cat`, `k`, `v`) VALUES ('%s', '%s', '%s') ON DUPLICATE KEY UPDATE `v` = '%s'"
1145 * But I think that it doesn't make sense here.
1148 $table = self::$dbo->escape($table);
1150 if (is_bool($old_fields)) {
1151 $sql = "SELECT * FROM `".$table."` WHERE `".
1152 implode("` = ? AND `", array_keys($condition))."` = ? LIMIT 1";
1155 foreach ($condition AS $value) {
1159 $do_insert = $old_fields;
1161 $old_fields = self::fetch_first($sql, $params);
1162 if (is_bool($old_fields)) {
1164 return self::insert($table, $fields);
1166 $old_fields = array();
1170 $do_update = (count($old_fields) == 0);
1172 foreach ($old_fields AS $fieldname => $content) {
1173 if (isset($fields[$fieldname])) {
1174 if ($fields[$fieldname] == $content) {
1175 unset($fields[$fieldname]);
1182 if (!$do_update || (count($fields) == 0)) {
1186 $sql = "UPDATE `".$table."` SET `".
1187 implode("` = ?, `", array_keys($fields))."` = ? WHERE `".
1188 implode("` = ? AND `", array_keys($condition))."` = ?";
1191 foreach ($fields AS $value) {
1194 foreach ($condition AS $value) {
1198 return self::e($sql, $params);
1202 * @brief Select rows from a table
1204 * @param string $table Table name
1205 * @param array $fields array of selected fields
1206 * @param array $condition array of fields for condition
1207 * @param array $params array of several parameters
1209 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1213 * $fields = array("id", "uri", "uid", "network");
1214 * $condition = array("uid" => 1, "network" => 'dspr');
1215 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1217 * $data = dba::select($table, $fields, $condition, $params);
1219 static public function select($table, $fields = array(), $condition = array(), $params = array()) {
1224 if (count($fields) > 0) {
1225 $select_fields = "`".implode("`, `", array_values($fields))."`";
1227 $select_fields = "*";
1230 if (count($condition) > 0) {
1231 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1233 $condition_string = "";
1237 $single_row = false;
1239 if (isset($params['order'])) {
1240 $param_string .= " ORDER BY ";
1241 foreach ($params['order'] AS $fields => $order) {
1242 if (!is_int($fields)) {
1243 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1245 $param_string .= "`".$order."`, ";
1248 $param_string = substr($param_string, 0, -2);
1251 if (isset($params['limit'])) {
1252 if (is_int($params['limit'])) {
1253 $param_string .= " LIMIT ".$params['limit'];
1254 $single_row =($params['limit'] == 1);
1258 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1260 $result = self::p($sql, $condition);
1262 if (is_bool($result) || !$single_row) {
1265 $row = self::fetch($result);
1266 self::close($result);
1272 * @brief Closes the current statement
1274 * @param object $stmt statement object
1275 * @return boolean was the close successfull?
1277 static public 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));
1322 // Function: q($sql,$args);
1323 // Description: execute SQL query with printf style args.
1324 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
1328 $args = func_get_args();
1331 if ($db && $db->connected) {
1332 $sql = $db->clean_query($sql);
1333 $sql = $db->any_value_fallback($sql);
1334 $stmt = @vsprintf($sql,$args); // Disabled warnings
1335 //logger("dba: q: $stmt", LOGGER_ALL);
1336 if ($stmt === false)
1337 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1339 $db->log_index($stmt);
1341 return $db->q($stmt);
1346 * This will happen occasionally trying to store the
1347 * session data after abnormal program termination
1350 logger('dba: no database: ' . print_r($args,true));
1355 * @brief Performs a query with "dirty reads"
1357 * By doing dirty reads (reading uncommitted data) no locks are performed
1358 * This function can be used to fetch data that doesn't need to be reliable.
1360 * @param $args Query parameters (1 to N parameters of different types)
1361 * @return array Query array
1366 $args = func_get_args();
1369 if ($db && $db->connected) {
1370 $sql = $db->clean_query($sql);
1371 $sql = $db->any_value_fallback($sql);
1372 $stmt = @vsprintf($sql,$args); // Disabled warnings
1373 if ($stmt === false)
1374 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1376 $db->log_index($stmt);
1378 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
1379 $retval = $db->q($stmt);
1380 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
1386 * This will happen occasionally trying to store the
1387 * session data after abnormal program termination
1390 logger('dba: no database: ' . print_r($args,true));
1396 * Raw db query, no arguments
1399 function dbq($sql) {
1402 if ($db && $db->connected) {
1403 $ret = $db->q($sql);
1410 // Caller is responsible for ensuring that any integer arguments to
1411 // dbesc_array are actually integers and not malformed strings containing
1412 // SQL injection vectors. All integer array elements should be specifically
1413 // cast to int to avoid trouble.
1414 function dbesc_array_cb(&$item, $key) {
1415 if (is_string($item))
1416 $item = dbesc($item);
1419 function dbesc_array(&$arr) {
1420 if (is_array($arr) && count($arr)) {
1421 array_walk($arr,'dbesc_array_cb');
1425 function dba_timer() {
1426 return microtime(true);