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"];
78 $this->db = @new PDO($connect, $user, $pass);
79 if (!$this->db->errorCode()) {
80 $this->connected = true;
82 } elseif (class_exists('mysqli')) {
83 $this->driver = 'mysqli';
84 $this->db = @new mysqli($server, $user, $pass, $db, $port);
85 if (!mysqli_connect_errno()) {
86 $this->connected = true;
88 if (isset($a->config["system"]["db_charset"])) {
89 $this->db->set_charset($a->config["system"]["db_charset"]);
92 } elseif (function_exists('mysql_connect')) {
93 $this->driver = 'mysql';
94 $this->db = mysql_connect($serveraddr, $user, $pass);
95 if ($this->db && mysql_select_db($db, $this->db)) {
96 $this->connected = true;
98 if (isset($a->config["system"]["db_charset"])) {
99 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
103 // No suitable SQL driver was found.
105 system_unavailable();
109 if (!$this->connected) {
112 system_unavailable();
115 $a->save_timestamp($stamp1, "network");
121 * @brief Returns the MySQL server version string
123 * This function discriminate between the deprecated mysql API and the current
124 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
128 public function server_info() {
129 if ($this->_server_info == '') {
130 switch ($this->driver) {
132 $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
135 $this->_server_info = $this->db->server_info;
138 $this->_server_info = mysql_get_server_info($this->db);
142 return $this->_server_info;
146 * @brief Returns the selected database name
150 public function database_name() {
151 $r = $this->q("SELECT DATABASE() AS `db`");
157 * @brief Analyze a database query and log this if some conditions are met.
159 * @param string $query The database query that will be analyzed
161 public function log_index($query) {
164 if ($a->config["system"]["db_log_index"] == "") {
168 // Don't explain an explain statement
169 if (strtolower(substr($query, 0, 7)) == "explain") {
173 // Only do the explain on "select", "update" and "delete"
174 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
178 $r = $this->q("EXPLAIN ".$query);
179 if (!dbm::is_result($r)) {
183 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
184 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
186 foreach ($r AS $row) {
187 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
188 $log = (in_array($row['key'], $watchlist) &&
189 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
194 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
198 if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
203 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
204 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
205 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
206 basename($backtrace[1]["file"])."\t".
207 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
208 substr($query, 0, 2000)."\n", FILE_APPEND);
213 public function q($sql, $onlyquery = false) {
216 if (!$this->db || !$this->connected) {
222 $connstr = ($this->connected() ? "Connected" : "Disonnected");
224 $stamp1 = microtime(true);
228 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
229 $sql = "/*".$a->callstack()." */ ".$sql;
234 switch ($this->driver) {
236 $result = @$this->db->query($sql);
237 // Is used to separate between queries that returning data - or not
238 if (!is_bool($result)) {
239 $columns = $result->columnCount();
243 $result = @$this->db->query($sql);
246 $result = @mysql_query($sql,$this->db);
249 $stamp2 = microtime(true);
250 $duration = (float)($stamp2 - $stamp1);
252 $a->save_timestamp($stamp1, "database");
254 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
255 $a->save_timestamp($stamp1, "database_write");
257 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
258 if (($duration > $a->config["system"]["db_loglimit"])) {
259 $duration = round($duration, 3);
260 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
261 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
262 basename($backtrace[1]["file"])."\t".
263 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
264 substr($sql, 0, 2000)."\n", FILE_APPEND);
268 switch ($this->driver) {
270 $errorInfo = $this->db->errorInfo();
272 $this->error = $errorInfo[2];
273 $this->errorno = $errorInfo[1];
277 if ($this->db->errno) {
278 $this->error = $this->db->error;
279 $this->errorno = $this->db->errno;
283 if (mysql_errno($this->db)) {
284 $this->error = mysql_error($this->db);
285 $this->errorno = mysql_errno($this->db);
289 if (strlen($this->error)) {
290 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
297 if ($result === false) {
299 } elseif ($result === true) {
302 switch ($this->driver) {
304 $mesg = $result->rowCount().' results'.EOL;
307 $mesg = $result->num_rows.' results'.EOL;
310 $mesg = mysql_num_rows($result).' results'.EOL;
315 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
316 . (($this->error) ? ' error: ' . $this->error : '')
319 logger('dba: ' . $str );
323 * If dbfail.out exists, we will write any failed calls directly to it,
324 * regardless of any logging that may or may nor be in effect.
325 * These usually indicate SQL syntax errors that need to be resolved.
328 if ($result === false) {
329 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
330 if (file_exists('dbfail.out')) {
331 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
335 if (is_bool($result)) {
339 $this->result = $result;
344 switch ($this->driver) {
346 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
349 $result->closeCursor();
352 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
355 $result->free_result();
358 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
361 mysql_free_result($result);
365 // PDO doesn't return "true" on successful operations - like mysqli does
366 // Emulate this behaviour by checking if the query returned data and had columns
367 // This should be reliable enough
368 if (($this->driver == 'pdo') && (count($r) == 0) && ($columns == 0)) {
372 //$a->save_timestamp($stamp1, "database");
375 logger('dba: ' . printable(print_r($r, true)));
380 public function dbg($dbg) {
384 public function escape($str) {
385 if ($this->db && $this->connected) {
386 switch ($this->driver) {
388 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
390 return @$this->db->real_escape_string($str);
392 return @mysql_real_escape_string($str,$this->db);
397 function connected() {
398 switch ($this->driver) {
400 // Not sure if this really is working like expected
401 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
404 $connected = $this->db->ping();
407 $connected = mysql_ping($this->db);
413 function insert_id() {
414 switch ($this->driver) {
416 $id = $this->db->lastInsertId();
419 $id = $this->db->insert_id;
422 $id = mysql_insert_id($this->db);
428 function __destruct() {
430 switch ($this->driver) {
438 mysql_close($this->db);
445 * @brief Replaces ANY_VALUE() function by MIN() function,
446 * if the database server does not support ANY_VALUE().
448 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
449 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
450 * A standard fall-back is to use MIN().
452 * @param string $sql An SQL string without the values
453 * @return string The input SQL string modified if necessary.
455 public function any_value_fallback($sql) {
456 $server_info = $this->server_info();
457 if (version_compare($server_info, '5.7.5', '<') ||
458 (stripos($server_info, 'MariaDB') !== false)) {
459 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
465 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
467 * This is safe when we bind the parameters later.
468 * The parameter values aren't part of the SQL.
470 * @param string $sql An SQL string without the values
471 * @return string The input SQL string modified if necessary.
473 public function clean_query($sql) {
474 $search = array("\t", "\n", "\r", " ");
475 $replace = array(' ', ' ', ' ', ' ');
478 $sql = str_replace($search, $replace, $sql);
479 } while ($oldsql != $sql);
486 * @brief Replaces the ? placeholders with the parameters in the $args array
488 * @param string $sql SQL query
489 * @param array $args The parameters that are to replace the ? placeholders
490 * @return string The replaced SQL query
492 static private function replace_parameters($sql, $args) {
494 foreach ($args AS $param => $value) {
495 if (is_int($args[$param]) || is_float($args[$param])) {
496 $replace = intval($args[$param]);
498 $replace = "'".self::$dbo->escape($args[$param])."'";
501 $pos = strpos($sql, '?', $offset);
502 if ($pos !== false) {
503 $sql = substr_replace($sql, $replace, $pos, 1);
505 $offset = $pos + strlen($replace);
511 * @brief Executes a prepared statement that returns data
512 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
513 * @param string $sql SQL statement
514 * @return object statement object
516 static public function p($sql) {
519 $stamp1 = microtime(true);
521 $args = func_get_args();
524 // When the second function parameter is an array then use this as the parameter array
525 if ((count($args) > 0) && (is_array($args[1]))) {
531 // Renumber the array keys to be sure that they fit
534 foreach ($params AS $param) {
535 $args[++$i] = $param;
538 if (!self::$dbo || !self::$dbo->connected) {
542 if (substr_count($sql, '?') != count($args)) {
543 // Question: Should we continue or stop the query here?
544 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
547 $sql = self::$dbo->clean_query($sql);
548 $sql = self::$dbo->any_value_fallback($sql);
550 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
551 $sql = "/*".$a->callstack()." */ ".$sql;
554 self::$dbo->error = '';
555 self::$dbo->errorno = 0;
556 self::$dbo->affected_rows = 0;
558 switch (self::$dbo->driver) {
560 if (!$stmt = self::$dbo->db->prepare($sql)) {
561 $errorInfo = self::$dbo->db->errorInfo();
562 self::$dbo->error = $errorInfo[2];
563 self::$dbo->errorno = $errorInfo[1];
568 foreach ($args AS $param => $value) {
569 $stmt->bindParam($param, $args[$param]);
572 if (!$stmt->execute()) {
573 $errorInfo = $stmt->errorInfo();
574 self::$dbo->error = $errorInfo[2];
575 self::$dbo->errorno = $errorInfo[1];
579 self::$dbo->affected_rows = $retval->rowCount();
583 $stmt = self::$dbo->db->stmt_init();
585 if (!$stmt->prepare($sql)) {
586 self::$dbo->error = $stmt->error;
587 self::$dbo->errorno = $stmt->errno;
594 foreach ($args AS $param => $value) {
595 if (is_int($args[$param])) {
597 } elseif (is_float($args[$param])) {
599 } elseif (is_string($args[$param])) {
604 $values[] = &$args[$param];
607 if (count($values) > 0) {
608 array_unshift($values, $params);
609 call_user_func_array(array($stmt, 'bind_param'), $values);
612 if (!$stmt->execute()) {
613 self::$dbo->error = self::$dbo->db->error;
614 self::$dbo->errorno = self::$dbo->db->errno;
617 $stmt->store_result();
619 self::$dbo->affected_rows = $retval->affected_rows;
623 // For the old "mysql" functions we cannot use prepared statements
624 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
625 if (mysql_errno(self::$dbo->db)) {
626 self::$dbo->error = mysql_error(self::$dbo->db);
627 self::$dbo->errorno = mysql_errno(self::$dbo->db);
629 self::$dbo->affected_rows = mysql_affected_rows($retval);
631 // Due to missing mysql_* support this here wasn't tested at all
632 // See here: http://php.net/manual/en/function.mysql-num-rows.php
633 if (self::$dbo->affected_rows <= 0) {
634 self::$dbo->affected_rows = mysql_num_rows($retval);
640 if (self::$dbo->errorno != 0) {
641 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
643 if (isset($trace[2])) {
644 $called_from = $trace[2];
646 // We use just something that is defined to avoid warnings
647 $called_from = $trace[0];
649 // We are having an own error logging in the function "e"
650 if ($called_from['function'] != 'e') {
651 // We have to preserve the error code, somewhere in the logging it get lost
652 $error = self::$dbo->error;
653 $errorno = self::$dbo->errorno;
655 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
656 $a->callstack(8)."\n".self::replace_parameters($sql, $params));
658 self::$dbo->error = $error;
659 self::$dbo->errorno = $errorno;
663 $a->save_timestamp($stamp1, 'database');
665 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
667 $stamp2 = microtime(true);
668 $duration = (float)($stamp2 - $stamp1);
670 if (($duration > $a->config["system"]["db_loglimit"])) {
671 $duration = round($duration, 3);
672 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
674 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
675 basename($backtrace[1]["file"])."\t".
676 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
677 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
684 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
686 * @param string $sql SQL statement
687 * @return boolean Was the query successfull? False is returned only if an error occurred
689 static public function e($sql) {
692 $stamp = microtime(true);
694 $args = func_get_args();
696 // In a case of a deadlock we are repeating the query 20 times
700 $stmt = call_user_func_array('self::p', $args);
702 if (is_bool($stmt)) {
704 } elseif (is_object($stmt)) {
712 } while ((self::$dbo->errorno == 1213) && (--$timeout > 0));
714 if (self::$dbo->errorno != 0) {
715 // We have to preserve the error code, somewhere in the logging it get lost
716 $error = self::$dbo->error;
717 $errorno = self::$dbo->errorno;
721 // When the second function parameter is an array then use this as the parameter array
722 if ((count($args) > 0) && (is_array($args[0]))) {
728 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
729 $a->callstack(8)."\n".self::replace_parameters($sql, $params));
731 self::$dbo->error = $error;
732 self::$dbo->errorno = $errorno;
735 $a->save_timestamp($stamp, "database_write");
741 * @brief Check if data exists
743 * @param string $sql SQL statement
744 * @return boolean Are there rows for that query?
746 static public function exists($sql) {
747 $args = func_get_args();
749 $stmt = call_user_func_array('self::p', $args);
751 if (is_bool($stmt)) {
754 $retval = (self::num_rows($stmt) > 0);
763 * @brief Fetches the first row
765 * @param string $sql SQL statement
766 * @return array first row of query
768 static public function fetch_first($sql) {
769 $args = func_get_args();
771 $stmt = call_user_func_array('self::p', $args);
773 if (is_bool($stmt)) {
776 $retval = self::fetch($stmt);
785 * @brief Returns the number of affected rows of the last statement
787 * @return int Number of rows
789 static public function affected_rows() {
790 return self::$dbo->affected_rows;
794 * @brief Returns the number of rows of a statement
796 * @param object Statement object
797 * @return int Number of rows
799 static public function num_rows($stmt) {
800 if (!is_object($stmt)) {
803 switch (self::$dbo->driver) {
805 return $stmt->rowCount();
807 return $stmt->num_rows;
809 return mysql_num_rows($stmt);
815 * @brief Fetch a single row
817 * @param object $stmt statement object
818 * @return array current row
820 static public function fetch($stmt) {
821 if (!is_object($stmt)) {
825 switch (self::$dbo->driver) {
827 return $stmt->fetch(PDO::FETCH_ASSOC);
829 // This code works, but is slow
831 // Bind the result to a result array
835 for ($x = 0; $x < $stmt->field_count; $x++) {
836 $cols[] = &$cols_num[$x];
839 call_user_func_array(array($stmt, 'bind_result'), $cols);
841 if (!$stmt->fetch()) {
846 // We need to get the field names for the array keys
847 // It seems that there is no better way to do this.
848 $result = $stmt->result_metadata();
849 $fields = $result->fetch_fields();
852 foreach ($cols_num AS $param => $col) {
853 $columns[$fields[$param]->name] = $col;
857 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
862 * @brief Insert a row into a table
864 * @param string $table Table name
865 * @param array $param parameter array
867 * @return boolean was the insert successfull?
869 static public function insert($table, $param) {
870 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
871 substr(str_repeat("?, ", count($param)), 0, -2).");";
873 return self::e($sql, $param);
877 * @brief Locks a table for exclusive write access
879 * This function can be extended in the future to accept a table array as well.
881 * @param string $table Table name
883 * @return boolean was the lock successful?
885 static public function lock($table) {
886 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
887 self::e("SET autocommit=0");
888 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
890 self::e("SET autocommit=1");
892 self::$in_transaction = true;
898 * @brief Unlocks all locked tables
900 * @return boolean was the unlock successful?
902 static public function unlock() {
903 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
905 $success = self::e("UNLOCK TABLES");
906 self::e("SET autocommit=1");
907 self::$in_transaction = false;
912 * @brief Starts a transaction
914 * @return boolean Was the command executed successfully?
916 static public function transaction() {
917 if (!self::e('COMMIT')) {
920 if (!self::e('START TRANSACTION')) {
923 self::$in_transaction = true;
928 * @brief Does a commit
930 * @return boolean Was the command executed successfully?
932 static public function commit() {
933 if (!self::e('COMMIT')) {
936 self::$in_transaction = false;
941 * @brief Does a rollback
943 * @return boolean Was the command executed successfully?
945 static public function rollback() {
946 if (!self::e('ROLLBACK')) {
949 self::$in_transaction = false;
954 * @brief Build the array with the table relations
956 * The array is build from the database definitions in dbstructure.php
958 * This process must only be started once, since the value is cached.
960 static private function build_relation_data() {
961 $definition = db_definition();
963 foreach ($definition AS $table => $structure) {
964 foreach ($structure['fields'] AS $field => $field_struct) {
965 if (isset($field_struct['relation'])) {
966 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
967 self::$relation[$rel_table][$rel_field][$table][] = $field;
975 * @brief Delete a row from a table
977 * @param string $table Table name
978 * @param array $param parameter array
979 * @param boolean $in_process Internal use: Only do a commit after the last delete
980 * @param array $callstack Internal use: prevent endless loops
982 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
984 static public function delete($table, $param, $in_process = false, &$callstack = array()) {
988 // Create a key for the loop prevention
989 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
991 // We quit when this key already exists in the callstack.
992 if (isset($callstack[$key])) {
996 $callstack[$key] = true;
998 $table = self::$dbo->escape($table);
1000 $commands[$key] = array('table' => $table, 'param' => $param);
1002 // To speed up the whole process we cache the table relations
1003 if (count(self::$relation) == 0) {
1004 self::build_relation_data();
1007 // Is there a relation entry for the table?
1008 if (isset(self::$relation[$table])) {
1009 // We only allow a simple "one field" relation.
1010 $field = array_keys(self::$relation[$table])[0];
1011 $rel_def = array_values(self::$relation[$table])[0];
1013 // Create a key for preventing double queries
1014 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
1016 // When the search field is the relation field, we don't need to fetch the rows
1017 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1018 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
1019 foreach ($rel_def AS $rel_table => $rel_fields) {
1020 foreach ($rel_fields AS $rel_field) {
1021 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
1022 $commands = array_merge($commands, $retval);
1025 // We quit when this key already exists in the callstack.
1026 } elseif (!isset($callstack[$qkey])) {
1028 $callstack[$qkey] = true;
1030 // Fetch all rows that are to be deleted
1031 $sql = "SELECT ".self::$dbo->escape($field)." FROM `".$table."` WHERE `".
1032 implode("` = ? AND `", array_keys($param))."` = ?";
1034 $data = self::p($sql, $param);
1035 while ($row = self::fetch($data)) {
1036 // Now we accumulate the delete commands
1037 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
1038 $commands = array_merge($commands, $retval);
1041 // Since we had split the delete command we don't need the original command anymore
1042 unset($commands[$key]);
1047 // Now we finalize the process
1048 $do_transaction = !self::$in_transaction;
1050 if ($do_transaction) {
1051 self::transaction();
1054 $compacted = array();
1056 foreach ($commands AS $command) {
1057 if (count($command['param']) > 1) {
1058 $sql = "DELETE FROM `".$command['table']."` WHERE `".
1059 implode("` = ? AND `", array_keys($command['param']))."` = ?";
1061 logger(self::replace_parameters($sql, $command['param']), LOGGER_DATA);
1063 if (!self::e($sql, $command['param'])) {
1064 if ($do_transaction) {
1070 $key_table = $command['table'];
1071 $key_param = array_keys($command['param'])[0];
1072 $value = array_values($command['param'])[0];
1074 // Split the SQL queries in chunks of 100 values
1075 // We do the $i stuff here to make the code better readable
1076 $i = $counter[$key_table][$key_param];
1077 if (count($compacted[$key_table][$key_param][$i]) > 100) {
1081 $compacted[$key_table][$key_param][$i][$value] = $value;
1082 $counter[$key_table][$key_param] = $i;
1085 foreach ($compacted AS $table => $values) {
1086 foreach ($values AS $field => $field_value_list) {
1087 foreach ($field_value_list AS $field_values) {
1088 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1089 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1091 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
1093 if (!self::e($sql, $field_values)) {
1094 if ($do_transaction) {
1102 if ($do_transaction) {
1112 * @brief Updates rows
1114 * Updates rows in the database. When $old_fields is set to an array,
1115 * the system will only do an update if the fields in that array changed.
1118 * Only the values in $old_fields are compared.
1119 * This is an intentional behaviour.
1122 * We include the timestamp field in $fields but not in $old_fields.
1123 * Then the row will only get the new timestamp when the other fields had changed.
1125 * When $old_fields is set to a boolean value the system will do this compare itself.
1126 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1129 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1130 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1132 * @param string $table Table name
1133 * @param array $fields contains the fields that are updated
1134 * @param array $condition condition array with the key values
1135 * @param array|boolean $old_fields array with the old field values that are about to be replaced
1137 * @return boolean was the update successfull?
1139 static public function update($table, $fields, $condition, $old_fields = array()) {
1141 /** @todo We may use MySQL specific functions here:
1142 * INSERT INTO `config` (`cat`, `k`, `v`) VALUES ('%s', '%s', '%s') ON DUPLICATE KEY UPDATE `v` = '%s'"
1143 * But I think that it doesn't make sense here.
1146 $table = self::$dbo->escape($table);
1148 if (is_bool($old_fields)) {
1149 $sql = "SELECT * FROM `".$table."` WHERE `".
1150 implode("` = ? AND `", array_keys($condition))."` = ? LIMIT 1";
1153 foreach ($condition AS $value) {
1157 $do_insert = $old_fields;
1159 $old_fields = self::fetch_first($sql, $params);
1160 if (is_bool($old_fields)) {
1162 return self::insert($table, $fields);
1164 $old_fields = array();
1168 $do_update = (count($old_fields) == 0);
1170 foreach ($old_fields AS $fieldname => $content) {
1171 if (isset($fields[$fieldname])) {
1172 if ($fields[$fieldname] == $content) {
1173 unset($fields[$fieldname]);
1180 if (!$do_update || (count($fields) == 0)) {
1184 $sql = "UPDATE `".$table."` SET `".
1185 implode("` = ?, `", array_keys($fields))."` = ? WHERE `".
1186 implode("` = ? AND `", array_keys($condition))."` = ?";
1189 foreach ($fields AS $value) {
1192 foreach ($condition AS $value) {
1196 return self::e($sql, $params);
1200 * @brief Select rows from a table
1202 * @param string $table Table name
1203 * @param array $fields array of selected fields
1204 * @param array $condition array of fields for condition
1205 * @param array $params array of several parameters
1207 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1211 * $fields = array("id", "uri", "uid", "network");
1212 * $condition = array("uid" => 1, "network" => 'dspr');
1213 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1215 * $data = dba::select($table, $fields, $condition, $params);
1217 static public function select($table, $fields = array(), $condition = array(), $params = array()) {
1222 if (count($fields) > 0) {
1223 $select_fields = "`".implode("`, `", array_values($fields))."`";
1225 $select_fields = "*";
1228 if (count($condition) > 0) {
1229 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1231 $condition_string = "";
1235 $single_row = false;
1237 if (isset($params['order'])) {
1238 $param_string .= " ORDER BY ";
1239 foreach ($params['order'] AS $fields => $order) {
1240 if (!is_int($fields)) {
1241 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1243 $param_string .= "`".$order."`, ";
1246 $param_string = substr($param_string, 0, -2);
1249 if (isset($params['limit'])) {
1250 if (is_int($params['limit'])) {
1251 $param_string .= " LIMIT ".$params['limit'];
1252 $single_row =($params['limit'] == 1);
1256 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1258 $result = self::p($sql, $condition);
1260 if (is_bool($result) || !$single_row) {
1263 $row = self::fetch($result);
1264 self::close($result);
1270 * @brief Closes the current statement
1272 * @param object $stmt statement object
1273 * @return boolean was the close successfull?
1275 static public function close($stmt) {
1276 if (!is_object($stmt)) {
1280 switch (self::$dbo->driver) {
1282 return $stmt->closeCursor();
1284 return $stmt->free_result();
1285 return $stmt->close();
1287 return mysql_free_result($stmt);
1292 function printable($s) {
1293 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
1294 $s = str_replace("\x00",'.',$s);
1295 if (x($_SERVER,'SERVER_NAME')) {
1296 $s = escape_tags($s);
1301 // Procedural functions
1302 function dbg($state) {
1310 function dbesc($str) {
1313 if ($db && $db->connected) {
1314 return($db->escape($str));
1316 return(str_replace("'","\\'",$str));
1320 // Function: q($sql,$args);
1321 // Description: execute SQL query with printf style args.
1322 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
1326 $args = func_get_args();
1329 if ($db && $db->connected) {
1330 $sql = $db->clean_query($sql);
1331 $sql = $db->any_value_fallback($sql);
1332 $stmt = @vsprintf($sql,$args); // Disabled warnings
1333 //logger("dba: q: $stmt", LOGGER_ALL);
1334 if ($stmt === false)
1335 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1337 $db->log_index($stmt);
1339 return $db->q($stmt);
1344 * This will happen occasionally trying to store the
1345 * session data after abnormal program termination
1348 logger('dba: no database: ' . print_r($args,true));
1353 * @brief Performs a query with "dirty reads"
1355 * By doing dirty reads (reading uncommitted data) no locks are performed
1356 * This function can be used to fetch data that doesn't need to be reliable.
1358 * @param $args Query parameters (1 to N parameters of different types)
1359 * @return array Query array
1364 $args = func_get_args();
1367 if ($db && $db->connected) {
1368 $sql = $db->clean_query($sql);
1369 $sql = $db->any_value_fallback($sql);
1370 $stmt = @vsprintf($sql,$args); // Disabled warnings
1371 if ($stmt === false)
1372 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1374 $db->log_index($stmt);
1376 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
1377 $retval = $db->q($stmt);
1378 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
1384 * This will happen occasionally trying to store the
1385 * session data after abnormal program termination
1388 logger('dba: no database: ' . print_r($args,true));
1394 * Raw db query, no arguments
1397 function dbq($sql) {
1400 if ($db && $db->connected) {
1401 $ret = $db->q($sql);
1408 // Caller is responsible for ensuring that any integer arguments to
1409 // dbesc_array are actually integers and not malformed strings containing
1410 // SQL injection vectors. All integer array elements should be specifically
1411 // cast to int to avoid trouble.
1412 function dbesc_array_cb(&$item, $key) {
1413 if (is_string($item))
1414 $item = dbesc($item);
1417 function dbesc_array(&$arr) {
1418 if (is_array($arr) && count($arr)) {
1419 array_walk($arr,'dbesc_array_cb');
1423 function dba_timer() {
1424 return microtime(true);