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;
24 function __construct($server, $user, $pass, $db, $install = false) {
27 $stamp1 = microtime(true);
29 $server = trim($server);
34 if (!(strlen($server) && strlen($user))) {
35 $this->connected = false;
41 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
42 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
43 $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
44 $this->connected = false;
51 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
52 $this->driver = 'pdo';
53 $connect = "mysql:host=".$server.";dbname=".$db;
54 if (isset($a->config["system"]["db_charset"])) {
55 $connect .= ";charset=".$a->config["system"]["db_charset"];
57 $this->db = @new PDO($connect, $user, $pass);
58 if (!$this->db->errorCode()) {
59 $this->connected = true;
61 } elseif (class_exists('mysqli')) {
62 $this->driver = 'mysqli';
63 $this->db = @new mysqli($server,$user,$pass,$db);
64 if (!mysqli_connect_errno()) {
65 $this->connected = true;
67 if (isset($a->config["system"]["db_charset"])) {
68 $this->db->set_charset($a->config["system"]["db_charset"]);
71 } elseif (function_exists('mysql_connect')) {
72 $this->driver = 'mysql';
73 $this->db = mysql_connect($server,$user,$pass);
74 if ($this->db && mysql_select_db($db,$this->db)) {
75 $this->connected = true;
77 if (isset($a->config["system"]["db_charset"])) {
78 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
82 // No suitable SQL driver was found.
88 if (!$this->connected) {
94 $a->save_timestamp($stamp1, "network");
98 * @brief Returns the MySQL server version string
100 * This function discriminate between the deprecated mysql API and the current
101 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
105 public function server_info() {
106 switch ($this->driver) {
108 $version = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
111 $version = $this->db->server_info;
114 $version = mysql_get_server_info($this->db);
121 * @brief Returns the selected database name
125 public function database_name() {
126 $r = $this->q("SELECT DATABASE() AS `db`");
132 * @brief Returns the number of rows
136 public function num_rows() {
137 if (!$this->result) {
141 switch ($this->driver) {
143 $rows = $this->result->rowCount();
146 $rows = $this->result->num_rows;
149 $rows = mysql_num_rows($this->result);
156 * @brief Analyze a database query and log this if some conditions are met.
158 * @param string $query The database query that will be analyzed
160 public function log_index($query) {
163 if ($a->config["system"]["db_log_index"] == "") {
167 // Don't explain an explain statement
168 if (strtolower(substr($query, 0, 7)) == "explain") {
172 // Only do the explain on "select", "update" and "delete"
173 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
177 $r = $this->q("EXPLAIN ".$query);
178 if (!dbm::is_result($r)) {
182 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
183 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
185 foreach ($r AS $row) {
186 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
187 $log = (in_array($row['key'], $watchlist) AND
188 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
193 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
197 if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
202 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
203 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
204 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
205 basename($backtrace[1]["file"])."\t".
206 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
207 substr($query, 0, 2000)."\n", FILE_APPEND);
212 public function q($sql, $onlyquery = false) {
215 if (!$this->db || !$this->connected) {
221 // Check the connection (This can reconnect the connection - if configured)
222 switch ($this->driver) {
224 // Not sure if this really is working like expected
225 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
228 $connected = $this->db->ping();
231 $connected = mysql_ping($this->db);
235 $connstr = ($connected ? "Connected" : "Disonnected");
237 $stamp1 = microtime(true);
241 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
242 $sql = "/*".$a->callstack()." */ ".$sql;
245 switch ($this->driver) {
247 $result = @$this->db->query($sql);
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 (($result === true) || ($result === false)) {
346 $this->result = $result;
351 switch ($this->driver) {
353 if ($result->rowCount()) {
354 while($x = $result->fetch(PDO::FETCH_ASSOC))
356 $result->closeCursor();
360 if ($result->num_rows) {
361 while($x = $result->fetch_array(MYSQLI_ASSOC))
363 $result->free_result();
367 if (mysql_num_rows($result)) {
368 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
370 mysql_free_result($result);
375 if (($this->driver == 'pdo') AND (strtolower(substr($orig_sql, 0, 6)) != "select") AND (count($r) == 0)) {
376 // mysqli separates the return value between "select" and "update" - pdo doesn't
380 //$a->save_timestamp($stamp1, "database");
383 logger('dba: ' . printable(print_r($r, true)));
388 public function qfetch() {
392 switch ($this->driver) {
394 if ($this->result->rowCount()) {
395 $x = $this->result->fetch(PDO::FETCH_ASSOC);
399 if ($this->result->num_rows) {
400 $x = $this->result->fetch_array(MYSQLI_ASSOC);
404 if (mysql_num_rows($this->result)) {
405 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
413 public function qclose() {
415 switch ($this->driver) {
417 $this->result->closeCursor();
420 $this->result->free_result();
423 mysql_free_result($this->result);
429 public function dbg($dbg) {
433 public function escape($str) {
434 if ($this->db && $this->connected) {
435 switch ($this->driver) {
437 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
439 return @$this->db->real_escape_string($str);
441 return @mysql_real_escape_string($str,$this->db);
446 function connected() {
447 switch ($this->driver) {
449 // Not sure if this really is working like expected
450 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
453 $connected = $this->db->ping();
456 $connected = mysql_ping($this->db);
462 function insert_id() {
463 switch ($this->driver) {
465 $id = $this->db->lastInsertId();
468 $id = $this->db->insert_id;
471 $id = mysql_insert_id($this->db);
477 function __destruct() {
479 switch ($this->driver) {
487 mysql_close($this->db);
494 function printable($s) {
495 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
496 $s = str_replace("\x00",'.',$s);
497 if (x($_SERVER,'SERVER_NAME')) {
498 $s = escape_tags($s);
503 // Procedural functions
504 function dbg($state) {
512 function dbesc($str) {
515 if ($db && $db->connected) {
516 return($db->escape($str));
518 return(str_replace("'","\\'",$str));
522 // Function: q($sql,$args);
523 // Description: execute SQL query with printf style args.
524 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
528 $args = func_get_args();
531 if ($db && $db->connected) {
532 $stmt = @vsprintf($sql,$args); // Disabled warnings
533 //logger("dba: q: $stmt", LOGGER_ALL);
535 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
537 $db->log_index($stmt);
539 return $db->q($stmt);
544 * This will happen occasionally trying to store the
545 * session data after abnormal program termination
548 logger('dba: no database: ' . print_r($args,true));
553 * @brief Performs a query with "dirty reads"
555 * By doing dirty reads (reading uncommitted data) no locks are performed
556 * This function can be used to fetch data that doesn't need to be reliable.
558 * @param $args Query parameters (1 to N parameters of different types)
559 * @return array Query array
564 $args = func_get_args();
567 if ($db && $db->connected) {
568 $stmt = @vsprintf($sql,$args); // Disabled warnings
570 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
572 $db->log_index($stmt);
574 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
575 $retval = $db->q($stmt);
576 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
582 * This will happen occasionally trying to store the
583 * session data after abnormal program termination
586 logger('dba: no database: ' . print_r($args,true));
592 * Raw db query, no arguments
598 if ($db && $db->connected) {
606 // Caller is responsible for ensuring that any integer arguments to
607 // dbesc_array are actually integers and not malformed strings containing
608 // SQL injection vectors. All integer array elements should be specifically
609 // cast to int to avoid trouble.
610 function dbesc_array_cb(&$item, $key) {
611 if (is_string($item))
612 $item = dbesc($item);
615 function dbesc_array(&$arr) {
616 if (is_array($arr) && count($arr)) {
617 array_walk($arr,'dbesc_array_cb');
621 function dba_timer() {
622 return microtime(true);