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 $connstr = ($this->connected() ? "Connected" : "Disonnected");
223 $stamp1 = microtime(true);
227 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
228 $sql = "/*".$a->callstack()." */ ".$sql;
233 switch ($this->driver) {
235 $result = @$this->db->query($sql);
236 // Is used to separate between queries that returning data - or not
237 $columns = $result->columnCount();
240 $result = @$this->db->query($sql);
243 $result = @mysql_query($sql,$this->db);
246 $stamp2 = microtime(true);
247 $duration = (float)($stamp2-$stamp1);
249 $a->save_timestamp($stamp1, "database");
251 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
252 $a->save_timestamp($stamp1, "database_write");
254 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
255 if (($duration > $a->config["system"]["db_loglimit"])) {
256 $duration = round($duration, 3);
257 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
258 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
259 basename($backtrace[1]["file"])."\t".
260 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
261 substr($sql, 0, 2000)."\n", FILE_APPEND);
265 switch ($this->driver) {
267 $errorInfo = $this->db->errorInfo();
269 $this->error = $errorInfo[2];
270 $this->errorno = $errorInfo[1];
274 if ($this->db->errno) {
275 $this->error = $this->db->error;
276 $this->errorno = $this->db->errno;
280 if (mysql_errno($this->db)) {
281 $this->error = mysql_error($this->db);
282 $this->errorno = mysql_errno($this->db);
286 if (strlen($this->error)) {
287 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
294 if ($result === false) {
296 } elseif ($result === true) {
299 switch ($this->driver) {
301 $mesg = $result->rowCount().' results'.EOL;
304 $mesg = $result->num_rows.' results'.EOL;
307 $mesg = mysql_num_rows($result).' results'.EOL;
312 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
313 . (($this->error) ? ' error: ' . $this->error : '')
316 logger('dba: ' . $str );
320 * If dbfail.out exists, we will write any failed calls directly to it,
321 * regardless of any logging that may or may nor be in effect.
322 * These usually indicate SQL syntax errors that need to be resolved.
325 if ($result === false) {
326 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
327 if (file_exists('dbfail.out')) {
328 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
332 if (($result === true) || ($result === false)) {
336 $this->result = $result;
341 switch ($this->driver) {
343 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
346 $result->closeCursor();
349 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
352 $result->free_result();
355 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
358 mysql_free_result($result);
362 // PDO doesn't return "true" on successful operations - like mysqli does
363 // Emulate this behaviour by checking if the query returned data and had columns
364 // This should be reliable enough
365 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
369 //$a->save_timestamp($stamp1, "database");
372 logger('dba: ' . printable(print_r($r, true)));
377 public function qfetch() {
381 switch ($this->driver) {
383 $x = $this->result->fetch(PDO::FETCH_ASSOC);
386 $x = $this->result->fetch_array(MYSQLI_ASSOC);
389 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
396 public function qclose() {
398 switch ($this->driver) {
400 $this->result->closeCursor();
403 $this->result->free_result();
406 mysql_free_result($this->result);
412 public function dbg($dbg) {
416 public function escape($str) {
417 if ($this->db && $this->connected) {
418 switch ($this->driver) {
420 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
422 return @$this->db->real_escape_string($str);
424 return @mysql_real_escape_string($str,$this->db);
429 function connected() {
430 switch ($this->driver) {
432 // Not sure if this really is working like expected
433 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
436 $connected = $this->db->ping();
439 $connected = mysql_ping($this->db);
445 function insert_id() {
446 switch ($this->driver) {
448 $id = $this->db->lastInsertId();
451 $id = $this->db->insert_id;
454 $id = mysql_insert_id($this->db);
460 function __destruct() {
462 switch ($this->driver) {
470 mysql_close($this->db);
477 function printable($s) {
478 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
479 $s = str_replace("\x00",'.',$s);
480 if (x($_SERVER,'SERVER_NAME')) {
481 $s = escape_tags($s);
486 // Procedural functions
487 function dbg($state) {
495 function dbesc($str) {
498 if ($db && $db->connected) {
499 return($db->escape($str));
501 return(str_replace("'","\\'",$str));
505 // Function: q($sql,$args);
506 // Description: execute SQL query with printf style args.
507 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
511 $args = func_get_args();
514 if ($db && $db->connected) {
515 $stmt = @vsprintf($sql,$args); // Disabled warnings
516 //logger("dba: q: $stmt", LOGGER_ALL);
518 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
520 $db->log_index($stmt);
522 return $db->q($stmt);
527 * This will happen occasionally trying to store the
528 * session data after abnormal program termination
531 logger('dba: no database: ' . print_r($args,true));
536 * @brief Performs a query with "dirty reads"
538 * By doing dirty reads (reading uncommitted data) no locks are performed
539 * This function can be used to fetch data that doesn't need to be reliable.
541 * @param $args Query parameters (1 to N parameters of different types)
542 * @return array Query array
547 $args = func_get_args();
550 if ($db && $db->connected) {
551 $stmt = @vsprintf($sql,$args); // Disabled warnings
553 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
555 $db->log_index($stmt);
557 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
558 $retval = $db->q($stmt);
559 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
565 * This will happen occasionally trying to store the
566 * session data after abnormal program termination
569 logger('dba: no database: ' . print_r($args,true));
575 * Raw db query, no arguments
581 if ($db && $db->connected) {
589 // Caller is responsible for ensuring that any integer arguments to
590 // dbesc_array are actually integers and not malformed strings containing
591 // SQL injection vectors. All integer array elements should be specifically
592 // cast to int to avoid trouble.
593 function dbesc_array_cb(&$item, $key) {
594 if (is_string($item))
595 $item = dbesc($item);
598 function dbesc_array(&$arr) {
599 if (is_array($arr) && count($arr)) {
600 array_walk($arr,'dbesc_array_cb');
604 function dba_timer() {
605 return microtime(true);