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 $stmt = self::$dbo->db->prepare($sql);
534 foreach ($args AS $param => $value) {
535 $stmt->bindParam($param, $args[$param]);
538 $success = $stmt->execute();
546 $errorInfo = self::$dbo->db->errorInfo();
549 self::$dbo->error = $errorInfo[2];
550 self::$dbo->errorno = $errorInfo[1];
555 $stmt = self::$dbo->db->stmt_init();
557 if (!$stmt->prepare($sql)) {
558 self::$dbo->error = self::$dbo->db->error;
559 self::$dbo->errorno = self::$dbo->db->errno;
566 foreach ($args AS $param => $value) {
567 if (is_int($args[$param])) {
569 } elseif (is_float($args[$param])) {
571 } elseif (is_string($args[$param])) {
576 $values[] = &$args[$param];
579 array_unshift($values, $params);
581 call_user_func_array(array($stmt, 'bind_param'), $values);
583 if (!$stmt->execute()) {
584 self::$dbo->error = self::$dbo->db->error;
585 self::$dbo->errorno = self::$dbo->db->errno;
587 } elseif (method_exists($stmt, 'get_result')) {
588 // Is mysqlnd installed?
589 $retval = $stmt->get_result();
595 // For the old "mysql" functions we cannot use prepared statements
596 foreach ($args AS $param => $value) {
597 if (is_int($args[$param]) OR is_float($args[$param])) {
598 $replace = intval($args[$param]);
600 $replace = "'".dbesc($args[$param])."'";
603 $pos = strpos($sql, '?');
604 if ($pos !== false) {
605 $sql = substr_replace($sql, $replace, $pos, 1);
609 $retval = mysql_query($sql, self::$dbo->db);
610 if (mysql_errno(self::$dbo->db)) {
611 self::$dbo->error = mysql_error(self::$dbo->db);
612 self::$dbo->errorno = mysql_errno(self::$dbo->db);
617 $stamp2 = microtime(true);
618 $duration = (float)($stamp2 - $stamp1);
620 $a->save_timestamp($stamp1, 'database');
622 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
623 $a->save_timestamp($stamp1, "database_write");
630 * @brief Executes a prepared statement
632 * @param string $sql SQL statement
633 * @return boolean Was the query successfull?
635 static public function e($sql) {
636 $args = func_get_args();
643 * @brief Fetch a single row
645 * @param object $stmt statement object
646 * @return array current row
648 static public function fetch($stmt) {
649 switch (self::$dbo->driver) {
651 return $stmt->fetch(PDO::FETCH_ASSOC);
653 // When mysqlnd is installed, we can use a shortcut
654 if (method_exists($stmt, 'fetch_array')) {
655 return $stmt->fetch_array(MYSQLI_ASSOC);
658 // This code works, but is slow
660 // Bind the result to a result array
664 for ($x = 0; $x < $stmt->field_count; $x++) {
665 $cols[] = &$cols_num[$x];
668 call_user_func_array(array($stmt, 'bind_result'), $cols);
670 $success = $stmt->fetch();
677 // We need to get the field names for the array keys
678 // It seems that there is no better way to do this.
679 $result = $stmt->result_metadata();
682 foreach ($cols_num AS $col) {
683 $field = $result->fetch_field();
684 $columns[$field->name] = $col;
688 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
693 * @brief Closes the current statement
695 * @param object $stmt statement object
696 * @return boolean was the close successfull?
698 static public function close($stmt) {
699 switch (self::$dbo->driver) {
701 return $stmt->closeCursor();
703 return $stmt->close();
705 return mysql_free_result($stmt);
710 function printable($s) {
711 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
712 $s = str_replace("\x00",'.',$s);
713 if (x($_SERVER,'SERVER_NAME')) {
714 $s = escape_tags($s);
719 // Procedural functions
720 function dbg($state) {
728 function dbesc($str) {
731 if ($db && $db->connected) {
732 return($db->escape($str));
734 return(str_replace("'","\\'",$str));
738 // Function: q($sql,$args);
739 // Description: execute SQL query with printf style args.
740 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
744 $args = func_get_args();
747 if ($db && $db->connected) {
748 $sql = $db->any_value_fallback($sql);
749 $stmt = @vsprintf($sql,$args); // Disabled warnings
750 //logger("dba: q: $stmt", LOGGER_ALL);
752 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
754 $db->log_index($stmt);
756 return $db->q($stmt);
761 * This will happen occasionally trying to store the
762 * session data after abnormal program termination
765 logger('dba: no database: ' . print_r($args,true));
770 * @brief Performs a query with "dirty reads"
772 * By doing dirty reads (reading uncommitted data) no locks are performed
773 * This function can be used to fetch data that doesn't need to be reliable.
775 * @param $args Query parameters (1 to N parameters of different types)
776 * @return array Query array
781 $args = func_get_args();
784 if ($db && $db->connected) {
785 $sql = $db->any_value_fallback($sql);
786 $stmt = @vsprintf($sql,$args); // Disabled warnings
788 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
790 $db->log_index($stmt);
792 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
793 $retval = $db->q($stmt);
794 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
800 * This will happen occasionally trying to store the
801 * session data after abnormal program termination
804 logger('dba: no database: ' . print_r($args,true));
810 * Raw db query, no arguments
816 if ($db && $db->connected) {
824 // Caller is responsible for ensuring that any integer arguments to
825 // dbesc_array are actually integers and not malformed strings containing
826 // SQL injection vectors. All integer array elements should be specifically
827 // cast to int to avoid trouble.
828 function dbesc_array_cb(&$item, $key) {
829 if (is_string($item))
830 $item = dbesc($item);
833 function dbesc_array(&$arr) {
834 if (is_array($arr) && count($arr)) {
835 array_walk($arr,'dbesc_array_cb');
839 function dba_timer() {
840 return microtime(true);