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 = '';
26 private static $relation = array();
28 function __construct($serveraddr, $user, $pass, $db, $install = false) {
31 $stamp1 = microtime(true);
33 $serveraddr = trim($serveraddr);
35 $serverdata = explode(':', $serveraddr);
36 $server = $serverdata[0];
38 if (count($serverdata) > 1) {
39 $port = trim($serverdata[1]);
42 $server = trim($server);
47 if (!(strlen($server) && strlen($user))) {
48 $this->connected = false;
54 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
55 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
56 $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
57 $this->connected = false;
64 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
65 $this->driver = 'pdo';
66 $connect = "mysql:host=".$server.";dbname=".$db;
69 $connect .= ";port=".$port;
72 if (isset($a->config["system"]["db_charset"])) {
73 $connect .= ";charset=".$a->config["system"]["db_charset"];
75 $this->db = @new PDO($connect, $user, $pass);
76 if (!$this->db->errorCode()) {
77 $this->connected = true;
79 } elseif (class_exists('mysqli')) {
80 $this->driver = 'mysqli';
81 $this->db = @new mysqli($server, $user, $pass, $db, $port);
82 if (!mysqli_connect_errno()) {
83 $this->connected = true;
85 if (isset($a->config["system"]["db_charset"])) {
86 $this->db->set_charset($a->config["system"]["db_charset"]);
89 } elseif (function_exists('mysql_connect')) {
90 $this->driver = 'mysql';
91 $this->db = mysql_connect($serveraddr, $user, $pass);
92 if ($this->db && mysql_select_db($db, $this->db)) {
93 $this->connected = true;
95 if (isset($a->config["system"]["db_charset"])) {
96 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
100 // No suitable SQL driver was found.
102 system_unavailable();
106 if (!$this->connected) {
109 system_unavailable();
112 $a->save_timestamp($stamp1, "network");
118 * @brief Returns the MySQL server version string
120 * This function discriminate between the deprecated mysql API and the current
121 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
125 public function server_info() {
126 if ($this->_server_info == '') {
127 switch ($this->driver) {
129 $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
132 $this->_server_info = $this->db->server_info;
135 $this->_server_info = mysql_get_server_info($this->db);
139 return $this->_server_info;
143 * @brief Returns the selected database name
147 public function database_name() {
148 $r = $this->q("SELECT DATABASE() AS `db`");
154 * @brief Analyze a database query and log this if some conditions are met.
156 * @param string $query The database query that will be analyzed
158 public function log_index($query) {
161 if ($a->config["system"]["db_log_index"] == "") {
165 // Don't explain an explain statement
166 if (strtolower(substr($query, 0, 7)) == "explain") {
170 // Only do the explain on "select", "update" and "delete"
171 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
175 $r = $this->q("EXPLAIN ".$query);
176 if (!dbm::is_result($r)) {
180 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
181 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
183 foreach ($r AS $row) {
184 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
185 $log = (in_array($row['key'], $watchlist) AND
186 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
191 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
195 if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
200 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
201 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
202 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
203 basename($backtrace[1]["file"])."\t".
204 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
205 substr($query, 0, 2000)."\n", FILE_APPEND);
210 public function q($sql, $onlyquery = false) {
213 if (!$this->db || !$this->connected) {
219 $connstr = ($this->connected() ? "Connected" : "Disonnected");
221 $stamp1 = microtime(true);
225 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
226 $sql = "/*".$a->callstack()." */ ".$sql;
231 switch ($this->driver) {
233 $result = @$this->db->query($sql);
234 // Is used to separate between queries that returning data - or not
235 if (!is_bool($result)) {
236 $columns = $result->columnCount();
240 $result = @$this->db->query($sql);
243 $result = @mysql_query($sql,$this->db);
246 $stamp2 = microtime(true);
247 $duration = (float)($stamp2 - $stamp1);
249 $a->save_timestamp($stamp1, "database");
251 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
252 $a->save_timestamp($stamp1, "database_write");
254 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
255 if (($duration > $a->config["system"]["db_loglimit"])) {
256 $duration = round($duration, 3);
257 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
258 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
259 basename($backtrace[1]["file"])."\t".
260 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
261 substr($sql, 0, 2000)."\n", FILE_APPEND);
265 switch ($this->driver) {
267 $errorInfo = $this->db->errorInfo();
269 $this->error = $errorInfo[2];
270 $this->errorno = $errorInfo[1];
274 if ($this->db->errno) {
275 $this->error = $this->db->error;
276 $this->errorno = $this->db->errno;
280 if (mysql_errno($this->db)) {
281 $this->error = mysql_error($this->db);
282 $this->errorno = mysql_errno($this->db);
286 if (strlen($this->error)) {
287 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
294 if ($result === false) {
296 } elseif ($result === true) {
299 switch ($this->driver) {
301 $mesg = $result->rowCount().' results'.EOL;
304 $mesg = $result->num_rows.' results'.EOL;
307 $mesg = mysql_num_rows($result).' results'.EOL;
312 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
313 . (($this->error) ? ' error: ' . $this->error : '')
316 logger('dba: ' . $str );
320 * If dbfail.out exists, we will write any failed calls directly to it,
321 * regardless of any logging that may or may nor be in effect.
322 * These usually indicate SQL syntax errors that need to be resolved.
325 if ($result === false) {
326 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
327 if (file_exists('dbfail.out')) {
328 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
332 if (is_bool($result)) {
336 $this->result = $result;
341 switch ($this->driver) {
343 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
346 $result->closeCursor();
349 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
352 $result->free_result();
355 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
358 mysql_free_result($result);
362 // PDO doesn't return "true" on successful operations - like mysqli does
363 // Emulate this behaviour by checking if the query returned data and had columns
364 // This should be reliable enough
365 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
369 //$a->save_timestamp($stamp1, "database");
372 logger('dba: ' . printable(print_r($r, true)));
377 public function dbg($dbg) {
381 public function escape($str) {
382 if ($this->db && $this->connected) {
383 switch ($this->driver) {
385 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
387 return @$this->db->real_escape_string($str);
389 return @mysql_real_escape_string($str,$this->db);
394 function connected() {
395 switch ($this->driver) {
397 // Not sure if this really is working like expected
398 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
401 $connected = $this->db->ping();
404 $connected = mysql_ping($this->db);
410 function insert_id() {
411 switch ($this->driver) {
413 $id = $this->db->lastInsertId();
416 $id = $this->db->insert_id;
419 $id = mysql_insert_id($this->db);
425 function __destruct() {
427 switch ($this->driver) {
435 mysql_close($this->db);
442 * @brief Replaces ANY_VALUE() function by MIN() function,
443 * if the database server does not support ANY_VALUE().
445 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
446 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
447 * A standard fall-back is to use MIN().
449 * @param string $sql An SQL string without the values
450 * @return string The input SQL string modified if necessary.
452 public function any_value_fallback($sql) {
453 $server_info = $this->server_info();
454 if (version_compare($server_info, '5.7.5', '<') ||
455 (stripos($server_info, 'MariaDB') !== false)) {
456 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
462 * @brief Replaces the ? placeholders with the parameters in the $args array
464 * @param string $sql SQL query
465 * @param array $args The parameters that are to replace the ? placeholders
466 * @return string The replaced SQL query
468 static private function replace_parameters($sql, $args) {
470 foreach ($args AS $param => $value) {
471 if (is_int($args[$param]) OR is_float($args[$param])) {
472 $replace = intval($args[$param]);
474 $replace = "'".self::$dbo->escape($args[$param])."'";
477 $pos = strpos($sql, '?', $offset);
478 if ($pos !== false) {
479 $sql = substr_replace($sql, $replace, $pos, 1);
481 $offset = $pos + strlen($replace);
487 * @brief Executes a prepared statement that returns data
488 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
489 * @param string $sql SQL statement
490 * @return object statement object
492 static public function p($sql) {
495 $stamp1 = microtime(true);
497 $args = func_get_args();
500 // When the second function parameter is an array then use this as the parameter array
501 if ((count($args) == 1) AND (is_array($args[1]))) {
504 foreach ($params AS $param) {
505 $args[++$i] = $param;
509 if (!self::$dbo OR !self::$dbo->connected) {
513 $sql = self::$dbo->any_value_fallback($sql);
515 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
516 $sql = "/*".$a->callstack()." */ ".$sql;
519 self::$dbo->error = '';
520 self::$dbo->errorno = 0;
522 switch (self::$dbo->driver) {
524 if (!$stmt = self::$dbo->db->prepare($sql)) {
525 $errorInfo = self::$dbo->db->errorInfo();
526 self::$dbo->error = $errorInfo[2];
527 self::$dbo->errorno = $errorInfo[1];
532 foreach ($args AS $param => $value) {
533 $stmt->bindParam($param, $args[$param]);
536 if (!$stmt->execute()) {
537 $errorInfo = $stmt->errorInfo();
538 self::$dbo->error = $errorInfo[2];
539 self::$dbo->errorno = $errorInfo[1];
546 $stmt = self::$dbo->db->stmt_init();
548 if (!$stmt->prepare($sql)) {
549 self::$dbo->error = $stmt->error;
550 self::$dbo->errorno = $stmt->errno;
557 foreach ($args AS $param => $value) {
558 if (is_int($args[$param])) {
560 } elseif (is_float($args[$param])) {
562 } elseif (is_string($args[$param])) {
567 $values[] = &$args[$param];
570 if (count($values) > 0) {
571 array_unshift($values, $params);
572 call_user_func_array(array($stmt, 'bind_param'), $values);
575 if (!$stmt->execute()) {
576 self::$dbo->error = self::$dbo->db->error;
577 self::$dbo->errorno = self::$dbo->db->errno;
580 $stmt->store_result();
585 // For the old "mysql" functions we cannot use prepared statements
586 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
587 if (mysql_errno(self::$dbo->db)) {
588 self::$dbo->error = mysql_error(self::$dbo->db);
589 self::$dbo->errorno = mysql_errno(self::$dbo->db);
594 if (self::$dbo->errorno != 0) {
595 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".self::replace_parameters($sql, $args));
598 $a->save_timestamp($stamp1, 'database');
600 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
602 $stamp2 = microtime(true);
603 $duration = (float)($stamp2 - $stamp1);
605 if (($duration > $a->config["system"]["db_loglimit"])) {
606 $duration = round($duration, 3);
607 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
609 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
610 basename($backtrace[1]["file"])."\t".
611 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
612 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
619 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
621 * @param string $sql SQL statement
622 * @return boolean Was the query successfull? False is returned only if an error occurred
624 static public function e($sql) {
627 $stamp = microtime(true);
629 $args = func_get_args();
631 $stmt = call_user_func_array('self::p', $args);
633 if (is_bool($stmt)) {
635 } elseif (is_object($stmt)) {
643 $a->save_timestamp($stamp, "database_write");
649 * @brief Check if data exists
651 * @param string $sql SQL statement
652 * @return boolean Are there rows for that query?
654 static public function exists($sql) {
655 $args = func_get_args();
657 $stmt = call_user_func_array('self::p', $args);
659 if (is_bool($stmt)) {
662 $retval = (self::num_rows($stmt) > 0);
671 * @brief Fetches the first row
673 * @param string $sql SQL statement
674 * @return array first row of query
676 static public function fetch_first($sql) {
677 $args = func_get_args();
679 $stmt = call_user_func_array('self::p', $args);
681 if (is_bool($stmt)) {
684 $retval = self::fetch($stmt);
693 * @brief Returns the number of rows of a statement
695 * @param object Statement object
696 * @return int Number of rows
698 static public function num_rows($stmt) {
699 switch (self::$dbo->driver) {
701 return $stmt->rowCount();
703 return $stmt->num_rows;
705 return mysql_num_rows($stmt);
711 * @brief Fetch a single row
713 * @param object $stmt statement object
714 * @return array current row
716 static public function fetch($stmt) {
717 if (!is_object($stmt)) {
721 switch (self::$dbo->driver) {
723 return $stmt->fetch(PDO::FETCH_ASSOC);
725 // This code works, but is slow
727 // Bind the result to a result array
731 for ($x = 0; $x < $stmt->field_count; $x++) {
732 $cols[] = &$cols_num[$x];
735 call_user_func_array(array($stmt, 'bind_result'), $cols);
737 if (!$stmt->fetch()) {
742 // We need to get the field names for the array keys
743 // It seems that there is no better way to do this.
744 $result = $stmt->result_metadata();
745 $fields = $result->fetch_fields();
748 foreach ($cols_num AS $param => $col) {
749 $columns[$fields[$param]->name] = $col;
753 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
758 * @brief Insert a row into a table
760 * @param string $table Table name
761 * @param array $param parameter array
763 * @return boolean was the insert successfull?
765 static public function insert($table, $param) {
766 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
767 substr(str_repeat("?, ", count($param)), 0, -2).");";
769 return self::e($sql, $param);
773 * @brief Build the array with the table relations
775 * The array is build from the database definitions in dbstructure.php
777 * This process must only be started once, since the value is cached.
779 static private function build_relation_data() {
780 $definition = db_definition();
782 foreach ($definition AS $table => $structure) {
783 foreach ($structure['fields'] AS $field => $field_struct) {
784 if (isset($field_struct['relation'])) {
785 foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
786 self::$relation[$rel_table][$rel_field][$table][] = $field;
794 * @brief Insert a row into a table
796 * @param string $table Table name
797 * @param array $param parameter array
798 * @param boolean $in_commit Internal use: Only do a commit after the last delete
799 * @param array $callstack Internal use: prevent endless loops
801 * @return boolean|array was the delete successfull? When $in_commit is set: deletion data
803 static public function delete($table, $param, $in_commit = false, &$callstack = array()) {
807 // Create a key for the loop prevention
808 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
810 // We quit when this key already exists in the callstack.
811 if (isset($callstack[$key])) {
815 $callstack[$key] = true;
817 $table = self::$dbo->escape($table);
819 $commands[$key] = array('table' => $table, 'param' => $param);
821 // To speed up the whole process we cache the table relations
822 if (count(self::$relation) == 0) {
823 self::build_relation_data();
826 // Is there a relation entry for the table?
827 if (isset(self::$relation[$table])) {
828 // We only allow a simple "one field" relation.
829 $field = array_keys(self::$relation[$table])[0];
830 $rel_def = array_values(self::$relation[$table])[0];
832 // Create a key for preventing double queries
833 $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
835 // When the search field is the relation field, we don't need to fetch the rows
836 // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
837 if ((count($param) == 1) AND ($field == array_keys($param)[0])) {
838 foreach ($rel_def AS $rel_table => $rel_fields) {
839 foreach ($rel_fields AS $rel_field) {
840 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
841 $commands = array_merge($commands, $retval);
844 // We quit when this key already exists in the callstack.
845 } elseif (!isset($callstack[$qkey])) {
847 $callstack[$qkey] = true;
849 // Fetch all rows that are to be deleted
850 $sql = "SELECT ".self::$dbo->escape($field)." FROM `".$table."` WHERE `".
851 implode("` = ? AND `", array_keys($param))."` = ?";
853 $data = self::p($sql, $param);
854 while ($row = self::fetch($data)) {
855 // Now we accumulate the delete commands
856 $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
857 $commands = array_merge($commands, $retval);
860 // Since we had split the delete command we don't need the original command anymore
861 unset($commands[$key]);
866 // Now we finalize the process
868 self::p("START TRANSACTION");
870 $compacted = array();
872 foreach ($commands AS $command) {
873 if (count($command['param']) > 1) {
874 $sql = "DELETE FROM `".$command['table']."` WHERE `".
875 implode("` = ? AND `", array_keys($command['param']))."` = ?";
877 logger(dba::replace_parameters($sql, $command['param']), LOGGER_DATA);
879 if (!self::e($sql, $param)) {
884 $key_table = $command['table'];
885 $key_param = array_keys($command['param'])[0];
886 $value = array_values($command['param'])[0];
888 // Split the SQL queries in chunks of 100 values
889 // We do the $i stuff here to make the code better readable
890 $i = $counter[$key_table][$key_param];
891 if (count($compacted[$key_table][$key_param][$i]) > 100) {
895 $compacted[$key_table][$key_param][$i][$value] = $value;
896 $counter[$key_table][$key_param] = $i;
899 foreach ($compacted AS $table => $values) {
900 foreach ($values AS $field => $field_value_list) {
901 foreach ($field_value_list AS $field_values) {
902 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
903 substr(str_repeat("?, ", count($field_values)), 0, -2).");";
905 logger(dba::replace_parameters($sql, $field_values), LOGGER_DATA);
907 if (!self::e($sql, $param)) {
922 * @brief Updates rows
924 * Updates rows in the database. When $old_fields is set to an array,
925 * the system will only do an update if the fields in that array changed.
928 * Only the values in $old_fields are compared.
929 * This is an intentional behaviour.
932 * We include the timestamp field in $fields but not in $old_fields.
933 * Then the row will only get the new timestamp when the other fields had changed.
935 * When $old_fields is set to a boolean value the system will do this compare itself.
936 * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
939 * Only set $old_fields to a boolean value when you are sure that you will update a single row.
940 * When you set $old_fields to "true" then $fields must contain all relevant fields!
942 * @param string $table Table name
943 * @param array $fields contains the fields that are updated
944 * @param array $condition condition array with the key values
945 * @param array|boolean $old_fields array with the old field values that are about to be replaced
947 * @return boolean was the update successfull?
949 static public function update($table, $fields, $condition, $old_fields = array()) {
951 /** @todo We may use MySQL specific functions here:
952 * INSERT INTO `config` (`cat`, `k`, `v`) VALUES ('%s', '%s', '%s') ON DUPLICATE KEY UPDATE `v` = '%s'"
953 * But I think that it doesn't make sense here.
956 $table = self::$dbo->escape($table);
958 if (is_bool($old_fields)) {
959 $sql = "SELECT * FROM `".$table."` WHERE `".
960 implode("` = ? AND `", array_keys($condition))."` = ? LIMIT 1";
963 foreach ($condition AS $value) {
967 $do_insert = $old_fields;
969 $old_fields = self::fetch_first($sql, $params);
970 if (is_bool($old_fields)) {
972 return self::insert($table, $fields);
974 $old_fields = array();
978 $do_update = (count($old_fields) == 0);
980 foreach ($old_fields AS $fieldname => $content) {
981 if (isset($fields[$fieldname])) {
982 if ($fields[$fieldname] == $content) {
983 unset($fields[$fieldname]);
990 if (!$do_update OR (count($fields) == 0)) {
994 $sql = "UPDATE `".$table."` SET `".
995 implode("` = ?, `", array_keys($fields))."` = ? WHERE `".
996 implode("` = ? AND `", array_keys($condition))."` = ?";
999 foreach ($fields AS $value) {
1002 foreach ($condition AS $value) {
1006 return self::e($sql, $params);
1010 * @brief Closes the current statement
1012 * @param object $stmt statement object
1013 * @return boolean was the close successfull?
1015 static public function close($stmt) {
1016 if (!is_object($stmt)) {
1020 switch (self::$dbo->driver) {
1022 return $stmt->closeCursor();
1024 return $stmt->free_result();
1025 return $stmt->close();
1027 return mysql_free_result($stmt);
1032 function printable($s) {
1033 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
1034 $s = str_replace("\x00",'.',$s);
1035 if (x($_SERVER,'SERVER_NAME')) {
1036 $s = escape_tags($s);
1041 // Procedural functions
1042 function dbg($state) {
1050 function dbesc($str) {
1053 if ($db && $db->connected) {
1054 return($db->escape($str));
1056 return(str_replace("'","\\'",$str));
1060 // Function: q($sql,$args);
1061 // Description: execute SQL query with printf style args.
1062 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
1066 $args = func_get_args();
1069 if ($db && $db->connected) {
1070 $sql = $db->any_value_fallback($sql);
1071 $stmt = @vsprintf($sql,$args); // Disabled warnings
1072 //logger("dba: q: $stmt", LOGGER_ALL);
1073 if ($stmt === false)
1074 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1076 $db->log_index($stmt);
1078 return $db->q($stmt);
1083 * This will happen occasionally trying to store the
1084 * session data after abnormal program termination
1087 logger('dba: no database: ' . print_r($args,true));
1092 * @brief Performs a query with "dirty reads"
1094 * By doing dirty reads (reading uncommitted data) no locks are performed
1095 * This function can be used to fetch data that doesn't need to be reliable.
1097 * @param $args Query parameters (1 to N parameters of different types)
1098 * @return array Query array
1103 $args = func_get_args();
1106 if ($db && $db->connected) {
1107 $sql = $db->any_value_fallback($sql);
1108 $stmt = @vsprintf($sql,$args); // Disabled warnings
1109 if ($stmt === false)
1110 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1112 $db->log_index($stmt);
1114 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
1115 $retval = $db->q($stmt);
1116 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
1122 * This will happen occasionally trying to store the
1123 * session data after abnormal program termination
1126 logger('dba: no database: ' . print_r($args,true));
1132 * Raw db query, no arguments
1135 function dbq($sql) {
1138 if ($db && $db->connected) {
1139 $ret = $db->q($sql);
1146 // Caller is responsible for ensuring that any integer arguments to
1147 // dbesc_array are actually integers and not malformed strings containing
1148 // SQL injection vectors. All integer array elements should be specifically
1149 // cast to int to avoid trouble.
1150 function dbesc_array_cb(&$item, $key) {
1151 if (is_string($item))
1152 $item = dbesc($item);
1155 function dbesc_array(&$arr) {
1156 if (is_array($arr) && count($arr)) {
1157 array_walk($arr,'dbesc_array_cb');
1161 function dba_timer() {
1162 return microtime(true);