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);
634 if (self::$dbo->errorno != 0) {
635 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
636 $called_from = array_shift($trace);
638 // We are having an own error logging in the function "p"
639 if ($called_from['function'] != 'p') {
640 // We have to preserve the error code, somewhere in the logging it get lost
641 $error = self::$dbo->error;
642 $errorno = self::$dbo->errorno;
644 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
645 $a->callstack(8))."\n".self::replace_parameters($sql, $args);
647 self::$dbo->error = $error;
648 self::$dbo->errorno = $errorno;
652 $a->save_timestamp($stamp1, 'database');
654 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
656 $stamp2 = microtime(true);
657 $duration = (float)($stamp2 - $stamp1);
659 if (($duration > $a->config["system"]["db_loglimit"])) {
660 $duration = round($duration, 3);
661 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
663 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
664 basename($backtrace[1]["file"])."\t".
665 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
666 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
673 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
675 * @param string $sql SQL statement
676 * @return boolean Was the query successfull? False is returned only if an error occurred
678 static public function e($sql) {
681 $stamp = microtime(true);
683 $args = func_get_args();
685 // In a case of a deadlock we are repeating the query 20 times
689 $stmt = call_user_func_array('self::p', $args);
691 if (is_bool($stmt)) {
693 } elseif (is_object($stmt)) {
701 } while ((self::$dbo->errorno == 1213) && (--$timeout > 0));
703 if (self::$dbo->errorno != 0) {
704 // We have to preserve the error code, somewhere in the logging it get lost
705 $error = self::$dbo->error;
706 $errorno = self::$dbo->errorno;
708 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
709 $a->callstack(8))."\n".self::replace_parameters($sql, $args);
711 self::$dbo->error = $error;
712 self::$dbo->errorno = $errorno;
715 $a->save_timestamp($stamp, "database_write");
721 * @brief Check if data exists
723 * @param string $sql SQL statement
724 * @return boolean Are there rows for that query?
726 static public function exists($sql) {
727 $args = func_get_args();
729 $stmt = call_user_func_array('self::p', $args);
731 if (is_bool($stmt)) {
734 $retval = (self::num_rows($stmt) > 0);
743 * @brief Fetches the first row
745 * @param string $sql SQL statement
746 * @return array first row of query
748 static public function fetch_first($sql) {
749 $args = func_get_args();
751 $stmt = call_user_func_array('self::p', $args);
753 if (is_bool($stmt)) {
756 $retval = self::fetch($stmt);
765 * @brief Returns the number of affected rows of the last statement
767 * @return int Number of rows
769 static public function affected_rows() {
770 return self::$dbo->affected_rows;
774 * @brief Returns the number of rows of a statement
776 * @param object Statement object
777 * @return int Number of rows
779 static public function num_rows($stmt) {
780 if (!is_object($stmt)) {
783 switch (self::$dbo->driver) {
785 return $stmt->rowCount();
787 return $stmt->num_rows;
789 return mysql_num_rows($stmt);
795 * @brief Fetch a single row
797 * @param object $stmt statement object
798 * @return array current row
800 static public function fetch($stmt) {
801 if (!is_object($stmt)) {
805 switch (self::$dbo->driver) {
807 return $stmt->fetch(PDO::FETCH_ASSOC);
809 // This code works, but is slow
811 // Bind the result to a result array
815 for ($x = 0; $x < $stmt->field_count; $x++) {
816 $cols[] = &$cols_num[$x];
819 call_user_func_array(array($stmt, 'bind_result'), $cols);
821 if (!$stmt->fetch()) {
826 // We need to get the field names for the array keys
827 // It seems that there is no better way to do this.
828 $result = $stmt->result_metadata();
829 $fields = $result->fetch_fields();
832 foreach ($cols_num AS $param => $col) {
833 $columns[$fields[$param]->name] = $col;
837 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
842 * @brief Insert a row into a table
844 * @param string $table Table name
845 * @param array $param parameter array
847 * @return boolean was the insert successfull?
849 static public function insert($table, $param) {
850 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
851 substr(str_repeat("?, ", count($param)), 0, -2).");";
853 return self::e($sql, $param);
857 * @brief Locks a table for exclusive write access
859 * This function can be extended in the future to accept a table array as well.
861 * @param string $table Table name
863 * @return boolean was the lock successful?
865 static public function lock($table) {
866 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
867 self::e("SET autocommit=0");
868 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
870 self::e("SET autocommit=1");
872 self::$in_transaction = true;
878 * @brief Unlocks all locked tables
880 * @return boolean was the unlock successful?
882 static public function unlock() {
883 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
885 $success = self::e("UNLOCK TABLES");
886 self::e("SET autocommit=1");
887 self::$in_transaction = false;
892 * @brief Starts a transaction
894 * @return boolean Was the command executed successfully?
896 static public function transaction() {
897 if (!self::e('COMMIT')) {
900 if (!self::e('START TRANSACTION')) {
903 self::$in_transaction = true;
908 * @brief Does a commit
910 * @return boolean Was the command executed successfully?
912 static public function commit() {
913 if (!self::e('COMMIT')) {
916 self::$in_transaction = false;
921 * @brief Does a rollback
923 * @return boolean Was the command executed successfully?
925 static public function rollback() {
926 if (!self::e('ROLLBACK')) {
929 self::$in_transaction = false;
934 * @brief Build the array with the table relations
936 * The array is build from the database definitions in dbstructure.php
938 * This process must only be started once, since the value is cached.
940 static private function build_relation_data() {
941 $definition = db_definition();
943 foreach ($definition AS $table => $structure) {
944 foreach ($structure['fields'] AS $field => $field_struct) {
945 if (isset($field_struct['relation'])) {
946 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
947 self::$relation[$rel_table][$rel_field][$table][] = $field;
955 * @brief Delete a row from a table
957 * @param string $table Table name
958 * @param array $param parameter array
959 * @param boolean $in_process Internal use: Only do a commit after the last delete
960 * @param array $callstack Internal use: prevent endless loops
962 * @return boolean|array was the delete successfull? When $in_process is set: deletion data
964 static public function delete($table, $param, $in_process = false, &$callstack = array()) {
968 // Create a key for the loop prevention
969 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
971 // We quit when this key already exists in the callstack.
972 if (isset($callstack[$key])) {
976 $callstack[$key] = true;
978 $table = self::$dbo->escape($table);
980 $commands[$key] = array('table' => $table, 'param' => $param);
982 // To speed up the whole process we cache the table relations
983 if (count(self::$relation) == 0) {
984 self::build_relation_data();
987 // Is there a relation entry for the table?
988 if (isset(self::$relation[$table])) {
989 // We only allow a simple "one field" relation.
990 $field = array_keys(self::$relation[$table])[0];
991 $rel_def = array_values(self::$relation[$table])[0];
993 // Create a key for preventing double queries
994 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
996 // When the search field is the relation field, we don't need to fetch the rows
997 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
998 if ((count($param) == 1) && ($field == array_keys($param)[0])) {
999 foreach ($rel_def AS $rel_table => $rel_fields) {
1000 foreach ($rel_fields AS $rel_field) {
1001 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
1002 $commands = array_merge($commands, $retval);
1005 // We quit when this key already exists in the callstack.
1006 } elseif (!isset($callstack[$qkey])) {
1008 $callstack[$qkey] = true;
1010 // Fetch all rows that are to be deleted
1011 $sql = "SELECT ".self::$dbo->escape($field)." FROM `".$table."` WHERE `".
1012 implode("` = ? AND `", array_keys($param))."` = ?";
1014 $data = self::p($sql, $param);
1015 while ($row = self::fetch($data)) {
1016 // Now we accumulate the delete commands
1017 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
1018 $commands = array_merge($commands, $retval);
1021 // Since we had split the delete command we don't need the original command anymore
1022 unset($commands[$key]);
1027 // Now we finalize the process
1028 $do_transaction = !self::$in_transaction;
1030 if ($do_transaction) {
1031 self::transaction();
1034 $compacted = array();
1036 foreach ($commands AS $command) {
1037 if (count($command['param']) > 1) {
1038 $sql = "DELETE FROM `".$command['table']."` WHERE `".
1039 implode("` = ? AND `", array_keys($command['param']))."` = ?";
1041 logger(dba::replace_parameters($sql, $command['param']), LOGGER_DATA);
1043 if (!self::e($sql, $command['param'])) {
1044 if ($do_transaction) {
1050 $key_table = $command['table'];
1051 $key_param = array_keys($command['param'])[0];
1052 $value = array_values($command['param'])[0];
1054 // Split the SQL queries in chunks of 100 values
1055 // We do the $i stuff here to make the code better readable
1056 $i = $counter[$key_table][$key_param];
1057 if (count($compacted[$key_table][$key_param][$i]) > 100) {
1061 $compacted[$key_table][$key_param][$i][$value] = $value;
1062 $counter[$key_table][$key_param] = $i;
1065 foreach ($compacted AS $table => $values) {
1066 foreach ($values AS $field => $field_value_list) {
1067 foreach ($field_value_list AS $field_values) {
1068 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1069 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1071 logger(dba::replace_parameters($sql, $field_values), LOGGER_DATA);
1073 if (!self::e($sql, $field_values)) {
1074 if ($do_transaction) {
1082 if ($do_transaction) {
1092 * @brief Updates rows
1094 * Updates rows in the database. When $old_fields is set to an array,
1095 * the system will only do an update if the fields in that array changed.
1098 * Only the values in $old_fields are compared.
1099 * This is an intentional behaviour.
1102 * We include the timestamp field in $fields but not in $old_fields.
1103 * Then the row will only get the new timestamp when the other fields had changed.
1105 * When $old_fields is set to a boolean value the system will do this compare itself.
1106 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1109 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1110 * When you set $old_fields to "true" then $fields must contain all relevant fields!
1112 * @param string $table Table name
1113 * @param array $fields contains the fields that are updated
1114 * @param array $condition condition array with the key values
1115 * @param array|boolean $old_fields array with the old field values that are about to be replaced
1117 * @return boolean was the update successfull?
1119 static public function update($table, $fields, $condition, $old_fields = array()) {
1121 /** @todo We may use MySQL specific functions here:
1122 * INSERT INTO `config` (`cat`, `k`, `v`) VALUES ('%s', '%s', '%s') ON DUPLICATE KEY UPDATE `v` = '%s'"
1123 * But I think that it doesn't make sense here.
1126 $table = self::$dbo->escape($table);
1128 if (is_bool($old_fields)) {
1129 $sql = "SELECT * FROM `".$table."` WHERE `".
1130 implode("` = ? AND `", array_keys($condition))."` = ? LIMIT 1";
1133 foreach ($condition AS $value) {
1137 $do_insert = $old_fields;
1139 $old_fields = self::fetch_first($sql, $params);
1140 if (is_bool($old_fields)) {
1142 return self::insert($table, $fields);
1144 $old_fields = array();
1148 $do_update = (count($old_fields) == 0);
1150 foreach ($old_fields AS $fieldname => $content) {
1151 if (isset($fields[$fieldname])) {
1152 if ($fields[$fieldname] == $content) {
1153 unset($fields[$fieldname]);
1160 if (!$do_update || (count($fields) == 0)) {
1164 $sql = "UPDATE `".$table."` SET `".
1165 implode("` = ?, `", array_keys($fields))."` = ? WHERE `".
1166 implode("` = ? AND `", array_keys($condition))."` = ?";
1169 foreach ($fields AS $value) {
1172 foreach ($condition AS $value) {
1176 return self::e($sql, $params);
1180 * @brief Select rows from a table
1182 * @param string $table Table name
1183 * @param array $fields array of selected fields
1184 * @param array $condition array of fields for condition
1185 * @param array $params array of several parameters
1187 * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1191 * $fields = array("id", "uri", "uid", "network");
1192 * $condition = array("uid" => 1, "network" => 'dspr');
1193 * $params = array("order" => array("id", "received" => true), "limit" => 1);
1195 * $data = dba::select($table, $fields, $condition, $params);
1197 static public function select($table, $fields = array(), $condition = array(), $params = array()) {
1202 if (count($fields) > 0) {
1203 $select_fields = "`".implode("`, `", array_values($fields))."`";
1205 $select_fields = "*";
1208 if (count($condition) > 0) {
1209 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1211 $condition_string = "";
1215 $single_row = false;
1217 if (isset($params['order'])) {
1218 $param_string .= " ORDER BY ";
1219 foreach ($params['order'] AS $fields => $order) {
1220 if (!is_int($fields)) {
1221 $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1223 $param_string .= "`".$order."`, ";
1226 $param_string = substr($param_string, 0, -2);
1229 if (isset($params['limit'])) {
1230 if (is_int($params['limit'])) {
1231 $param_string .= " LIMIT ".$params['limit'];
1232 $single_row =($params['limit'] == 1);
1236 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1238 $result = self::p($sql, $condition);
1240 if (is_bool($result) || !$single_row) {
1243 $row = self::fetch($result);
1244 self::close($result);
1250 * @brief Closes the current statement
1252 * @param object $stmt statement object
1253 * @return boolean was the close successfull?
1255 static public function close($stmt) {
1256 if (!is_object($stmt)) {
1260 switch (self::$dbo->driver) {
1262 return $stmt->closeCursor();
1264 return $stmt->free_result();
1265 return $stmt->close();
1267 return mysql_free_result($stmt);
1272 function printable($s) {
1273 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
1274 $s = str_replace("\x00",'.',$s);
1275 if (x($_SERVER,'SERVER_NAME')) {
1276 $s = escape_tags($s);
1281 // Procedural functions
1282 function dbg($state) {
1290 function dbesc($str) {
1293 if ($db && $db->connected) {
1294 return($db->escape($str));
1296 return(str_replace("'","\\'",$str));
1300 // Function: q($sql,$args);
1301 // Description: execute SQL query with printf style args.
1302 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
1306 $args = func_get_args();
1309 if ($db && $db->connected) {
1310 $sql = $db->clean_query($sql);
1311 $sql = $db->any_value_fallback($sql);
1312 $stmt = @vsprintf($sql,$args); // Disabled warnings
1313 //logger("dba: q: $stmt", LOGGER_ALL);
1314 if ($stmt === false)
1315 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1317 $db->log_index($stmt);
1319 return $db->q($stmt);
1324 * This will happen occasionally trying to store the
1325 * session data after abnormal program termination
1328 logger('dba: no database: ' . print_r($args,true));
1333 * @brief Performs a query with "dirty reads"
1335 * By doing dirty reads (reading uncommitted data) no locks are performed
1336 * This function can be used to fetch data that doesn't need to be reliable.
1338 * @param $args Query parameters (1 to N parameters of different types)
1339 * @return array Query array
1344 $args = func_get_args();
1347 if ($db && $db->connected) {
1348 $sql = $db->clean_query($sql);
1349 $sql = $db->any_value_fallback($sql);
1350 $stmt = @vsprintf($sql,$args); // Disabled warnings
1351 if ($stmt === false)
1352 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1354 $db->log_index($stmt);
1356 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
1357 $retval = $db->q($stmt);
1358 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
1364 * This will happen occasionally trying to store the
1365 * session data after abnormal program termination
1368 logger('dba: no database: ' . print_r($args,true));
1374 * Raw db query, no arguments
1377 function dbq($sql) {
1380 if ($db && $db->connected) {
1381 $ret = $db->q($sql);
1388 // Caller is responsible for ensuring that any integer arguments to
1389 // dbesc_array are actually integers and not malformed strings containing
1390 // SQL injection vectors. All integer array elements should be specifically
1391 // cast to int to avoid trouble.
1392 function dbesc_array_cb(&$item, $key) {
1393 if (is_string($item))
1394 $item = dbesc($item);
1397 function dbesc_array(&$arr) {
1398 if (is_array($arr) && count($arr)) {
1399 array_walk($arr,'dbesc_array_cb');
1403 function dba_timer() {
1404 return microtime(true);