2 require_once("dbm.php");
4 # if PDO is avaible for mysql, use the new database abstraction
5 # TODO: PDO is disabled for release 3.3. We need to investigate why
6 # the update from 3.2 fails with pdo
8 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
9 require_once("library/dddbl2/dddbl.php");
10 require_once("include/dba_pdo.php");
15 require_once('include/datetime.php');
18 * @class MySQL database class
20 * For debugging, insert 'dbg(1);' anywhere in the program flow.
21 * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
22 * When logging, all binary info is converted to text and html entities are escaped so that
23 * the debugging stream is safe to view within both terminals and web pages.
27 if (! class_exists('dba')) {
33 public $mysqli = true;
34 public $connected = false;
35 public $error = false;
37 function __construct($server, $user, $pass, $db, $install = false) {
40 $stamp1 = microtime(true);
42 $server = trim($server);
47 if (!(strlen($server) && strlen($user))) {
48 $this->connected = false;
54 if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
55 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
56 $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
57 $this->connected = false;
64 if (class_exists('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 $this->mysqli = false;
74 $this->db = mysql_connect($server,$user,$pass);
75 if ($this->db && mysql_select_db($db,$this->db)) {
76 $this->connected = true;
78 if (isset($a->config["system"]["db_charset"]))
79 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
81 if (!$this->connected) {
88 $a->save_timestamp($stamp1, "network");
91 public function getdb() {
96 * @brief Returns the MySQL server version string
98 * This function discriminate between the deprecated mysql API and the current
99 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
103 public function server_info() {
105 $return = $this->db->server_info;
107 $return = mysql_get_server_info($this->db);
113 * @brief Returns the selected database name
117 public function database_name() {
118 $r = $this->q("SELECT DATABASE() AS `db`");
124 * @brief Returns the number of rows
128 public function num_rows() {
129 if (!$this->result) {
134 $return = $this->result->num_rows;
136 $return = mysql_num_rows($this->result);
142 * @brief Analyze a database query and log this if some conditions are met.
144 * @param string $query The database query that will be analyzed
146 public function log_index($query) {
149 if ($a->config["system"]["db_log_index"] == "") {
153 // Don't explain an explain statement
154 if (strtolower(substr($query, 0, 7)) == "explain") {
158 // Only do the explain on "select", "update" and "delete"
159 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
163 $r = $this->q("EXPLAIN ".$query);
164 if (!dbm::is_result($r)) {
168 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
169 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
171 foreach ($r AS $row) {
172 if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
173 $log = (in_array($row['key'], $watchlist) AND
174 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
178 if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
182 if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
187 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
188 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
189 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
190 basename($backtrace[1]["file"])."\t".
191 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
192 substr($query, 0, 2000)."\n", FILE_APPEND);
197 public function q($sql, $onlyquery = false) {
200 if (!$this->db || !$this->connected) {
206 // Check the connection (This can reconnect the connection - if configured)
208 $connected = $this->db->ping();
210 $connected = mysql_ping($this->db);
212 $connstr = ($connected ? "Connected" : "Disonnected");
214 $stamp1 = microtime(true);
218 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
219 $sql = "/*".$a->callstack()." */ ".$sql;
223 $result = @$this->db->query($sql);
225 $result = @mysql_query($sql,$this->db);
227 $stamp2 = microtime(true);
228 $duration = (float)($stamp2-$stamp1);
230 $a->save_timestamp($stamp1, "database");
232 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
233 $a->save_timestamp($stamp1, "database_write");
235 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
236 if (($duration > $a->config["system"]["db_loglimit"])) {
237 $duration = round($duration, 3);
238 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
239 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
240 basename($backtrace[1]["file"])."\t".
241 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
242 substr($sql, 0, 2000)."\n", FILE_APPEND);
247 if ($this->db->errno) {
248 $this->error = $this->db->error;
249 $this->errorno = $this->db->errno;
251 } elseif (mysql_errno($this->db)) {
252 $this->error = mysql_error($this->db);
253 $this->errorno = mysql_errno($this->db);
256 if (strlen($this->error)) {
257 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
264 if ($result === false) {
266 } elseif ($result === true) {
270 $mesg = $result->num_rows . ' results' . EOL;
272 $mesg = mysql_num_rows($result) . ' results' . EOL;
276 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
277 . (($this->error) ? ' error: ' . $this->error : '')
280 logger('dba: ' . $str );
284 * If dbfail.out exists, we will write any failed calls directly to it,
285 * regardless of any logging that may or may nor be in effect.
286 * These usually indicate SQL syntax errors that need to be resolved.
289 if ($result === false) {
290 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
291 if (file_exists('dbfail.out')) {
292 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
296 if (($result === true) || ($result === false)) {
300 $this->result = $result;
306 if ($result->num_rows) {
307 while($x = $result->fetch_array(MYSQLI_ASSOC))
309 $result->free_result();
312 if (mysql_num_rows($result)) {
313 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
315 mysql_free_result($result);
319 //$a->save_timestamp($stamp1, "database");
322 logger('dba: ' . printable(print_r($r, true)));
327 public function qfetch() {
332 if ($this->result->num_rows)
333 $x = $this->result->fetch_array(MYSQLI_ASSOC);
335 if (mysql_num_rows($this->result))
336 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
342 public function qclose() {
345 $this->result->free_result();
347 mysql_free_result($this->result);
352 public function dbg($dbg) {
356 public function escape($str) {
357 if ($this->db && $this->connected) {
359 return @$this->db->real_escape_string($str);
361 return @mysql_real_escape_string($str,$this->db);
366 function connected() {
368 $connected = $this->db->ping();
370 $connected = mysql_ping($this->db);
375 function __destruct() {
380 mysql_close($this->db);
386 if (! function_exists('printable')) {
387 function printable($s) {
388 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
389 $s = str_replace("\x00",'.',$s);
390 if (x($_SERVER,'SERVER_NAME')) {
391 $s = escape_tags($s);
396 // Procedural functions
397 if (! function_exists('dbg')) {
398 function dbg($state) {
405 if (! function_exists('dbesc')) {
406 function dbesc($str) {
408 if ($db && $db->connected) {
409 return($db->escape($str));
411 return(str_replace("'","\\'",$str));
417 // Function: q($sql,$args);
418 // Description: execute SQL query with printf style args.
419 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
422 if (! function_exists('q')) {
426 $args = func_get_args();
429 if ($db && $db->connected) {
430 $stmt = @vsprintf($sql,$args); // Disabled warnings
431 //logger("dba: q: $stmt", LOGGER_ALL);
433 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
435 $db->log_index($stmt);
437 return $db->q($stmt);
442 * This will happen occasionally trying to store the
443 * session data after abnormal program termination
446 logger('dba: no database: ' . print_r($args,true));
452 * @brief Performs a query with "dirty reads"
454 * By doing dirty reads (reading uncommitted data) no locks are performed
455 * This function can be used to fetch data that doesn't need to be reliable.
457 * @param $args Query parameters (1 to N parameters of different types)
458 * @return array Query array
463 $args = func_get_args();
466 if ($db && $db->connected) {
467 $stmt = @vsprintf($sql,$args); // Disabled warnings
469 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
471 $db->log_index($stmt);
473 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
474 $retval = $db->q($stmt);
475 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
481 * This will happen occasionally trying to store the
482 * session data after abnormal program termination
485 logger('dba: no database: ' . print_r($args,true));
492 * Raw db query, no arguments
496 if (! function_exists('dbq')) {
500 if ($db && $db->connected) {
509 // Caller is responsible for ensuring that any integer arguments to
510 // dbesc_array are actually integers and not malformed strings containing
511 // SQL injection vectors. All integer array elements should be specifically
512 // cast to int to avoid trouble.
515 if (! function_exists('dbesc_array_cb')) {
516 function dbesc_array_cb(&$item, $key) {
517 if (is_string($item))
518 $item = dbesc($item);
522 if (! function_exists('dbesc_array')) {
523 function dbesc_array(&$arr) {
524 if (is_array($arr) && count($arr)) {
525 array_walk($arr,'dbesc_array_cb');
530 function dba_timer() {
531 return microtime(true);