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.
21 public $connected = false;
22 public $error = false;
23 private $_server_info = '';
26 function __construct($server, $user, $pass, $db, $install = false) {
29 $stamp1 = microtime(true);
31 $server = trim($server);
36 if (!(strlen($server) && strlen($user))) {
37 $this->connected = false;
43 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
44 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
45 $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
46 $this->connected = false;
53 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
54 $this->driver = 'pdo';
55 $connect = "mysql:host=".$server.";dbname=".$db;
56 if (isset($a->config["system"]["db_charset"])) {
57 $connect .= ";charset=".$a->config["system"]["db_charset"];
59 $this->db = @new PDO($connect, $user, $pass);
60 if (!$this->db->errorCode()) {
61 $this->connected = true;
63 } elseif (class_exists('mysqli')) {
64 $this->driver = 'mysqli';
65 $this->db = @new mysqli($server,$user,$pass,$db);
66 if (!mysqli_connect_errno()) {
67 $this->connected = true;
69 if (isset($a->config["system"]["db_charset"])) {
70 $this->db->set_charset($a->config["system"]["db_charset"]);
73 } elseif (function_exists('mysql_connect')) {
74 $this->driver = 'mysql';
75 $this->db = mysql_connect($server,$user,$pass);
76 if ($this->db && mysql_select_db($db,$this->db)) {
77 $this->connected = true;
79 if (isset($a->config["system"]["db_charset"])) {
80 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
84 // No suitable SQL driver was found.
90 if (!$this->connected) {
96 $a->save_timestamp($stamp1, "network");
102 * @brief Returns the MySQL server version string
104 * This function discriminate between the deprecated mysql API and the current
105 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
109 public function server_info() {
110 if ($this->_server_info == '') {
111 switch ($this->driver) {
113 $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
116 $this->_server_info = $this->db->server_info;
119 $this->_server_info = mysql_get_server_info($this->db);
123 return $this->_server_info;
127 * @brief Returns the selected database name
131 public function database_name() {
132 $r = $this->q("SELECT DATABASE() AS `db`");
138 * @brief Analyze a database query and log this if some conditions are met.
140 * @param string $query The database query that will be analyzed
142 public function log_index($query) {
145 if ($a->config["system"]["db_log_index"] == "") {
149 // Don't explain an explain statement
150 if (strtolower(substr($query, 0, 7)) == "explain") {
154 // Only do the explain on "select", "update" and "delete"
155 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
159 $r = $this->q("EXPLAIN ".$query);
160 if (!dbm::is_result($r)) {
164 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
165 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
167 foreach ($r AS $row) {
168 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
169 $log = (in_array($row['key'], $watchlist) AND
170 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
175 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
179 if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
184 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
185 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
186 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
187 basename($backtrace[1]["file"])."\t".
188 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
189 substr($query, 0, 2000)."\n", FILE_APPEND);
194 public function q($sql, $onlyquery = false) {
197 if (!$this->db || !$this->connected) {
203 $connstr = ($this->connected() ? "Connected" : "Disonnected");
205 $stamp1 = microtime(true);
209 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
210 $sql = "/*".$a->callstack()." */ ".$sql;
215 switch ($this->driver) {
217 $result = @$this->db->query($sql);
218 // Is used to separate between queries that returning data - or not
219 if (!is_bool($result)) {
220 $columns = $result->columnCount();
224 $result = @$this->db->query($sql);
227 $result = @mysql_query($sql,$this->db);
230 $stamp2 = microtime(true);
231 $duration = (float)($stamp2 - $stamp1);
233 $a->save_timestamp($stamp1, "database");
235 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
236 $a->save_timestamp($stamp1, "database_write");
238 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
239 if (($duration > $a->config["system"]["db_loglimit"])) {
240 $duration = round($duration, 3);
241 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
242 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
243 basename($backtrace[1]["file"])."\t".
244 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
245 substr($sql, 0, 2000)."\n", FILE_APPEND);
249 switch ($this->driver) {
251 $errorInfo = $this->db->errorInfo();
253 $this->error = $errorInfo[2];
254 $this->errorno = $errorInfo[1];
258 if ($this->db->errno) {
259 $this->error = $this->db->error;
260 $this->errorno = $this->db->errno;
264 if (mysql_errno($this->db)) {
265 $this->error = mysql_error($this->db);
266 $this->errorno = mysql_errno($this->db);
270 if (strlen($this->error)) {
271 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
278 if ($result === false) {
280 } elseif ($result === true) {
283 switch ($this->driver) {
285 $mesg = $result->rowCount().' results'.EOL;
288 $mesg = $result->num_rows.' results'.EOL;
291 $mesg = mysql_num_rows($result).' results'.EOL;
296 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
297 . (($this->error) ? ' error: ' . $this->error : '')
300 logger('dba: ' . $str );
304 * If dbfail.out exists, we will write any failed calls directly to it,
305 * regardless of any logging that may or may nor be in effect.
306 * These usually indicate SQL syntax errors that need to be resolved.
309 if ($result === false) {
310 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
311 if (file_exists('dbfail.out')) {
312 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
316 if (is_bool($result)) {
320 $this->result = $result;
325 switch ($this->driver) {
327 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
330 $result->closeCursor();
333 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
336 $result->free_result();
339 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
342 mysql_free_result($result);
346 // PDO doesn't return "true" on successful operations - like mysqli does
347 // Emulate this behaviour by checking if the query returned data and had columns
348 // This should be reliable enough
349 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
353 //$a->save_timestamp($stamp1, "database");
356 logger('dba: ' . printable(print_r($r, true)));
361 public function dbg($dbg) {
365 public function escape($str) {
366 if ($this->db && $this->connected) {
367 switch ($this->driver) {
369 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
371 return @$this->db->real_escape_string($str);
373 return @mysql_real_escape_string($str,$this->db);
378 function connected() {
379 switch ($this->driver) {
381 // Not sure if this really is working like expected
382 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
385 $connected = $this->db->ping();
388 $connected = mysql_ping($this->db);
394 function insert_id() {
395 switch ($this->driver) {
397 $id = $this->db->lastInsertId();
400 $id = $this->db->insert_id;
403 $id = mysql_insert_id($this->db);
409 function __destruct() {
411 switch ($this->driver) {
419 mysql_close($this->db);
426 * @brief Replaces ANY_VALUE() function by MIN() function,
427 * if the database server does not support ANY_VALUE().
429 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
430 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
431 * A standard fall-back is to use MIN().
433 * @param string $sql An SQL string without the values
434 * @return string The input SQL string modified if necessary.
436 public function any_value_fallback($sql) {
437 $server_info = $this->server_info();
438 if (version_compare($server_info, '5.7.5', '<') ||
439 (stripos($server_info, 'MariaDB') !== false)) {
440 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
446 * @brief Executes a prepared statement
448 * @param string $sql SQL statement
449 * @return object statement object
451 static public function p($sql) {
454 $stamp1 = microtime(true);
456 $args = func_get_args();
459 if (!self::$dbo OR !self::$dbo->connected) {
463 $sql = self::$dbo->any_value_fallback($sql);
465 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
466 $sql = "/*".$a->callstack()." */ ".$sql;
469 switch (self::$dbo->driver) {
471 if (!$stmt = self::$dbo->db->prepare($sql)) {
472 $errorInfo = self::$dbo->db->errorInfo();
473 self::$dbo->error = $errorInfo[2];
474 self::$dbo->errorno = $errorInfo[1];
479 foreach ($args AS $param => $value) {
480 $stmt->bindParam($param, $args[$param]);
483 if (!$stmt->execute()) {
484 $errorInfo = self::$dbo->db->errorInfo();
485 self::$dbo->error = $errorInfo[2];
486 self::$dbo->errorno = $errorInfo[1];
493 $stmt = self::$dbo->db->stmt_init();
495 if (!$stmt->prepare($sql)) {
496 self::$dbo->error = self::$dbo->db->error;
497 self::$dbo->errorno = self::$dbo->db->errno;
504 foreach ($args AS $param => $value) {
505 if (is_int($args[$param])) {
507 } elseif (is_float($args[$param])) {
509 } elseif (is_string($args[$param])) {
514 $values[] = &$args[$param];
517 array_unshift($values, $params);
519 call_user_func_array(array($stmt, 'bind_param'), $values);
521 if (!$stmt->execute()) {
522 self::$dbo->error = self::$dbo->db->error;
523 self::$dbo->errorno = self::$dbo->db->errno;
526 $stmt->store_result();
531 // For the old "mysql" functions we cannot use prepared statements
532 foreach ($args AS $param => $value) {
533 if (is_int($args[$param]) OR is_float($args[$param])) {
534 $replace = intval($args[$param]);
536 $replace = "'".dbesc($args[$param])."'";
539 $pos = strpos($sql, '?');
540 if ($pos !== false) {
541 $sql = substr_replace($sql, $replace, $pos, 1);
545 $retval = mysql_query($sql, self::$dbo->db);
546 if (mysql_errno(self::$dbo->db)) {
547 self::$dbo->error = mysql_error(self::$dbo->db);
548 self::$dbo->errorno = mysql_errno(self::$dbo->db);
553 $a->save_timestamp($stamp1, 'database');
555 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
557 $stamp2 = microtime(true);
558 $duration = (float)($stamp2 - $stamp1);
560 if (($duration > $a->config["system"]["db_loglimit"])) {
561 $duration = round($duration, 3);
562 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
563 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
564 basename($backtrace[1]["file"])."\t".
565 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
566 substr($sql, 0, 2000)."\n", FILE_APPEND);
573 * @brief Executes a prepared statement
575 * @param string $sql SQL statement
576 * @return boolean Was the query successfull?
578 static public function e($sql) {
581 $stamp = microtime(true);
583 $args = func_get_args();
585 $stmt = call_user_func_array('self::p', $args);
587 if (is_bool($stmt)) {
589 } elseif (is_object($stmt)) {
597 $a->save_timestamp($stamp, "database_write");
603 * @brief Check if data exists
605 * @param string $sql SQL statement
606 * @return boolean Are there rows for that query?
608 static public function exists($sql) {
609 $args = func_get_args();
611 $stmt = call_user_func_array('self::p', $args);
613 if (is_bool($stmt)) {
616 $retval = (self::rows($stmt) > 0);
625 * @brief Returns the number of rows of a statement
627 * @param object Statement object
628 * @return int Number of rows
630 static public function num_rows($stmt) {
631 switch (self::$dbo->driver) {
633 return $stmt->rowCount();
635 return $stmt->num_rows;
637 return mysql_num_rows($stmt);
643 * @brief Fetch a single row
645 * @param object $stmt statement object
646 * @return array current row
648 static public function fetch($stmt) {
649 if (!is_object($stmt)) {
653 switch (self::$dbo->driver) {
655 return $stmt->fetch(PDO::FETCH_ASSOC);
657 // This code works, but is slow
659 // Bind the result to a result array
663 for ($x = 0; $x < $stmt->field_count; $x++) {
664 $cols[] = &$cols_num[$x];
667 call_user_func_array(array($stmt, 'bind_result'), $cols);
669 if (!$stmt->fetch()) {
674 // We need to get the field names for the array keys
675 // It seems that there is no better way to do this.
676 $result = $stmt->result_metadata();
677 $fields = $result->fetch_fields();
680 foreach ($cols_num AS $param => $col) {
681 $columns[$fields[$param]->name] = $col;
685 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
690 * @brief Closes the current statement
692 * @param object $stmt statement object
693 * @return boolean was the close successfull?
695 static public function close($stmt) {
696 if (!is_object($stmt)) {
700 switch (self::$dbo->driver) {
702 return $stmt->closeCursor();
704 return $stmt->free_result();
705 return $stmt->close();
707 return mysql_free_result($stmt);
712 function printable($s) {
713 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
714 $s = str_replace("\x00",'.',$s);
715 if (x($_SERVER,'SERVER_NAME')) {
716 $s = escape_tags($s);
721 // Procedural functions
722 function dbg($state) {
730 function dbesc($str) {
733 if ($db && $db->connected) {
734 return($db->escape($str));
736 return(str_replace("'","\\'",$str));
740 // Function: q($sql,$args);
741 // Description: execute SQL query with printf style args.
742 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
746 $args = func_get_args();
749 if ($db && $db->connected) {
750 $sql = $db->any_value_fallback($sql);
751 $stmt = @vsprintf($sql,$args); // Disabled warnings
752 //logger("dba: q: $stmt", LOGGER_ALL);
754 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
756 $db->log_index($stmt);
758 return $db->q($stmt);
763 * This will happen occasionally trying to store the
764 * session data after abnormal program termination
767 logger('dba: no database: ' . print_r($args,true));
772 * @brief Performs a query with "dirty reads"
774 * By doing dirty reads (reading uncommitted data) no locks are performed
775 * This function can be used to fetch data that doesn't need to be reliable.
777 * @param $args Query parameters (1 to N parameters of different types)
778 * @return array Query array
783 $args = func_get_args();
786 if ($db && $db->connected) {
787 $sql = $db->any_value_fallback($sql);
788 $stmt = @vsprintf($sql,$args); // Disabled warnings
790 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
792 $db->log_index($stmt);
794 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
795 $retval = $db->q($stmt);
796 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
802 * This will happen occasionally trying to store the
803 * session data after abnormal program termination
806 logger('dba: no database: ' . print_r($args,true));
812 * Raw db query, no arguments
818 if ($db && $db->connected) {
826 // Caller is responsible for ensuring that any integer arguments to
827 // dbesc_array are actually integers and not malformed strings containing
828 // SQL injection vectors. All integer array elements should be specifically
829 // cast to int to avoid trouble.
830 function dbesc_array_cb(&$item, $key) {
831 if (is_string($item))
832 $item = dbesc($item);
835 function dbesc_array(&$arr) {
836 if (is_array($arr) && count($arr)) {
837 array_walk($arr,'dbesc_array_cb');
841 function dba_timer() {
842 return microtime(true);