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.
23 public $connected = false;
24 public $error = false;
25 private $_server_info = '';
28 function __construct($server, $user, $pass, $db, $install = false) {
31 $stamp1 = microtime(true);
33 $server = trim($server);
38 if (!(strlen($server) && strlen($user))) {
39 $this->connected = false;
45 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
46 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
47 $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
48 $this->connected = false;
55 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
56 $this->driver = 'pdo';
57 $connect = "mysql:host=".$server.";dbname=".$db;
58 if (isset($a->config["system"]["db_charset"])) {
59 $connect .= ";charset=".$a->config["system"]["db_charset"];
61 $this->db = @new PDO($connect, $user, $pass);
62 if (!$this->db->errorCode()) {
63 $this->connected = true;
65 } elseif (class_exists('mysqli')) {
66 $this->driver = 'mysqli';
67 $this->db = @new mysqli($server,$user,$pass,$db);
68 if (!mysqli_connect_errno()) {
69 $this->connected = true;
71 if (isset($a->config["system"]["db_charset"])) {
72 $this->db->set_charset($a->config["system"]["db_charset"]);
75 } elseif (function_exists('mysql_connect')) {
76 $this->driver = 'mysql';
77 $this->db = mysql_connect($server,$user,$pass);
78 if ($this->db && mysql_select_db($db,$this->db)) {
79 $this->connected = true;
81 if (isset($a->config["system"]["db_charset"])) {
82 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
86 // No suitable SQL driver was found.
92 if (!$this->connected) {
98 $a->save_timestamp($stamp1, "network");
104 * @brief Returns the MySQL server version string
106 * This function discriminate between the deprecated mysql API and the current
107 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
111 public function server_info() {
112 if ($this->_server_info == '') {
113 switch ($this->driver) {
115 $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
118 $this->_server_info = $this->db->server_info;
121 $this->_server_info = mysql_get_server_info($this->db);
125 return $this->_server_info;
129 * @brief Returns the selected database name
133 public function database_name() {
134 $r = $this->q("SELECT DATABASE() AS `db`");
140 * @brief Returns the number of rows
144 public function num_rows() {
145 if (!$this->result) {
149 switch ($this->driver) {
151 $rows = $this->result->rowCount();
154 $rows = $this->result->num_rows;
157 $rows = mysql_num_rows($this->result);
164 * @brief Analyze a database query and log this if some conditions are met.
166 * @param string $query The database query that will be analyzed
168 public function log_index($query) {
171 if ($a->config["system"]["db_log_index"] == "") {
175 // Don't explain an explain statement
176 if (strtolower(substr($query, 0, 7)) == "explain") {
180 // Only do the explain on "select", "update" and "delete"
181 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
185 $r = $this->q("EXPLAIN ".$query);
186 if (!dbm::is_result($r)) {
190 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
191 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
193 foreach ($r AS $row) {
194 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
195 $log = (in_array($row['key'], $watchlist) AND
196 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
201 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
205 if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
210 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
211 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
212 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
213 basename($backtrace[1]["file"])."\t".
214 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
215 substr($query, 0, 2000)."\n", FILE_APPEND);
220 public function q($sql, $onlyquery = false) {
223 if (!$this->db || !$this->connected) {
229 $connstr = ($this->connected() ? "Connected" : "Disonnected");
231 $stamp1 = microtime(true);
235 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
236 $sql = "/*".$a->callstack()." */ ".$sql;
241 switch ($this->driver) {
243 $result = @$this->db->query($sql);
244 // Is used to separate between queries that returning data - or not
245 if (!is_bool($result)) {
246 $columns = $result->columnCount();
250 $result = @$this->db->query($sql);
253 $result = @mysql_query($sql,$this->db);
256 $stamp2 = microtime(true);
257 $duration = (float)($stamp2-$stamp1);
259 $a->save_timestamp($stamp1, "database");
261 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
262 $a->save_timestamp($stamp1, "database_write");
264 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
265 if (($duration > $a->config["system"]["db_loglimit"])) {
266 $duration = round($duration, 3);
267 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
268 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
269 basename($backtrace[1]["file"])."\t".
270 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
271 substr($sql, 0, 2000)."\n", FILE_APPEND);
275 switch ($this->driver) {
277 $errorInfo = $this->db->errorInfo();
279 $this->error = $errorInfo[2];
280 $this->errorno = $errorInfo[1];
284 if ($this->db->errno) {
285 $this->error = $this->db->error;
286 $this->errorno = $this->db->errno;
290 if (mysql_errno($this->db)) {
291 $this->error = mysql_error($this->db);
292 $this->errorno = mysql_errno($this->db);
296 if (strlen($this->error)) {
297 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
304 if ($result === false) {
306 } elseif ($result === true) {
309 switch ($this->driver) {
311 $mesg = $result->rowCount().' results'.EOL;
314 $mesg = $result->num_rows.' results'.EOL;
317 $mesg = mysql_num_rows($result).' results'.EOL;
322 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
323 . (($this->error) ? ' error: ' . $this->error : '')
326 logger('dba: ' . $str );
330 * If dbfail.out exists, we will write any failed calls directly to it,
331 * regardless of any logging that may or may nor be in effect.
332 * These usually indicate SQL syntax errors that need to be resolved.
335 if ($result === false) {
336 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
337 if (file_exists('dbfail.out')) {
338 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
342 if (is_bool($result)) {
346 $this->result = $result;
351 switch ($this->driver) {
353 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
356 $result->closeCursor();
359 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
362 $result->free_result();
365 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
368 mysql_free_result($result);
372 // PDO doesn't return "true" on successful operations - like mysqli does
373 // Emulate this behaviour by checking if the query returned data and had columns
374 // This should be reliable enough
375 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
379 //$a->save_timestamp($stamp1, "database");
382 logger('dba: ' . printable(print_r($r, true)));
387 public function qfetch() {
391 switch ($this->driver) {
393 $x = $this->result->fetch(PDO::FETCH_ASSOC);
396 $x = $this->result->fetch_array(MYSQLI_ASSOC);
399 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
406 public function qclose() {
408 switch ($this->driver) {
410 $this->result->closeCursor();
413 $this->result->free_result();
416 mysql_free_result($this->result);
422 public function dbg($dbg) {
426 public function escape($str) {
427 if ($this->db && $this->connected) {
428 switch ($this->driver) {
430 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
432 return @$this->db->real_escape_string($str);
434 return @mysql_real_escape_string($str,$this->db);
439 function connected() {
440 switch ($this->driver) {
442 // Not sure if this really is working like expected
443 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
446 $connected = $this->db->ping();
449 $connected = mysql_ping($this->db);
455 function insert_id() {
456 switch ($this->driver) {
458 $id = $this->db->lastInsertId();
461 $id = $this->db->insert_id;
464 $id = mysql_insert_id($this->db);
471 * @brief Replaces ANY_VALUE() function by MIN() function,
472 * if the database server does not support ANY_VALUE().
474 * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
475 * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
476 * A standard fall-back is to use MIN().
478 * @param string $sql An SQL string without the values
479 * @return string The input SQL string modified if necessary.
481 public function any_value_fallback($sql) {
482 $server_info = $this->server_info();
483 if (version_compare($server_info, '5.7.5', '<') ||
484 (stripos($server_info, 'MariaDB') !== false)) {
485 $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
490 function __destruct() {
492 switch ($this->driver) {
500 mysql_close($this->db);
507 * @brief Executes a prepared statement
509 * @param string $sql SQL statement
510 * @return object statement object
512 static public function p($sql) {
515 $stamp1 = microtime(true);
517 $args = func_get_args();
520 if (!self::$dbo OR !self::$dbo->connected) {
524 $sql = self::$dbo->any_value_fallback($sql);
528 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
529 $sql = "/*".$a->callstack()." */ ".$sql;
532 switch (self::$dbo->driver) {
534 $stmt = self::$dbo->db->prepare($sql);
536 foreach ($args AS $param => $value) {
537 $stmt->bindParam($param, $args[$param]);
540 $success = $stmt->execute();
548 $errorInfo = self::$dbo->db->errorInfo();
551 self::$dbo->error = $errorInfo[2];
552 self::$dbo->errorno = $errorInfo[1];
557 $stmt = self::$dbo->db->stmt_init();
559 if (!$stmt->prepare($sql)) {
560 self::$dbo->error = self::$dbo->db->error;
561 self::$dbo->errorno = self::$dbo->db->errno;
568 foreach ($args AS $param => $value) {
569 if (is_int($args[$param])) {
571 } elseif (is_float($args[$param])) {
573 } elseif (is_string($args[$param])) {
578 $values[] = &$args[$param];
581 array_unshift($values, $params);
583 call_user_func_array(array($stmt, 'bind_param'), $values);
585 if (!$stmt->execute()) {
586 self::$dbo->error = self::$dbo->db->error;
587 self::$dbo->errorno = self::$dbo->db->errno;
589 } elseif (method_exists($stmt, 'get_result')) {
590 // Is mysqlnd installed?
591 $retval = $stmt->get_result();
597 // For the old "mysql" functions we cannot use prepared statements
598 foreach ($args AS $param => $value) {
599 if (is_int($args[$param]) OR is_float($args[$param])) {
600 $replace = intval($args[$param]);
602 $replace = "'".dbesc($args[$param])."'";
605 $pos = strpos($sql, '?');
606 if ($pos !== false) {
607 $sql = substr_replace($sql, $replace, $pos, 1);
611 $retval = mysql_query($sql, self::$dbo->db);
612 if (mysql_errno(self::$dbo->db)) {
613 self::$dbo->error = mysql_error(self::$dbo->db);
614 self::$dbo->errorno = mysql_errno(self::$dbo->db);
619 $stamp2 = microtime(true);
620 $duration = (float)($stamp2 - $stamp1);
622 $a->save_timestamp($stamp1, 'database');
624 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
625 $a->save_timestamp($stamp1, "database_write");
632 * @brief Executes a prepared statement
634 * @param string $sql SQL statement
635 * @return boolean Was the query successfull?
637 static public function e($sql) {
641 * @brief Fetch a single row
643 * @param object $stmt statement object
644 * @return array current row
646 static public function fetch($stmt) {
647 switch (self::$dbo->driver) {
649 return $stmt->fetch(PDO::FETCH_ASSOC);
651 // When mysqlnd is installed, we can use a shortcut
652 if (method_exists($stmt, 'fetch_array')) {
653 return $stmt->fetch_array(MYSQLI_ASSOC);
656 // This code works, but is slow
658 // Bind the result to a result array
662 for ($x = 0; $x < $stmt->field_count; $x++) {
663 $cols[] = &$cols_num[$x];
666 call_user_func_array(array($stmt, 'bind_result'), $cols);
668 $success = $stmt->fetch();
675 // We need to get the field names for the array keys
676 // It seems that there is no better way to do this.
677 $result = $stmt->result_metadata();
680 foreach ($cols_num AS $col) {
681 $field = $result->fetch_field();
682 $columns[$field->name] = $col;
686 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
691 * @brief Closes the current statement
693 * @param object $stmt statement object
694 * @return boolean was the close successfull?
696 static public function close($stmt) {
697 switch (self::$dbo->driver) {
699 return $stmt->closeCursor();
701 return $stmt->close();
703 return mysql_free_result($stmt);
708 function printable($s) {
709 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
710 $s = str_replace("\x00",'.',$s);
711 if (x($_SERVER,'SERVER_NAME')) {
712 $s = escape_tags($s);
717 // Procedural functions
718 function dbg($state) {
726 function dbesc($str) {
729 if ($db && $db->connected) {
730 return($db->escape($str));
732 return(str_replace("'","\\'",$str));
736 // Function: q($sql,$args);
737 // Description: execute SQL query with printf style args.
738 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
742 $args = func_get_args();
745 if ($db && $db->connected) {
746 $sql = $db->any_value_fallback($sql);
747 $stmt = @vsprintf($sql,$args); // Disabled warnings
748 //logger("dba: q: $stmt", LOGGER_ALL);
750 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
752 $db->log_index($stmt);
754 return $db->q($stmt);
759 * This will happen occasionally trying to store the
760 * session data after abnormal program termination
763 logger('dba: no database: ' . print_r($args,true));
768 * @brief Performs a query with "dirty reads"
770 * By doing dirty reads (reading uncommitted data) no locks are performed
771 * This function can be used to fetch data that doesn't need to be reliable.
773 * @param $args Query parameters (1 to N parameters of different types)
774 * @return array Query array
779 $args = func_get_args();
782 if ($db && $db->connected) {
783 $sql = $db->any_value_fallback($sql);
784 $stmt = @vsprintf($sql,$args); // Disabled warnings
786 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
788 $db->log_index($stmt);
790 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
791 $retval = $db->q($stmt);
792 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
798 * This will happen occasionally trying to store the
799 * session data after abnormal program termination
802 logger('dba: no database: ' . print_r($args,true));
808 * Raw db query, no arguments
814 if ($db && $db->connected) {
822 // Caller is responsible for ensuring that any integer arguments to
823 // dbesc_array are actually integers and not malformed strings containing
824 // SQL injection vectors. All integer array elements should be specifically
825 // cast to int to avoid trouble.
826 function dbesc_array_cb(&$item, $key) {
827 if (is_string($item))
828 $item = dbesc($item);
831 function dbesc_array(&$arr) {
832 if (is_array($arr) && count($arr)) {
833 array_walk($arr,'dbesc_array_cb');
837 function dba_timer() {
838 return microtime(true);