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"]);
70 } elseif (function_exists('mysql_connect')) {
71 $this->driver = 'mysql';
72 $this->db = mysql_connect($server,$user,$pass);
73 if ($this->db && mysql_select_db($db,$this->db)) {
74 $this->connected = true;
76 if (isset($a->config["system"]["db_charset"]))
77 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
79 // No suitable SQL driver was found.
85 if (!$this->connected) {
91 $a->save_timestamp($stamp1, "network");
95 * @brief Returns the MySQL server version string
97 * This function discriminate between the deprecated mysql API and the current
98 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
102 public function server_info() {
103 switch ($this->driver) {
105 $version = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
108 $version = $this->db->server_info;
111 $version = mysql_get_server_info($this->db);
118 * @brief Returns the selected database name
122 public function database_name() {
123 $r = $this->q("SELECT DATABASE() AS `db`");
129 * @brief Returns the number of rows
133 public function num_rows() {
134 if (!$this->result) {
138 switch ($this->driver) {
140 $rows = $this->result->rowCount();
143 $rows = $this->result->num_rows;
146 $rows = mysql_num_rows($this->result);
153 * @brief Analyze a database query and log this if some conditions are met.
155 * @param string $query The database query that will be analyzed
157 public function log_index($query) {
160 if ($a->config["system"]["db_log_index"] == "") {
164 // Don't explain an explain statement
165 if (strtolower(substr($query, 0, 7)) == "explain") {
169 // Only do the explain on "select", "update" and "delete"
170 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
174 $r = $this->q("EXPLAIN ".$query);
175 if (!dbm::is_result($r)) {
179 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
180 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
182 foreach ($r AS $row) {
183 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
184 $log = (in_array($row['key'], $watchlist) AND
185 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
190 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
194 if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
199 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
200 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
201 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
202 basename($backtrace[1]["file"])."\t".
203 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
204 substr($query, 0, 2000)."\n", FILE_APPEND);
209 public function q($sql, $onlyquery = false) {
212 if (!$this->db || !$this->connected) {
218 // Check the connection (This can reconnect the connection - if configured)
219 switch ($this->driver) {
221 // Not sure if this really is working like expected
222 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
225 $connected = $this->db->ping();
228 $connected = mysql_ping($this->db);
232 $connstr = ($connected ? "Connected" : "Disonnected");
234 $stamp1 = microtime(true);
238 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
239 $sql = "/*".$a->callstack()." */ ".$sql;
242 switch ($this->driver) {
244 $result = @$this->db->query($sql);
247 $result = @$this->db->query($sql);
250 $result = @mysql_query($sql,$this->db);
253 $stamp2 = microtime(true);
254 $duration = (float)($stamp2-$stamp1);
256 $a->save_timestamp($stamp1, "database");
258 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
259 $a->save_timestamp($stamp1, "database_write");
261 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
262 if (($duration > $a->config["system"]["db_loglimit"])) {
263 $duration = round($duration, 3);
264 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
265 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
266 basename($backtrace[1]["file"])."\t".
267 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
268 substr($sql, 0, 2000)."\n", FILE_APPEND);
272 switch ($this->driver) {
274 $errorInfo = $this->db->errorInfo();
276 $this->error = $errorInfo[2];
277 $this->errorno = $errorInfo[1];
281 if ($this->db->errno) {
282 $this->error = $this->db->error;
283 $this->errorno = $this->db->errno;
287 if (mysql_errno($this->db)) {
288 $this->error = mysql_error($this->db);
289 $this->errorno = mysql_errno($this->db);
293 if (strlen($this->error)) {
294 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
301 if ($result === false) {
303 } elseif ($result === true) {
306 switch ($this->driver) {
308 $mesg = $result->rowCount().' results'.EOL;
311 $mesg = $result->num_rows.' results'.EOL;
314 $mesg = mysql_num_rows($result).' results'.EOL;
319 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
320 . (($this->error) ? ' error: ' . $this->error : '')
323 logger('dba: ' . $str );
327 * If dbfail.out exists, we will write any failed calls directly to it,
328 * regardless of any logging that may or may nor be in effect.
329 * These usually indicate SQL syntax errors that need to be resolved.
332 if ($result === false) {
333 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
334 if (file_exists('dbfail.out')) {
335 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
339 if (($result === true) || ($result === false)) {
343 $this->result = $result;
348 switch ($this->driver) {
350 if ($result->rowCount()) {
351 while($x = $result->fetch(PDO::FETCH_ASSOC))
353 $result->closeCursor();
357 if ($result->num_rows) {
358 while($x = $result->fetch_array(MYSQLI_ASSOC))
360 $result->free_result();
364 if (mysql_num_rows($result)) {
365 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
367 mysql_free_result($result);
372 //$a->save_timestamp($stamp1, "database");
375 logger('dba: ' . printable(print_r($r, true)));
380 public function qfetch() {
384 switch ($this->driver) {
386 if ($this->result->rowCount()) {
387 $x = $this->result->fetch(PDO::FETCH_ASSOC);
391 if ($this->result->num_rows) {
392 $x = $this->result->fetch_array(MYSQLI_ASSOC);
396 if (mysql_num_rows($this->result)) {
397 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
405 public function qclose() {
407 switch ($this->driver) {
409 $this->result->closeCursor();
412 $this->result->free_result();
415 mysql_free_result($this->result);
421 public function dbg($dbg) {
425 public function escape($str) {
426 if ($this->db && $this->connected) {
427 switch ($this->driver) {
429 return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
431 return @$this->db->real_escape_string($str);
433 return @mysql_real_escape_string($str,$this->db);
438 function connected() {
439 switch ($this->driver) {
441 // Not sure if this really is working like expected
442 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
445 $connected = $this->db->ping();
448 $connected = mysql_ping($this->db);
454 function insert_id() {
455 switch ($this->driver) {
457 $id = $this->db->lastInsertId();
460 $id = $this->db->insert_id;
463 $id = mysql_insert_id($this->db);
469 function __destruct() {
471 switch ($this->driver) {
479 mysql_close($this->db);
486 function printable($s) {
487 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
488 $s = str_replace("\x00",'.',$s);
489 if (x($_SERVER,'SERVER_NAME')) {
490 $s = escape_tags($s);
495 // Procedural functions
496 function dbg($state) {
504 function dbesc($str) {
507 if ($db && $db->connected) {
508 return($db->escape($str));
510 return(str_replace("'","\\'",$str));
514 // Function: q($sql,$args);
515 // Description: execute SQL query with printf style args.
516 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
520 $args = func_get_args();
523 if ($db && $db->connected) {
524 $stmt = @vsprintf($sql,$args); // Disabled warnings
525 //logger("dba: q: $stmt", LOGGER_ALL);
527 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
529 $db->log_index($stmt);
531 return $db->q($stmt);
536 * This will happen occasionally trying to store the
537 * session data after abnormal program termination
540 logger('dba: no database: ' . print_r($args,true));
545 * @brief Performs a query with "dirty reads"
547 * By doing dirty reads (reading uncommitted data) no locks are performed
548 * This function can be used to fetch data that doesn't need to be reliable.
550 * @param $args Query parameters (1 to N parameters of different types)
551 * @return array Query array
556 $args = func_get_args();
559 if ($db && $db->connected) {
560 $stmt = @vsprintf($sql,$args); // Disabled warnings
562 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
564 $db->log_index($stmt);
566 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
567 $retval = $db->q($stmt);
568 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
574 * This will happen occasionally trying to store the
575 * session data after abnormal program termination
578 logger('dba: no database: ' . print_r($args,true));
584 * Raw db query, no arguments
590 if ($db && $db->connected) {
598 // Caller is responsible for ensuring that any integer arguments to
599 // dbesc_array are actually integers and not malformed strings containing
600 // SQL injection vectors. All integer array elements should be specifically
601 // cast to int to avoid trouble.
602 function dbesc_array_cb(&$item, $key) {
603 if (is_string($item))
604 $item = dbesc($item);
607 function dbesc_array(&$arr) {
608 if (is_array($arr) && count($arr)) {
609 array_walk($arr,'dbesc_array_cb');
613 function dba_timer() {
614 return microtime(true);