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;
24 private $_server_info = '';
25 private static $in_transaction = false;
27 private static $relation = array();
29 function __construct($serveraddr, $user, $pass, $db, $install = false) {
32 $stamp1 = microtime(true);
34 $serveraddr = trim($serveraddr);
36 $serverdata = explode(':', $serveraddr);
37 $server = $serverdata[0];
39 if (count($serverdata) > 1) {
40 $port = trim($serverdata[1]);
43 $server = trim($server);
48 if (!(strlen($server) && strlen($user))) {
49 $this->connected = false;
55 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
56 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
57 $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
58 $this->connected = false;
65 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
66 $this->driver = 'pdo';
67 $connect = "mysql:host=".$server.";dbname=".$db;
70 $connect .= ";port=".$port;
73 if (isset($a->config["system"]["db_charset"])) {
74 $connect .= ";charset=".$a->config["system"]["db_charset"];
76 $this->db = @new PDO($connect, $user, $pass);
77 if (!$this->db->errorCode()) {
78 $this->connected = true;
80 } elseif (class_exists('mysqli')) {
81 $this->driver = 'mysqli';
82 $this->db = @new mysqli($server, $user, $pass, $db, $port);
83 if (!mysqli_connect_errno()) {
84 $this->connected = true;
86 if (isset($a->config["system"]["db_charset"])) {
87 $this->db->set_charset($a->config["system"]["db_charset"]);
90 } elseif (function_exists('mysql_connect')) {
91 $this->driver = 'mysql';
92 $this->db = mysql_connect($serveraddr, $user, $pass);
93 if ($this->db && mysql_select_db($db, $this->db)) {
94 $this->connected = true;
96 if (isset($a->config["system"]["db_charset"])) {
97 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
101 // No suitable SQL driver was found.
103 system_unavailable();
107 if (!$this->connected) {
110 system_unavailable();
113 $a->save_timestamp($stamp1, "network");
119 * @brief Returns the MySQL server version string
121 * This function discriminate between the deprecated mysql API and the current
122 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
126 public function server_info() {
127 if ($this->_server_info == '') {
128 switch ($this->driver) {
130 $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
133 $this->_server_info = $this->db->server_info;
136 $this->_server_info = mysql_get_server_info($this->db);
140 return $this->_server_info;
144 * @brief Returns the selected database name
148 public function database_name() {
149 $r = $this->q("SELECT DATABASE() AS `db`");
155 * @brief Analyze a database query and log this if some conditions are met.
157 * @param string $query The database query that will be analyzed
159 public function log_index($query) {
162 if ($a->config["system"]["db_log_index"] == "") {
166 // Don't explain an explain statement
167 if (strtolower(substr($query, 0, 7)) == "explain") {
171 // Only do the explain on "select", "update" and "delete"
172 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
176 $r = $this->q("EXPLAIN ".$query);
177 if (!dbm::is_result($r)) {
181 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
182 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
184 foreach ($r AS $row) {
185 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
186 $log = (in_array($row['key'], $watchlist) AND
187 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
192 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
196 if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
201 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
202 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
203 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
204 basename($backtrace[1]["file"])."\t".
205 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
206 substr($query, 0, 2000)."\n", FILE_APPEND);
211 public function q($sql, $onlyquery = false) {
214 if (!$this->db || !$this->connected) {
220 $connstr = ($this->connected() ? "Connected" : "Disonnected");
222 $stamp1 = microtime(true);
226 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
227 $sql = "/*".$a->callstack()." */ ".$sql;
232 switch ($this->driver) {
234 $result = @$this->db->query($sql);
235 // Is used to separate between queries that returning data - or not
236 if (!is_bool($result)) {
237 $columns = $result->columnCount();
241 $result = @$this->db->query($sql);
244 $result = @mysql_query($sql,$this->db);
247 $stamp2 = microtime(true);
248 $duration = (float)($stamp2 - $stamp1);
250 $a->save_timestamp($stamp1, "database");
252 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
253 $a->save_timestamp($stamp1, "database_write");
255 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
256 if (($duration > $a->config["system"]["db_loglimit"])) {
257 $duration = round($duration, 3);
258 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
259 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
260 basename($backtrace[1]["file"])."\t".
261 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
262 substr($sql, 0, 2000)."\n", FILE_APPEND);
266 switch ($this->driver) {
268 $errorInfo = $this->db->errorInfo();
270 $this->error = $errorInfo[2];
271 $this->errorno = $errorInfo[1];
275 if ($this->db->errno) {
276 $this->error = $this->db->error;
277 $this->errorno = $this->db->errno;
281 if (mysql_errno($this->db)) {
282 $this->error = mysql_error($this->db);
283 $this->errorno = mysql_errno($this->db);
287 if (strlen($this->error)) {
288 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
295 if ($result === false) {
297 } elseif ($result === true) {
300 switch ($this->driver) {
302 $mesg = $result->rowCount().' results'.EOL;
305 $mesg = $result->num_rows.' results'.EOL;
308 $mesg = mysql_num_rows($result).' results'.EOL;
313 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
314 . (($this->error) ? ' error: ' . $this->error : '')
317 logger('dba: ' . $str );
321 * If dbfail.out exists, we will write any failed calls directly to it,
322 * regardless of any logging that may or may nor be in effect.
323 * These usually indicate SQL syntax errors that need to be resolved.
326 if ($result === false) {
327 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
328 if (file_exists('dbfail.out')) {
329 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
333 if (is_bool($result)) {
337 $this->result = $result;
342 switch ($this->driver) {
344 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
347 $result->closeCursor();
350 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
353 $result->free_result();
356 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
359 mysql_free_result($result);
363 // PDO doesn't return "true" on successful operations - like mysqli does
364 // Emulate this behaviour by checking if the query returned data and had columns
365 // This should be reliable enough
366 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
370 //$a->save_timestamp($stamp1, "database");
373 logger('dba: ' . printable(print_r($r, true)));
378 public function dbg($dbg) {
382 public function escape($str) {
383 if ($this->db && $this->connected) {
384 switch ($this->driver) {
386 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
388 return @$this->db->real_escape_string($str);
390 return @mysql_real_escape_string($str,$this->db);
395 function connected() {
396 switch ($this->driver) {
398 // Not sure if this really is working like expected
399 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
402 $connected = $this->db->ping();
405 $connected = mysql_ping($this->db);
411 function insert_id() {
412 switch ($this->driver) {
414 $id = $this->db->lastInsertId();
417 $id = $this->db->insert_id;
420 $id = mysql_insert_id($this->db);
426 function __destruct() {
428 switch ($this->driver) {
436 mysql_close($this->db);
443 * @brief Replaces ANY_VALUE() function by MIN() function,
444 * if the database server does not support ANY_VALUE().
446 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
447 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
448 * A standard fall-back is to use MIN().
450 * @param string $sql An SQL string without the values
451 * @return string The input SQL string modified if necessary.
453 public function any_value_fallback($sql) {
454 $server_info = $this->server_info();
455 if (version_compare($server_info, '5.7.5', '<') ||
456 (stripos($server_info, 'MariaDB') !== false)) {
457 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
463 * @brief beautifies the query - useful for "SHOW PROCESSLIST"
465 * This is safe when we bind the parameters later.
466 * The parameter values aren't part of the SQL.
468 * @param string $sql An SQL string without the values
469 * @return string The input SQL string modified if necessary.
471 public function clean_query($sql) {
472 $search = array("\t", "\n", "\r", " ");
473 $replace = array(' ', ' ', ' ', ' ');
476 $sql = str_replace($search, $replace, $sql);
477 } while ($oldsql != $sql);
484 * @brief Replaces the ? placeholders with the parameters in the $args array
486 * @param string $sql SQL query
487 * @param array $args The parameters that are to replace the ? placeholders
488 * @return string The replaced SQL query
490 static private function replace_parameters($sql, $args) {
492 foreach ($args AS $param => $value) {
493 if (is_int($args[$param]) OR is_float($args[$param])) {
494 $replace = intval($args[$param]);
496 $replace = "'".self::$dbo->escape($args[$param])."'";
499 $pos = strpos($sql, '?', $offset);
500 if ($pos !== false) {
501 $sql = substr_replace($sql, $replace, $pos, 1);
503 $offset = $pos + strlen($replace);
509 * @brief Executes a prepared statement that returns data
510 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
511 * @param string $sql SQL statement
512 * @return object statement object
514 static public function p($sql) {
517 $stamp1 = microtime(true);
519 $args = func_get_args();
522 // When the second function parameter is an array then use this as the parameter array
523 if ((count($args) > 0) AND (is_array($args[1]))) {
529 // Renumber the array keys to be sure that they fit
532 foreach ($params AS $param) {
533 $args[++$i] = $param;
536 if (!self::$dbo OR !self::$dbo->connected) {
540 if (substr_count($sql, '?') != count($args)) {
541 // Question: Should we continue or stop the query here?
542 logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
545 $sql = self::$dbo->clean_query($sql);
546 $sql = self::$dbo->any_value_fallback($sql);
548 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
549 $sql = "/*".$a->callstack()." */ ".$sql;
552 self::$dbo->error = '';
553 self::$dbo->errorno = 0;
555 switch (self::$dbo->driver) {
557 if (!$stmt = self::$dbo->db->prepare($sql)) {
558 $errorInfo = self::$dbo->db->errorInfo();
559 self::$dbo->error = $errorInfo[2];
560 self::$dbo->errorno = $errorInfo[1];
565 foreach ($args AS $param => $value) {
566 $stmt->bindParam($param, $args[$param]);
569 if (!$stmt->execute()) {
570 $errorInfo = $stmt->errorInfo();
571 self::$dbo->error = $errorInfo[2];
572 self::$dbo->errorno = $errorInfo[1];
579 $stmt = self::$dbo->db->stmt_init();
581 if (!$stmt->prepare($sql)) {
582 self::$dbo->error = $stmt->error;
583 self::$dbo->errorno = $stmt->errno;
590 foreach ($args AS $param => $value) {
591 if (is_int($args[$param])) {
593 } elseif (is_float($args[$param])) {
595 } elseif (is_string($args[$param])) {
600 $values[] = &$args[$param];
603 if (count($values) > 0) {
604 array_unshift($values, $params);
605 call_user_func_array(array($stmt, 'bind_param'), $values);
608 if (!$stmt->execute()) {
609 self::$dbo->error = self::$dbo->db->error;
610 self::$dbo->errorno = self::$dbo->db->errno;
613 $stmt->store_result();
618 // For the old "mysql" functions we cannot use prepared statements
619 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
620 if (mysql_errno(self::$dbo->db)) {
621 self::$dbo->error = mysql_error(self::$dbo->db);
622 self::$dbo->errorno = mysql_errno(self::$dbo->db);
627 if (self::$dbo->errorno != 0) {
628 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
629 $a->callstack(8))."\n".self::replace_parameters($sql, $args);
632 $a->save_timestamp($stamp1, 'database');
634 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
636 $stamp2 = microtime(true);
637 $duration = (float)($stamp2 - $stamp1);
639 if (($duration > $a->config["system"]["db_loglimit"])) {
640 $duration = round($duration, 3);
641 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
643 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
644 basename($backtrace[1]["file"])."\t".
645 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
646 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
653 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
655 * @param string $sql SQL statement
656 * @return boolean Was the query successfull? False is returned only if an error occurred
658 static public function e($sql) {
661 $stamp = microtime(true);
663 $args = func_get_args();
665 $stmt = call_user_func_array('self::p', $args);
667 if (is_bool($stmt)) {
669 } elseif (is_object($stmt)) {
677 $a->save_timestamp($stamp, "database_write");
683 * @brief Check if data exists
685 * @param string $sql SQL statement
686 * @return boolean Are there rows for that query?
688 static public function exists($sql) {
689 $args = func_get_args();
691 $stmt = call_user_func_array('self::p', $args);
693 if (is_bool($stmt)) {
696 $retval = (self::num_rows($stmt) > 0);
705 * @brief Fetches the first row
707 * @param string $sql SQL statement
708 * @return array first row of query
710 static public function fetch_first($sql) {
711 $args = func_get_args();
713 $stmt = call_user_func_array('self::p', $args);
715 if (is_bool($stmt)) {
718 $retval = self::fetch($stmt);
727 * @brief Returns the number of rows of a statement
729 * @param object Statement object
730 * @return int Number of rows
732 static public function num_rows($stmt) {
733 if (!is_object($stmt)) {
736 switch (self::$dbo->driver) {
738 return $stmt->rowCount();
740 return $stmt->num_rows;
742 return mysql_num_rows($stmt);
748 * @brief Fetch a single row
750 * @param object $stmt statement object
751 * @return array current row
753 static public function fetch($stmt) {
754 if (!is_object($stmt)) {
758 switch (self::$dbo->driver) {
760 return $stmt->fetch(PDO::FETCH_ASSOC);
762 // This code works, but is slow
764 // Bind the result to a result array
768 for ($x = 0; $x < $stmt->field_count; $x++) {
769 $cols[] = &$cols_num[$x];
772 call_user_func_array(array($stmt, 'bind_result'), $cols);
774 if (!$stmt->fetch()) {
779 // We need to get the field names for the array keys
780 // It seems that there is no better way to do this.
781 $result = $stmt->result_metadata();
782 $fields = $result->fetch_fields();
785 foreach ($cols_num AS $param => $col) {
786 $columns[$fields[$param]->name] = $col;
790 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
795 * @brief Insert a row into a table
797 * @param string $table Table name
798 * @param array $param parameter array
800 * @return boolean was the insert successfull?
802 static public function insert($table, $param) {
803 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
804 substr(str_repeat("?, ", count($param)), 0, -2).");";
806 return self::e($sql, $param);
810 * @brief Locks a table for exclusive write access
812 * This function can be extended in the future to accept a table array as well.
814 * @param string $table Table name
816 * @return boolean was the lock successful?
818 static public function lock($table) {
819 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
820 self::e("SET autocommit=0");
821 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
823 self::e("SET autocommit=1");
825 self::$in_transaction = true;
831 * @brief Unlocks all locked tables
833 * @return boolean was the unlock successful?
835 static public function unlock() {
836 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
838 $success = self::e("UNLOCK TABLES");
839 self::e("SET autocommit=1");
840 self::$in_transaction = false;
845 * @brief Starts a transaction
847 * @return boolean Was the command executed successfully?
849 static public function transaction() {
850 if (!self::e('COMMIT')) {
853 if (!self::e('START TRANSACTION')) {
856 self::$in_transaction = true;
861 * @brief Does a commit
863 * @return boolean Was the command executed successfully?
865 static public function commit() {
866 if (!self::e('COMMIT')) {
869 self::$in_transaction = false;
874 * @brief Does a rollback
876 * @return boolean Was the command executed successfully?
878 static public function rollback() {
879 if (!self::e('ROLLBACK')) {
882 self::$in_transaction = false;
887 * @brief Build the array with the table relations
889 * The array is build from the database definitions in dbstructure.php
891 * This process must only be started once, since the value is cached.
893 static private function build_relation_data() {
894 $definition = db_definition();
896 foreach ($definition AS $table => $structure) {
897 foreach ($structure['fields'] AS $field => $field_struct) {
898 if (isset($field_struct['relation'])) {
899 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
900 self::$relation[$rel_table][$rel_field][$table][] = $field;
908 * @brief Delete a row from a table
910 * @param string $table Table name
911 * @param array $param parameter array
912 * @param boolean $in_process Internal use: Only do a commit after the last delete
913 * @param array $callstack Internal use: prevent endless loops
915 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
917 static public function delete($table, $param, $in_process = false, &$callstack = array()) {
921 // Create a key for the loop prevention
922 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
924 // We quit when this key already exists in the callstack.
925 if (isset($callstack[$key])) {
929 $callstack[$key] = true;
931 $table = self::$dbo->escape($table);
933 $commands[$key] = array('table' => $table, 'param' => $param);
935 // To speed up the whole process we cache the table relations
936 if (count(self::$relation) == 0) {
937 self::build_relation_data();
940 // Is there a relation entry for the table?
941 if (isset(self::$relation[$table])) {
942 // We only allow a simple "one field" relation.
943 $field = array_keys(self::$relation[$table])[0];
944 $rel_def = array_values(self::$relation[$table])[0];
946 // Create a key for preventing double queries
947 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
949 // When the search field is the relation field, we don't need to fetch the rows
950 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
951 if ((count($param) == 1) AND ($field == array_keys($param)[0])) {
952 foreach ($rel_def AS $rel_table => $rel_fields) {
953 foreach ($rel_fields AS $rel_field) {
954 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
955 $commands = array_merge($commands, $retval);
958 // We quit when this key already exists in the callstack.
959 } elseif (!isset($callstack[$qkey])) {
961 $callstack[$qkey] = true;
963 // Fetch all rows that are to be deleted
964 $sql = "SELECT ".self::$dbo->escape($field)." FROM `".$table."` WHERE `".
965 implode("` = ? AND `", array_keys($param))."` = ?";
967 $data = self::p($sql, $param);
968 while ($row = self::fetch($data)) {
969 // Now we accumulate the delete commands
970 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
971 $commands = array_merge($commands, $retval);
974 // Since we had split the delete command we don't need the original command anymore
975 unset($commands[$key]);
980 // Now we finalize the process
981 $do_transaction = !self::$in_transaction;
983 if ($do_transaction) {
987 $compacted = array();
989 foreach ($commands AS $command) {
990 if (count($command['param']) > 1) {
991 $sql = "DELETE FROM `".$command['table']."` WHERE `".
992 implode("` = ? AND `", array_keys($command['param']))."` = ?";
994 logger(dba::replace_parameters($sql, $command['param']), LOGGER_DATA);
996 if (!self::e($sql, $command['param'])) {
997 if ($do_transaction) {
1003 $key_table = $command['table'];
1004 $key_param = array_keys($command['param'])[0];
1005 $value = array_values($command['param'])[0];
1007 // Split the SQL queries in chunks of 100 values
1008 // We do the $i stuff here to make the code better readable
1009 $i = $counter[$key_table][$key_param];
1010 if (count($compacted[$key_table][$key_param][$i]) > 100) {
1014 $compacted[$key_table][$key_param][$i][$value] = $value;
1015 $counter[$key_table][$key_param] = $i;
1018 foreach ($compacted AS $table => $values) {
1019 foreach ($values AS $field => $field_value_list) {
1020 foreach ($field_value_list AS $field_values) {
1021 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1022 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1024 logger(dba::replace_parameters($sql, $field_values), LOGGER_DATA);
1026 if (!self::e($sql, $field_values)) {
1027 if ($do_transaction) {
1035 if ($do_transaction) {
1045 * @brief Updates rows
1047 * Updates rows in the database. When $old_fields is set to an array,
1048 * the system will only do an update if the fields in that array changed.
1051 * Only the values in $old_fields are compared.
1052 * This is an intentional behaviour.
1055 * We include the timestamp field in $fields but not in $old_fields.
1056 * Then the row will only get the new timestamp when the other fields had changed.
1058 * When $old_fields is set to a boolean value the system will do this compare itself.
1059 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1062 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1063 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1065 * @param string $table Table name
1066 * @param array $fields contains the fields that are updated
1067 * @param array $condition condition array with the key values
1068 * @param array|boolean $old_fields array with the old field values that are about to be replaced
1070 * @return boolean was the update successfull?
1072 static public function update($table, $fields, $condition, $old_fields = array()) {
1074 /** @todo We may use MySQL specific functions here:
1075 * INSERT INTO `config` (`cat`, `k`, `v`) VALUES ('%s', '%s', '%s') ON DUPLICATE KEY UPDATE `v` = '%s'"
1076 * But I think that it doesn't make sense here.
1079 $table = self::$dbo->escape($table);
1081 if (is_bool($old_fields)) {
1082 $sql = "SELECT * FROM `".$table."` WHERE `".
1083 implode("` = ? AND `", array_keys($condition))."` = ? LIMIT 1";
1086 foreach ($condition AS $value) {
1090 $do_insert = $old_fields;
1092 $old_fields = self::fetch_first($sql, $params);
1093 if (is_bool($old_fields)) {
1095 return self::insert($table, $fields);
1097 $old_fields = array();
1101 $do_update = (count($old_fields) == 0);
1103 foreach ($old_fields AS $fieldname => $content) {
1104 if (isset($fields[$fieldname])) {
1105 if ($fields[$fieldname] == $content) {
1106 unset($fields[$fieldname]);
1113 if (!$do_update OR (count($fields) == 0)) {
1117 $sql = "UPDATE `".$table."` SET `".
1118 implode("` = ?, `", array_keys($fields))."` = ? WHERE `".
1119 implode("` = ? AND `", array_keys($condition))."` = ?";
1122 foreach ($fields AS $value) {
1125 foreach ($condition AS $value) {
1129 return self::e($sql, $params);
1133 * @brief Select rows from a table
1135 * @param string $table Table name
1136 * @param array $fields array of selected fields
1137 * @param array $condition array of fields for condition
1138 * @param array $params array of several parameters
1140 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1144 * $fields = array("id", "uri", "uid", "network");
1145 * $condition = array("uid" => 1, "network" => 'dspr');
1146 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1148 * $data = dba::select($table, $fields, $condition, $params);
1150 static public function select($table, $fields = array(), $condition = array(), $params = array()) {
1155 if (count($fields) > 0) {
1156 $select_fields = "`".implode("`, `", array_values($fields))."`";
1158 $select_fields = "*";
1161 if (count($condition) > 0) {
1162 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1164 $condition_string = "";
1168 $single_row = false;
1170 if (isset($params['order'])) {
1171 $param_string .= " ORDER BY ";
1172 foreach ($params['order'] AS $fields => $order) {
1173 if (!is_int($fields)) {
1174 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1176 $param_string .= "`".$order."`, ";
1179 $param_string = substr($param_string, 0, -2);
1182 if (isset($params['limit'])) {
1183 if (is_int($params['limit'])) {
1184 $param_string .= " LIMIT ".$params['limit'];
1185 $single_row =($params['limit'] == 1);
1189 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1191 $result = self::p($sql, $condition);
1193 if (is_bool($result) OR !$single_row) {
1196 $row = self::fetch($result);
1197 self::close($result);
1203 * @brief Closes the current statement
1205 * @param object $stmt statement object
1206 * @return boolean was the close successfull?
1208 static public function close($stmt) {
1209 if (!is_object($stmt)) {
1213 switch (self::$dbo->driver) {
1215 return $stmt->closeCursor();
1217 return $stmt->free_result();
1218 return $stmt->close();
1220 return mysql_free_result($stmt);
1225 function printable($s) {
1226 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
1227 $s = str_replace("\x00",'.',$s);
1228 if (x($_SERVER,'SERVER_NAME')) {
1229 $s = escape_tags($s);
1234 // Procedural functions
1235 function dbg($state) {
1243 function dbesc($str) {
1246 if ($db && $db->connected) {
1247 return($db->escape($str));
1249 return(str_replace("'","\\'",$str));
1253 // Function: q($sql,$args);
1254 // Description: execute SQL query with printf style args.
1255 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
1259 $args = func_get_args();
1262 if ($db && $db->connected) {
1263 $sql = $db->clean_query($sql);
1264 $sql = $db->any_value_fallback($sql);
1265 $stmt = @vsprintf($sql,$args); // Disabled warnings
1266 //logger("dba: q: $stmt", LOGGER_ALL);
1267 if ($stmt === false)
1268 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1270 $db->log_index($stmt);
1272 return $db->q($stmt);
1277 * This will happen occasionally trying to store the
1278 * session data after abnormal program termination
1281 logger('dba: no database: ' . print_r($args,true));
1286 * @brief Performs a query with "dirty reads"
1288 * By doing dirty reads (reading uncommitted data) no locks are performed
1289 * This function can be used to fetch data that doesn't need to be reliable.
1291 * @param $args Query parameters (1 to N parameters of different types)
1292 * @return array Query array
1297 $args = func_get_args();
1300 if ($db && $db->connected) {
1301 $sql = $db->clean_query($sql);
1302 $sql = $db->any_value_fallback($sql);
1303 $stmt = @vsprintf($sql,$args); // Disabled warnings
1304 if ($stmt === false)
1305 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1307 $db->log_index($stmt);
1309 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
1310 $retval = $db->q($stmt);
1311 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
1317 * This will happen occasionally trying to store the
1318 * session data after abnormal program termination
1321 logger('dba: no database: ' . print_r($args,true));
1327 * Raw db query, no arguments
1330 function dbq($sql) {
1333 if ($db && $db->connected) {
1334 $ret = $db->q($sql);
1341 // Caller is responsible for ensuring that any integer arguments to
1342 // dbesc_array are actually integers and not malformed strings containing
1343 // SQL injection vectors. All integer array elements should be specifically
1344 // cast to int to avoid trouble.
1345 function dbesc_array_cb(&$item, $key) {
1346 if (is_string($item))
1347 $item = dbesc($item);
1350 function dbesc_array(&$arr) {
1351 if (is_array($arr) && count($arr)) {
1352 array_walk($arr,'dbesc_array_cb');
1356 function dba_timer() {
1357 return microtime(true);