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 Returns the number of rows
142 public function num_rows() {
143 if (!$this->result) {
147 switch ($this->driver) {
149 $rows = $this->result->rowCount();
152 $rows = $this->result->num_rows;
155 $rows = mysql_num_rows($this->result);
162 * @brief Analyze a database query and log this if some conditions are met.
164 * @param string $query The database query that will be analyzed
166 public function log_index($query) {
169 if ($a->config["system"]["db_log_index"] == "") {
173 // Don't explain an explain statement
174 if (strtolower(substr($query, 0, 7)) == "explain") {
178 // Only do the explain on "select", "update" and "delete"
179 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
183 $r = $this->q("EXPLAIN ".$query);
184 if (!dbm::is_result($r)) {
188 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
189 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
191 foreach ($r AS $row) {
192 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
193 $log = (in_array($row['key'], $watchlist) AND
194 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
199 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
203 if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
208 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
209 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
210 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
211 basename($backtrace[1]["file"])."\t".
212 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
213 substr($query, 0, 2000)."\n", FILE_APPEND);
218 public function q($sql, $onlyquery = false) {
221 if (!$this->db || !$this->connected) {
227 $connstr = ($this->connected() ? "Connected" : "Disonnected");
229 $stamp1 = microtime(true);
233 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
234 $sql = "/*".$a->callstack()." */ ".$sql;
239 switch ($this->driver) {
241 $result = @$this->db->query($sql);
242 // Is used to separate between queries that returning data - or not
243 if (!is_bool($result)) {
244 $columns = $result->columnCount();
248 $result = @$this->db->query($sql);
251 $result = @mysql_query($sql,$this->db);
254 $stamp2 = microtime(true);
255 $duration = (float)($stamp2 - $stamp1);
257 $a->save_timestamp($stamp1, "database");
259 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
260 $a->save_timestamp($stamp1, "database_write");
262 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
263 if (($duration > $a->config["system"]["db_loglimit"])) {
264 $duration = round($duration, 3);
265 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
266 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
267 basename($backtrace[1]["file"])."\t".
268 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
269 substr($sql, 0, 2000)."\n", FILE_APPEND);
273 switch ($this->driver) {
275 $errorInfo = $this->db->errorInfo();
277 $this->error = $errorInfo[2];
278 $this->errorno = $errorInfo[1];
282 if ($this->db->errno) {
283 $this->error = $this->db->error;
284 $this->errorno = $this->db->errno;
288 if (mysql_errno($this->db)) {
289 $this->error = mysql_error($this->db);
290 $this->errorno = mysql_errno($this->db);
294 if (strlen($this->error)) {
295 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
302 if ($result === false) {
304 } elseif ($result === true) {
307 switch ($this->driver) {
309 $mesg = $result->rowCount().' results'.EOL;
312 $mesg = $result->num_rows.' results'.EOL;
315 $mesg = mysql_num_rows($result).' results'.EOL;
320 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
321 . (($this->error) ? ' error: ' . $this->error : '')
324 logger('dba: ' . $str );
328 * If dbfail.out exists, we will write any failed calls directly to it,
329 * regardless of any logging that may or may nor be in effect.
330 * These usually indicate SQL syntax errors that need to be resolved.
333 if ($result === false) {
334 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
335 if (file_exists('dbfail.out')) {
336 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
340 if (is_bool($result)) {
344 $this->result = $result;
349 switch ($this->driver) {
351 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
354 $result->closeCursor();
357 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
360 $result->free_result();
363 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
366 mysql_free_result($result);
370 // PDO doesn't return "true" on successful operations - like mysqli does
371 // Emulate this behaviour by checking if the query returned data and had columns
372 // This should be reliable enough
373 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
377 //$a->save_timestamp($stamp1, "database");
380 logger('dba: ' . printable(print_r($r, true)));
385 public function qfetch() {
389 switch ($this->driver) {
391 $x = $this->result->fetch(PDO::FETCH_ASSOC);
394 $x = $this->result->fetch_array(MYSQLI_ASSOC);
397 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
404 public function qclose() {
406 switch ($this->driver) {
408 $this->result->closeCursor();
411 $this->result->free_result();
414 mysql_free_result($this->result);
420 public function dbg($dbg) {
424 public function escape($str) {
425 if ($this->db && $this->connected) {
426 switch ($this->driver) {
428 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
430 return @$this->db->real_escape_string($str);
432 return @mysql_real_escape_string($str,$this->db);
437 function connected() {
438 switch ($this->driver) {
440 // Not sure if this really is working like expected
441 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
444 $connected = $this->db->ping();
447 $connected = mysql_ping($this->db);
453 function insert_id() {
454 switch ($this->driver) {
456 $id = $this->db->lastInsertId();
459 $id = $this->db->insert_id;
462 $id = mysql_insert_id($this->db);
468 function __destruct() {
470 switch ($this->driver) {
478 mysql_close($this->db);
485 * @brief Replaces ANY_VALUE() function by MIN() function,
486 * if the database server does not support ANY_VALUE().
488 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
489 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
490 * A standard fall-back is to use MIN().
492 * @param string $sql An SQL string without the values
493 * @return string The input SQL string modified if necessary.
495 public function any_value_fallback($sql) {
496 $server_info = $this->server_info();
497 if (version_compare($server_info, '5.7.5', '<') ||
498 (stripos($server_info, 'MariaDB') !== false)) {
499 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
505 * @brief Executes a prepared statement
507 * @param string $sql SQL statement
508 * @return object statement object
510 static public function p($sql) {
513 $stamp1 = microtime(true);
515 $args = func_get_args();
518 if (!self::$dbo OR !self::$dbo->connected) {
522 $sql = self::$dbo->any_value_fallback($sql);
526 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
527 $sql = "/*".$a->callstack()." */ ".$sql;
530 switch (self::$dbo->driver) {
532 if (!$stmt = self::$dbo->db->prepare($sql)) {
533 $errorInfo = self::$dbo->db->errorInfo();
534 self::$dbo->error = $errorInfo[2];
535 self::$dbo->errorno = $errorInfo[1];
540 foreach ($args AS $param => $value) {
541 $stmt->bindParam($param, $args[$param]);
544 if (!$stmt->execute()) {
545 $errorInfo = self::$dbo->db->errorInfo();
546 self::$dbo->error = $errorInfo[2];
547 self::$dbo->errorno = $errorInfo[1];
554 $stmt = self::$dbo->db->stmt_init();
556 if (!$stmt->prepare($sql)) {
557 self::$dbo->error = self::$dbo->db->error;
558 self::$dbo->errorno = self::$dbo->db->errno;
565 foreach ($args AS $param => $value) {
566 if (is_int($args[$param])) {
568 } elseif (is_float($args[$param])) {
570 } elseif (is_string($args[$param])) {
575 $values[] = &$args[$param];
578 array_unshift($values, $params);
580 call_user_func_array(array($stmt, 'bind_param'), $values);
582 if (!$stmt->execute()) {
583 self::$dbo->error = self::$dbo->db->error;
584 self::$dbo->errorno = self::$dbo->db->errno;
586 } elseif (method_exists($stmt, 'get_result')) {
587 // Is mysqlnd installed?
588 $retval = $stmt->get_result();
594 // For the old "mysql" functions we cannot use prepared statements
595 foreach ($args AS $param => $value) {
596 if (is_int($args[$param]) OR is_float($args[$param])) {
597 $replace = intval($args[$param]);
599 $replace = "'".dbesc($args[$param])."'";
602 $pos = strpos($sql, '?');
603 if ($pos !== false) {
604 $sql = substr_replace($sql, $replace, $pos, 1);
608 $retval = mysql_query($sql, self::$dbo->db);
609 if (mysql_errno(self::$dbo->db)) {
610 self::$dbo->error = mysql_error(self::$dbo->db);
611 self::$dbo->errorno = mysql_errno(self::$dbo->db);
616 $a->save_timestamp($stamp1, 'database');
618 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
620 $stamp2 = microtime(true);
621 $duration = (float)($stamp2 - $stamp1);
623 if (($duration > $a->config["system"]["db_loglimit"])) {
624 $duration = round($duration, 3);
625 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
626 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
627 basename($backtrace[1]["file"])."\t".
628 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
629 substr($sql, 0, 2000)."\n", FILE_APPEND);
636 * @brief Executes a prepared statement
638 * @param string $sql SQL statement
639 * @return boolean Was the query successfull?
641 static public function e($sql) {
644 $stamp = microtime(true);
646 $args = func_get_args();
648 $stmt = call_user_func_array('self::p', $args);
650 if (is_bool($stmt)) {
652 } elseif (is_object($stmt)) {
660 $a->save_timestamp($stamp, "database_write");
666 * @brief Check if data exists
668 * @param string $sql SQL statement
669 * @return boolean Are there rows for that query?
671 static public function exists($sql) {
672 $args = func_get_args();
674 $stmt = call_user_func_array('self::p', $args);
676 if (is_bool($stmt)) {
679 $retval = is_array(self::fetch($stmt));
688 * @brief Fetch a single row
690 * @param object $stmt statement object
691 * @return array current row
693 static public function fetch($stmt) {
694 if (!is_object($stmt)) {
698 switch (self::$dbo->driver) {
700 return $stmt->fetch(PDO::FETCH_ASSOC);
702 // When mysqlnd is installed, we can use a shortcut
703 if (method_exists($stmt, 'fetch_array')) {
704 return $stmt->fetch_array(MYSQLI_ASSOC);
707 // This code works, but is slow
709 // Bind the result to a result array
713 for ($x = 0; $x < $stmt->field_count; $x++) {
714 $cols[] = &$cols_num[$x];
717 call_user_func_array(array($stmt, 'bind_result'), $cols);
719 $success = $stmt->fetch();
726 // We need to get the field names for the array keys
727 // It seems that there is no better way to do this.
728 $result = $stmt->result_metadata();
731 foreach ($cols_num AS $col) {
732 $field = $result->fetch_field();
733 $columns[$field->name] = $col;
737 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
742 * @brief Closes the current statement
744 * @param object $stmt statement object
745 * @return boolean was the close successfull?
747 static public function close($stmt) {
748 if (!is_object($stmt)) {
752 switch (self::$dbo->driver) {
754 return $stmt->closeCursor();
756 return $stmt->close();
758 return mysql_free_result($stmt);
763 function printable($s) {
764 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
765 $s = str_replace("\x00",'.',$s);
766 if (x($_SERVER,'SERVER_NAME')) {
767 $s = escape_tags($s);
772 // Procedural functions
773 function dbg($state) {
781 function dbesc($str) {
784 if ($db && $db->connected) {
785 return($db->escape($str));
787 return(str_replace("'","\\'",$str));
791 // Function: q($sql,$args);
792 // Description: execute SQL query with printf style args.
793 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
797 $args = func_get_args();
800 if ($db && $db->connected) {
801 $sql = $db->any_value_fallback($sql);
802 $stmt = @vsprintf($sql,$args); // Disabled warnings
803 //logger("dba: q: $stmt", LOGGER_ALL);
805 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
807 $db->log_index($stmt);
809 return $db->q($stmt);
814 * This will happen occasionally trying to store the
815 * session data after abnormal program termination
818 logger('dba: no database: ' . print_r($args,true));
823 * @brief Performs a query with "dirty reads"
825 * By doing dirty reads (reading uncommitted data) no locks are performed
826 * This function can be used to fetch data that doesn't need to be reliable.
828 * @param $args Query parameters (1 to N parameters of different types)
829 * @return array Query array
834 $args = func_get_args();
837 if ($db && $db->connected) {
838 $sql = $db->any_value_fallback($sql);
839 $stmt = @vsprintf($sql,$args); // Disabled warnings
841 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
843 $db->log_index($stmt);
845 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
846 $retval = $db->q($stmt);
847 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
853 * This will happen occasionally trying to store the
854 * session data after abnormal program termination
857 logger('dba: no database: ' . print_r($args,true));
863 * Raw db query, no arguments
869 if ($db && $db->connected) {
877 // Caller is responsible for ensuring that any integer arguments to
878 // dbesc_array are actually integers and not malformed strings containing
879 // SQL injection vectors. All integer array elements should be specifically
880 // cast to int to avoid trouble.
881 function dbesc_array_cb(&$item, $key) {
882 if (is_string($item))
883 $item = dbesc($item);
886 function dbesc_array(&$arr) {
887 if (is_array($arr) && count($arr)) {
888 array_walk($arr,'dbesc_array_cb');
892 function dba_timer() {
893 return microtime(true);