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);
141 public function log_index($query) {
144 if (($a->config["system"]["db_log_index"] == "") OR ($a->config["system"]["db_log_index_watch"] == "") OR
145 (intval($a->config["system"]["db_loglimit_index"]) == 0)) {
149 if (strtolower(substr($query, 0, 7)) == "explain") {
153 $r = $this->q("EXPLAIN ".$query);
154 if (!dbm::is_result($r)) {
158 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
160 foreach ($r AS $row) {
161 if (in_array($row['key'], $watchlist) AND
162 ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"]))) {
163 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
164 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
165 $row['key']."\t".$row['rows']."\t".
166 basename($backtrace[1]["file"])."\t".
167 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
168 substr($query, 0, 2000)."\n", FILE_APPEND);
173 public function q($sql, $onlyquery = false) {
176 if (!$this->db || !$this->connected) {
182 // Check the connection (This can reconnect the connection - if configured)
184 $connected = $this->db->ping();
186 $connected = mysql_ping($this->db);
188 $connstr = ($connected ? "Connected" : "Disonnected");
190 $stamp1 = microtime(true);
194 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
195 $sql = "/*".$a->callstack()." */ ".$sql;
199 $result = @$this->db->query($sql);
201 $result = @mysql_query($sql,$this->db);
203 $stamp2 = microtime(true);
204 $duration = (float)($stamp2-$stamp1);
206 $a->save_timestamp($stamp1, "database");
208 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
209 $a->save_timestamp($stamp1, "database_write");
211 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
212 if (($duration > $a->config["system"]["db_loglimit"])) {
213 $duration = round($duration, 3);
214 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
215 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
216 basename($backtrace[1]["file"])."\t".
217 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
218 substr($sql, 0, 2000)."\n", FILE_APPEND);
223 if ($this->db->errno) {
224 $this->error = $this->db->error;
225 $this->errorno = $this->db->errno;
227 } elseif (mysql_errno($this->db)) {
228 $this->error = mysql_error($this->db);
229 $this->errorno = mysql_errno($this->db);
232 if (strlen($this->error)) {
233 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
240 if ($result === false) {
242 } elseif ($result === true) {
246 $mesg = $result->num_rows . ' results' . EOL;
248 $mesg = mysql_num_rows($result) . ' results' . EOL;
252 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
253 . (($this->error) ? ' error: ' . $this->error : '')
256 logger('dba: ' . $str );
260 * If dbfail.out exists, we will write any failed calls directly to it,
261 * regardless of any logging that may or may nor be in effect.
262 * These usually indicate SQL syntax errors that need to be resolved.
265 if ($result === false) {
266 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
267 if (file_exists('dbfail.out')) {
268 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
272 if (($result === true) || ($result === false)) {
276 $this->result = $result;
282 if ($result->num_rows) {
283 while($x = $result->fetch_array(MYSQLI_ASSOC))
285 $result->free_result();
288 if (mysql_num_rows($result)) {
289 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
291 mysql_free_result($result);
295 //$a->save_timestamp($stamp1, "database");
298 logger('dba: ' . printable(print_r($r, true)));
303 public function qfetch() {
308 if ($this->result->num_rows)
309 $x = $this->result->fetch_array(MYSQLI_ASSOC);
311 if (mysql_num_rows($this->result))
312 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
318 public function qclose() {
321 $this->result->free_result();
323 mysql_free_result($this->result);
328 public function dbg($dbg) {
332 public function escape($str) {
333 if ($this->db && $this->connected) {
335 return @$this->db->real_escape_string($str);
337 return @mysql_real_escape_string($str,$this->db);
342 function connected() {
344 $connected = $this->db->ping();
346 $connected = mysql_ping($this->db);
351 function __destruct() {
356 mysql_close($this->db);
362 if (! function_exists('printable')) {
363 function printable($s) {
364 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
365 $s = str_replace("\x00",'.',$s);
366 if (x($_SERVER,'SERVER_NAME')) {
367 $s = escape_tags($s);
372 // Procedural functions
373 if (! function_exists('dbg')) {
374 function dbg($state) {
381 if (! function_exists('dbesc')) {
382 function dbesc($str) {
384 if ($db && $db->connected) {
385 return($db->escape($str));
387 return(str_replace("'","\\'",$str));
393 // Function: q($sql,$args);
394 // Description: execute SQL query with printf style args.
395 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
398 if (! function_exists('q')) {
402 $args = func_get_args();
405 if ($db && $db->connected) {
406 $stmt = @vsprintf($sql,$args); // Disabled warnings
407 //logger("dba: q: $stmt", LOGGER_ALL);
409 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
411 $db->log_index($stmt);
413 return $db->q($stmt);
418 * This will happen occasionally trying to store the
419 * session data after abnormal program termination
422 logger('dba: no database: ' . print_r($args,true));
428 * @brief Performs a query with "dirty reads"
430 * By doing dirty reads (reading uncommitted data) no locks are performed
431 * This function can be used to fetch data that doesn't need to be reliable.
433 * @param $args Query parameters (1 to N parameters of different types)
434 * @return array Query array
439 $args = func_get_args();
442 if ($db && $db->connected) {
443 $stmt = @vsprintf($sql,$args); // Disabled warnings
445 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
447 $db->log_index($stmt);
449 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
450 $retval = $db->q($stmt);
451 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
457 * This will happen occasionally trying to store the
458 * session data after abnormal program termination
461 logger('dba: no database: ' . print_r($args,true));
468 * Raw db query, no arguments
472 if (! function_exists('dbq')) {
476 if ($db && $db->connected) {
485 // Caller is responsible for ensuring that any integer arguments to
486 // dbesc_array are actually integers and not malformed strings containing
487 // SQL injection vectors. All integer array elements should be specifically
488 // cast to int to avoid trouble.
491 if (! function_exists('dbesc_array_cb')) {
492 function dbesc_array_cb(&$item, $key) {
493 if (is_string($item))
494 $item = dbesc($item);
498 if (! function_exists('dbesc_array')) {
499 function dbesc_array(&$arr) {
500 if (is_array($arr) && count($arr)) {
501 array_walk($arr,'dbesc_array_cb');
506 function dba_timer() {
507 return microtime(true);