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 = '';
27 function __construct($server, $user, $pass, $db, $install = false) {
30 $stamp1 = microtime(true);
32 $server = trim($server);
37 if (!(strlen($server) && strlen($user))) {
38 $this->connected = false;
44 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
45 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
46 $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
47 $this->connected = false;
54 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
55 $this->driver = 'pdo';
56 $connect = "mysql:host=".$server.";dbname=".$db;
57 if (isset($a->config["system"]["db_charset"])) {
58 $connect .= ";charset=".$a->config["system"]["db_charset"];
60 $this->db = @new PDO($connect, $user, $pass);
61 if (!$this->db->errorCode()) {
62 $this->connected = true;
64 } elseif (class_exists('mysqli')) {
65 $this->driver = 'mysqli';
66 $this->db = @new mysqli($server,$user,$pass,$db);
67 if (!mysqli_connect_errno()) {
68 $this->connected = true;
70 if (isset($a->config["system"]["db_charset"])) {
71 $this->db->set_charset($a->config["system"]["db_charset"]);
74 } elseif (function_exists('mysql_connect')) {
75 $this->driver = 'mysql';
76 $this->db = mysql_connect($server,$user,$pass);
77 if ($this->db && mysql_select_db($db,$this->db)) {
78 $this->connected = true;
80 if (isset($a->config["system"]["db_charset"])) {
81 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
85 // No suitable SQL driver was found.
91 if (!$this->connected) {
97 $a->save_timestamp($stamp1, "network");
103 * @brief Returns the MySQL server version string
105 * This function discriminate between the deprecated mysql API and the current
106 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
110 public function server_info() {
111 if ($this->_server_info == '') {
112 switch ($this->driver) {
114 $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
117 $this->_server_info = $this->db->server_info;
120 $this->_server_info = mysql_get_server_info($this->db);
124 return $this->_server_info;
128 * @brief Returns the selected database name
132 public function database_name() {
133 $r = $this->q("SELECT DATABASE() AS `db`");
139 * @brief Analyze a database query and log this if some conditions are met.
141 * @param string $query The database query that will be analyzed
143 public function log_index($query) {
146 if ($a->config["system"]["db_log_index"] == "") {
150 // Don't explain an explain statement
151 if (strtolower(substr($query, 0, 7)) == "explain") {
155 // Only do the explain on "select", "update" and "delete"
156 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
160 $r = $this->q("EXPLAIN ".$query);
161 if (!dbm::is_result($r)) {
165 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
166 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
168 foreach ($r AS $row) {
169 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
170 $log = (in_array($row['key'], $watchlist) AND
171 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
176 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
180 if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
185 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
186 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
187 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
188 basename($backtrace[1]["file"])."\t".
189 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
190 substr($query, 0, 2000)."\n", FILE_APPEND);
195 public function q($sql, $onlyquery = false) {
198 if (!$this->db || !$this->connected) {
204 $connstr = ($this->connected() ? "Connected" : "Disonnected");
206 $stamp1 = microtime(true);
210 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
211 $sql = "/*".$a->callstack()." */ ".$sql;
216 switch ($this->driver) {
218 $result = @$this->db->query($sql);
219 // Is used to separate between queries that returning data - or not
220 if (!is_bool($result)) {
221 $columns = $result->columnCount();
225 $result = @$this->db->query($sql);
228 $result = @mysql_query($sql,$this->db);
231 $stamp2 = microtime(true);
232 $duration = (float)($stamp2 - $stamp1);
234 $a->save_timestamp($stamp1, "database");
236 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
237 $a->save_timestamp($stamp1, "database_write");
239 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
240 if (($duration > $a->config["system"]["db_loglimit"])) {
241 $duration = round($duration, 3);
242 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
243 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
244 basename($backtrace[1]["file"])."\t".
245 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
246 substr($sql, 0, 2000)."\n", FILE_APPEND);
250 switch ($this->driver) {
252 $errorInfo = $this->db->errorInfo();
254 $this->error = $errorInfo[2];
255 $this->errorno = $errorInfo[1];
259 if ($this->db->errno) {
260 $this->error = $this->db->error;
261 $this->errorno = $this->db->errno;
265 if (mysql_errno($this->db)) {
266 $this->error = mysql_error($this->db);
267 $this->errorno = mysql_errno($this->db);
271 if (strlen($this->error)) {
272 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
279 if ($result === false) {
281 } elseif ($result === true) {
284 switch ($this->driver) {
286 $mesg = $result->rowCount().' results'.EOL;
289 $mesg = $result->num_rows.' results'.EOL;
292 $mesg = mysql_num_rows($result).' results'.EOL;
297 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
298 . (($this->error) ? ' error: ' . $this->error : '')
301 logger('dba: ' . $str );
305 * If dbfail.out exists, we will write any failed calls directly to it,
306 * regardless of any logging that may or may nor be in effect.
307 * These usually indicate SQL syntax errors that need to be resolved.
310 if ($result === false) {
311 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
312 if (file_exists('dbfail.out')) {
313 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
317 if (is_bool($result)) {
321 $this->result = $result;
326 switch ($this->driver) {
328 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
331 $result->closeCursor();
334 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
337 $result->free_result();
340 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
343 mysql_free_result($result);
347 // PDO doesn't return "true" on successful operations - like mysqli does
348 // Emulate this behaviour by checking if the query returned data and had columns
349 // This should be reliable enough
350 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
354 //$a->save_timestamp($stamp1, "database");
357 logger('dba: ' . printable(print_r($r, true)));
362 public function dbg($dbg) {
366 public function escape($str) {
367 if ($this->db && $this->connected) {
368 switch ($this->driver) {
370 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
372 return @$this->db->real_escape_string($str);
374 return @mysql_real_escape_string($str,$this->db);
379 function connected() {
380 switch ($this->driver) {
382 // Not sure if this really is working like expected
383 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
386 $connected = $this->db->ping();
389 $connected = mysql_ping($this->db);
395 function insert_id() {
396 switch ($this->driver) {
398 $id = $this->db->lastInsertId();
401 $id = $this->db->insert_id;
404 $id = mysql_insert_id($this->db);
410 function __destruct() {
412 switch ($this->driver) {
420 mysql_close($this->db);
427 * @brief Replaces ANY_VALUE() function by MIN() function,
428 * if the database server does not support ANY_VALUE().
430 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
431 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
432 * A standard fall-back is to use MIN().
434 * @param string $sql An SQL string without the values
435 * @return string The input SQL string modified if necessary.
437 public function any_value_fallback($sql) {
438 $server_info = $this->server_info();
439 if (version_compare($server_info, '5.7.5', '<') ||
440 (stripos($server_info, 'MariaDB') !== false)) {
441 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
447 * @brief Replaces the ? placeholders with the parameters in the $args array
449 * @param string $sql SQL query
450 * @param array $args The parameters that are to replace the ? placeholders
451 * @return string The replaced SQL query
453 static private function replace_parameters($sql, $args) {
455 foreach ($args AS $param => $value) {
456 if (is_int($args[$param]) OR is_float($args[$param])) {
457 $replace = intval($args[$param]);
459 $replace = "'".dbesc($args[$param])."'";
462 $pos = strpos($sql, '?', $offset);
463 if ($pos !== false) {
464 $sql = substr_replace($sql, $replace, $pos, 1);
466 $offset = $pos + strlen($replace);
472 * @brief Executes a prepared statement that returns data
473 * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
474 * @param string $sql SQL statement
475 * @return object statement object
477 static public function p($sql) {
480 $stamp1 = microtime(true);
482 $args = func_get_args();
485 if (!self::$dbo OR !self::$dbo->connected) {
489 $sql = self::$dbo->any_value_fallback($sql);
491 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
492 $sql = "/*".$a->callstack()." */ ".$sql;
495 self::$dbo->error = '';
496 self::$dbo->errorno = 0;
498 switch (self::$dbo->driver) {
500 if (!$stmt = self::$dbo->db->prepare($sql)) {
501 $errorInfo = self::$dbo->db->errorInfo();
502 self::$dbo->error = $errorInfo[2];
503 self::$dbo->errorno = $errorInfo[1];
508 foreach ($args AS $param => $value) {
509 $stmt->bindParam($param, $args[$param]);
512 if (!$stmt->execute()) {
513 $errorInfo = self::$dbo->db->errorInfo();
514 self::$dbo->error = $errorInfo[2];
515 self::$dbo->errorno = $errorInfo[1];
522 $stmt = self::$dbo->db->stmt_init();
524 if (!$stmt->prepare($sql)) {
525 self::$dbo->error = self::$dbo->db->error;
526 self::$dbo->errorno = self::$dbo->db->errno;
533 foreach ($args AS $param => $value) {
534 if (is_int($args[$param])) {
536 } elseif (is_float($args[$param])) {
538 } elseif (is_string($args[$param])) {
543 $values[] = &$args[$param];
546 array_unshift($values, $params);
548 call_user_func_array(array($stmt, 'bind_param'), $values);
550 if (!$stmt->execute()) {
551 self::$dbo->error = self::$dbo->db->error;
552 self::$dbo->errorno = self::$dbo->db->errno;
555 $stmt->store_result();
560 // For the old "mysql" functions we cannot use prepared statements
561 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
562 if (mysql_errno(self::$dbo->db)) {
563 self::$dbo->error = mysql_error(self::$dbo->db);
564 self::$dbo->errorno = mysql_errno(self::$dbo->db);
569 if (self::$dbo->errorno != 0) {
570 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error);
573 $a->save_timestamp($stamp1, 'database');
575 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
577 $stamp2 = microtime(true);
578 $duration = (float)($stamp2 - $stamp1);
580 if (($duration > $a->config["system"]["db_loglimit"])) {
581 $duration = round($duration, 3);
582 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
584 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
585 basename($backtrace[1]["file"])."\t".
586 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
587 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
594 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
596 * @param string $sql SQL statement
597 * @return boolean Was the query successfull? False is returned only if an error occurred
599 static public function e($sql) {
602 $stamp = microtime(true);
604 $args = func_get_args();
606 $stmt = call_user_func_array('self::p', $args);
608 if (is_bool($stmt)) {
610 } elseif (is_object($stmt)) {
618 $a->save_timestamp($stamp, "database_write");
624 * @brief Check if data exists
626 * @param string $sql SQL statement
627 * @return boolean Are there rows for that query?
629 static public function exists($sql) {
630 $args = func_get_args();
632 $stmt = call_user_func_array('self::p', $args);
634 if (is_bool($stmt)) {
637 $retval = (self::num_rows($stmt) > 0);
646 * @brief Fetches the first row
648 * @param string $sql SQL statement
649 * @return array first row of query
651 static public function fetch_first($sql) {
652 $args = func_get_args();
654 $stmt = call_user_func_array('self::p', $args);
656 if (is_bool($stmt)) {
659 $retval = self::fetch($stmt);
668 * @brief Returns the number of rows of a statement
670 * @param object Statement object
671 * @return int Number of rows
673 static public function num_rows($stmt) {
674 switch (self::$dbo->driver) {
676 return $stmt->rowCount();
678 return $stmt->num_rows;
680 return mysql_num_rows($stmt);
686 * @brief Fetch a single row
688 * @param object $stmt statement object
689 * @return array current row
691 static public function fetch($stmt) {
692 if (!is_object($stmt)) {
696 switch (self::$dbo->driver) {
698 return $stmt->fetch(PDO::FETCH_ASSOC);
700 // This code works, but is slow
702 // Bind the result to a result array
706 for ($x = 0; $x < $stmt->field_count; $x++) {
707 $cols[] = &$cols_num[$x];
710 call_user_func_array(array($stmt, 'bind_result'), $cols);
712 if (!$stmt->fetch()) {
717 // We need to get the field names for the array keys
718 // It seems that there is no better way to do this.
719 $result = $stmt->result_metadata();
720 $fields = $result->fetch_fields();
723 foreach ($cols_num AS $param => $col) {
724 $columns[$fields[$param]->name] = $col;
728 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
733 * @brief Insert a row into a table
735 * @param string $table Table name
736 * @param array $param parameter array
738 * @return boolean was the insert successfull?
740 static public function insert($table, $param) {
741 $sql = "INSERT INTO `".$table."` (`".implode("`, `", array_keys($param))."`) VALUES (".
742 substr(str_repeat("?, ", count($param)), 0, -2).");";
744 $sql = self::replace_parameters($sql, $param);
746 return self::e($sql);
750 * @brief Closes the current statement
752 * @param object $stmt statement object
753 * @return boolean was the close successfull?
755 static public function close($stmt) {
756 if (!is_object($stmt)) {
760 switch (self::$dbo->driver) {
762 return $stmt->closeCursor();
764 return $stmt->free_result();
765 return $stmt->close();
767 return mysql_free_result($stmt);
772 function printable($s) {
773 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
774 $s = str_replace("\x00",'.',$s);
775 if (x($_SERVER,'SERVER_NAME')) {
776 $s = escape_tags($s);
781 // Procedural functions
782 function dbg($state) {
790 function dbesc($str) {
793 if ($db && $db->connected) {
794 return($db->escape($str));
796 return(str_replace("'","\\'",$str));
800 // Function: q($sql,$args);
801 // Description: execute SQL query with printf style args.
802 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
806 $args = func_get_args();
809 if ($db && $db->connected) {
810 $sql = $db->any_value_fallback($sql);
811 $stmt = @vsprintf($sql,$args); // Disabled warnings
812 //logger("dba: q: $stmt", LOGGER_ALL);
814 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
816 $db->log_index($stmt);
818 return $db->q($stmt);
823 * This will happen occasionally trying to store the
824 * session data after abnormal program termination
827 logger('dba: no database: ' . print_r($args,true));
832 * @brief Performs a query with "dirty reads"
834 * By doing dirty reads (reading uncommitted data) no locks are performed
835 * This function can be used to fetch data that doesn't need to be reliable.
837 * @param $args Query parameters (1 to N parameters of different types)
838 * @return array Query array
843 $args = func_get_args();
846 if ($db && $db->connected) {
847 $sql = $db->any_value_fallback($sql);
848 $stmt = @vsprintf($sql,$args); // Disabled warnings
850 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
852 $db->log_index($stmt);
854 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
855 $retval = $db->q($stmt);
856 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
862 * This will happen occasionally trying to store the
863 * session data after abnormal program termination
866 logger('dba: no database: ' . print_r($args,true));
872 * Raw db query, no arguments
878 if ($db && $db->connected) {
886 // Caller is responsible for ensuring that any integer arguments to
887 // dbesc_array are actually integers and not malformed strings containing
888 // SQL injection vectors. All integer array elements should be specifically
889 // cast to int to avoid trouble.
890 function dbesc_array_cb(&$item, $key) {
891 if (is_string($item))
892 $item = dbesc($item);
895 function dbesc_array(&$arr) {
896 if (is_array($arr) && count($arr)) {
897 array_walk($arr,'dbesc_array_cb');
901 function dba_timer() {
902 return microtime(true);