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 switch (self::$dbo->driver) {
497 if (!$stmt = self::$dbo->db->prepare($sql)) {
498 $errorInfo = self::$dbo->db->errorInfo();
499 self::$dbo->error = $errorInfo[2];
500 self::$dbo->errorno = $errorInfo[1];
505 foreach ($args AS $param => $value) {
506 $stmt->bindParam($param, $args[$param]);
509 if (!$stmt->execute()) {
510 $errorInfo = self::$dbo->db->errorInfo();
511 self::$dbo->error = $errorInfo[2];
512 self::$dbo->errorno = $errorInfo[1];
519 $stmt = self::$dbo->db->stmt_init();
521 if (!$stmt->prepare($sql)) {
522 self::$dbo->error = self::$dbo->db->error;
523 self::$dbo->errorno = self::$dbo->db->errno;
530 foreach ($args AS $param => $value) {
531 if (is_int($args[$param])) {
533 } elseif (is_float($args[$param])) {
535 } elseif (is_string($args[$param])) {
540 $values[] = &$args[$param];
543 array_unshift($values, $params);
545 call_user_func_array(array($stmt, 'bind_param'), $values);
547 if (!$stmt->execute()) {
548 self::$dbo->error = self::$dbo->db->error;
549 self::$dbo->errorno = self::$dbo->db->errno;
552 $stmt->store_result();
557 // For the old "mysql" functions we cannot use prepared statements
558 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
559 if (mysql_errno(self::$dbo->db)) {
560 self::$dbo->error = mysql_error(self::$dbo->db);
561 self::$dbo->errorno = mysql_errno(self::$dbo->db);
566 $a->save_timestamp($stamp1, 'database');
568 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
570 $stamp2 = microtime(true);
571 $duration = (float)($stamp2 - $stamp1);
573 if (($duration > $a->config["system"]["db_loglimit"])) {
574 $duration = round($duration, 3);
575 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
577 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
578 basename($backtrace[1]["file"])."\t".
579 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
580 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
587 * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
589 * @param string $sql SQL statement
590 * @return boolean Was the query successfull? False is returned only if an error occurred
592 static public function e($sql) {
595 $stamp = microtime(true);
597 $args = func_get_args();
599 $stmt = call_user_func_array('self::p', $args);
601 if (is_bool($stmt)) {
603 } elseif (is_object($stmt)) {
611 $a->save_timestamp($stamp, "database_write");
617 * @brief Check if data exists
619 * @param string $sql SQL statement
620 * @return boolean Are there rows for that query?
622 static public function exists($sql) {
623 $args = func_get_args();
625 $stmt = call_user_func_array('self::p', $args);
627 if (is_bool($stmt)) {
630 $retval = (self::rows($stmt) > 0);
639 * @brief Returns the number of rows of a statement
641 * @param object Statement object
642 * @return int Number of rows
644 static public function num_rows($stmt) {
645 switch (self::$dbo->driver) {
647 return $stmt->rowCount();
649 return $stmt->num_rows;
651 return mysql_num_rows($stmt);
657 * @brief Fetch a single row
659 * @param object $stmt statement object
660 * @return array current row
662 static public function fetch($stmt) {
663 if (!is_object($stmt)) {
667 switch (self::$dbo->driver) {
669 return $stmt->fetch(PDO::FETCH_ASSOC);
671 // This code works, but is slow
673 // Bind the result to a result array
677 for ($x = 0; $x < $stmt->field_count; $x++) {
678 $cols[] = &$cols_num[$x];
681 call_user_func_array(array($stmt, 'bind_result'), $cols);
683 if (!$stmt->fetch()) {
688 // We need to get the field names for the array keys
689 // It seems that there is no better way to do this.
690 $result = $stmt->result_metadata();
691 $fields = $result->fetch_fields();
694 foreach ($cols_num AS $param => $col) {
695 $columns[$fields[$param]->name] = $col;
699 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
704 * @brief Closes the current statement
706 * @param object $stmt statement object
707 * @return boolean was the close successfull?
709 static public function close($stmt) {
710 if (!is_object($stmt)) {
714 switch (self::$dbo->driver) {
716 return $stmt->closeCursor();
718 return $stmt->free_result();
719 return $stmt->close();
721 return mysql_free_result($stmt);
726 function printable($s) {
727 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
728 $s = str_replace("\x00",'.',$s);
729 if (x($_SERVER,'SERVER_NAME')) {
730 $s = escape_tags($s);
735 // Procedural functions
736 function dbg($state) {
744 function dbesc($str) {
747 if ($db && $db->connected) {
748 return($db->escape($str));
750 return(str_replace("'","\\'",$str));
754 // Function: q($sql,$args);
755 // Description: execute SQL query with printf style args.
756 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
760 $args = func_get_args();
763 if ($db && $db->connected) {
764 $sql = $db->any_value_fallback($sql);
765 $stmt = @vsprintf($sql,$args); // Disabled warnings
766 //logger("dba: q: $stmt", LOGGER_ALL);
768 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
770 $db->log_index($stmt);
772 return $db->q($stmt);
777 * This will happen occasionally trying to store the
778 * session data after abnormal program termination
781 logger('dba: no database: ' . print_r($args,true));
786 * @brief Performs a query with "dirty reads"
788 * By doing dirty reads (reading uncommitted data) no locks are performed
789 * This function can be used to fetch data that doesn't need to be reliable.
791 * @param $args Query parameters (1 to N parameters of different types)
792 * @return array Query array
797 $args = func_get_args();
800 if ($db && $db->connected) {
801 $sql = $db->any_value_fallback($sql);
802 $stmt = @vsprintf($sql,$args); // Disabled warnings
804 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
806 $db->log_index($stmt);
808 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
809 $retval = $db->q($stmt);
810 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
816 * This will happen occasionally trying to store the
817 * session data after abnormal program termination
820 logger('dba: no database: ' . print_r($args,true));
826 * Raw db query, no arguments
832 if ($db && $db->connected) {
840 // Caller is responsible for ensuring that any integer arguments to
841 // dbesc_array are actually integers and not malformed strings containing
842 // SQL injection vectors. All integer array elements should be specifically
843 // cast to int to avoid trouble.
844 function dbesc_array_cb(&$item, $key) {
845 if (is_string($item))
846 $item = dbesc($item);
849 function dbesc_array(&$arr) {
850 if (is_array($arr) && count($arr)) {
851 array_walk($arr,'dbesc_array_cb');
855 function dba_timer() {
856 return microtime(true);