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 if (!is_bool($result)) {
238 $columns = $result->columnCount();
242 $result = @$this->db->query($sql);
245 $result = @mysql_query($sql,$this->db);
248 $stamp2 = microtime(true);
249 $duration = (float)($stamp2-$stamp1);
251 $a->save_timestamp($stamp1, "database");
253 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
254 $a->save_timestamp($stamp1, "database_write");
256 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
257 if (($duration > $a->config["system"]["db_loglimit"])) {
258 $duration = round($duration, 3);
259 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
260 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
261 basename($backtrace[1]["file"])."\t".
262 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
263 substr($sql, 0, 2000)."\n", FILE_APPEND);
267 switch ($this->driver) {
269 $errorInfo = $this->db->errorInfo();
271 $this->error = $errorInfo[2];
272 $this->errorno = $errorInfo[1];
276 if ($this->db->errno) {
277 $this->error = $this->db->error;
278 $this->errorno = $this->db->errno;
282 if (mysql_errno($this->db)) {
283 $this->error = mysql_error($this->db);
284 $this->errorno = mysql_errno($this->db);
288 if (strlen($this->error)) {
289 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
296 if ($result === false) {
298 } elseif ($result === true) {
301 switch ($this->driver) {
303 $mesg = $result->rowCount().' results'.EOL;
306 $mesg = $result->num_rows.' results'.EOL;
309 $mesg = mysql_num_rows($result).' results'.EOL;
314 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
315 . (($this->error) ? ' error: ' . $this->error : '')
318 logger('dba: ' . $str );
322 * If dbfail.out exists, we will write any failed calls directly to it,
323 * regardless of any logging that may or may nor be in effect.
324 * These usually indicate SQL syntax errors that need to be resolved.
327 if ($result === false) {
328 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
329 if (file_exists('dbfail.out')) {
330 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
334 if (is_bool($result)) {
338 $this->result = $result;
343 switch ($this->driver) {
345 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
348 $result->closeCursor();
351 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
354 $result->free_result();
357 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
360 mysql_free_result($result);
364 // PDO doesn't return "true" on successful operations - like mysqli does
365 // Emulate this behaviour by checking if the query returned data and had columns
366 // This should be reliable enough
367 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
371 //$a->save_timestamp($stamp1, "database");
374 logger('dba: ' . printable(print_r($r, true)));
379 public function qfetch() {
383 switch ($this->driver) {
385 $x = $this->result->fetch(PDO::FETCH_ASSOC);
388 $x = $this->result->fetch_array(MYSQLI_ASSOC);
391 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
398 public function qclose() {
400 switch ($this->driver) {
402 $this->result->closeCursor();
405 $this->result->free_result();
408 mysql_free_result($this->result);
414 public function dbg($dbg) {
418 public function escape($str) {
419 if ($this->db && $this->connected) {
420 switch ($this->driver) {
422 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
424 return @$this->db->real_escape_string($str);
426 return @mysql_real_escape_string($str,$this->db);
431 function connected() {
432 switch ($this->driver) {
434 // Not sure if this really is working like expected
435 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
438 $connected = $this->db->ping();
441 $connected = mysql_ping($this->db);
447 function insert_id() {
448 switch ($this->driver) {
450 $id = $this->db->lastInsertId();
453 $id = $this->db->insert_id;
456 $id = mysql_insert_id($this->db);
462 function __destruct() {
464 switch ($this->driver) {
472 mysql_close($this->db);
479 function printable($s) {
480 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
481 $s = str_replace("\x00",'.',$s);
482 if (x($_SERVER,'SERVER_NAME')) {
483 $s = escape_tags($s);
488 // Procedural functions
489 function dbg($state) {
497 function dbesc($str) {
500 if ($db && $db->connected) {
501 return($db->escape($str));
503 return(str_replace("'","\\'",$str));
507 // Function: q($sql,$args);
508 // Description: execute SQL query with printf style args.
509 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
513 $args = func_get_args();
516 if ($db && $db->connected) {
517 $stmt = @vsprintf($sql,$args); // Disabled warnings
518 //logger("dba: q: $stmt", LOGGER_ALL);
520 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
522 $db->log_index($stmt);
524 return $db->q($stmt);
529 * This will happen occasionally trying to store the
530 * session data after abnormal program termination
533 logger('dba: no database: ' . print_r($args,true));
538 * @brief Performs a query with "dirty reads"
540 * By doing dirty reads (reading uncommitted data) no locks are performed
541 * This function can be used to fetch data that doesn't need to be reliable.
543 * @param $args Query parameters (1 to N parameters of different types)
544 * @return array Query array
549 $args = func_get_args();
552 if ($db && $db->connected) {
553 $stmt = @vsprintf($sql,$args); // Disabled warnings
555 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
557 $db->log_index($stmt);
559 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
560 $retval = $db->q($stmt);
561 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
567 * This will happen occasionally trying to store the
568 * session data after abnormal program termination
571 logger('dba: no database: ' . print_r($args,true));
577 * Raw db query, no arguments
583 if ($db && $db->connected) {
591 // Caller is responsible for ensuring that any integer arguments to
592 // dbesc_array are actually integers and not malformed strings containing
593 // SQL injection vectors. All integer array elements should be specifically
594 // cast to int to avoid trouble.
595 function dbesc_array_cb(&$item, $key) {
596 if (is_string($item))
597 $item = dbesc($item);
600 function dbesc_array(&$arr) {
601 if (is_array($arr) && count($arr)) {
602 array_walk($arr,'dbesc_array_cb');
606 function dba_timer() {
607 return microtime(true);