3 if(class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
4 require_once("library/dddbl2/dddbl.php");
5 require_once("include/dba_pdo.php");
8 require_once('include/datetime.php');
12 * MySQL database class
14 * For debugging, insert 'dbg(1);' anywhere in the program flow.
15 * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
16 * When logging, all binary info is converted to text and html entities are escaped so that
17 * the debugging stream is safe to view within both terminals and web pages.
21 if(! class_exists('dba')) {
27 public $mysqli = true;
28 public $connected = false;
29 public $error = false;
31 function __construct($server,$user,$pass,$db,$install = false) {
34 $stamp1 = microtime(true);
36 $server = trim($server);
41 if (!(strlen($server) && strlen($user))){
42 $this->connected = false;
48 if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
49 if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
50 $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
51 $this->connected = false;
58 if(class_exists('mysqli')) {
59 $this->db = @new mysqli($server,$user,$pass,$db);
60 if(! mysqli_connect_errno()) {
61 $this->connected = true;
65 $this->mysqli = false;
66 $this->db = mysql_connect($server,$user,$pass);
67 if($this->db && mysql_select_db($db,$this->db)) {
68 $this->connected = true;
71 if(! $this->connected) {
77 $a->save_timestamp($stamp1, "network");
80 public function getdb() {
84 public function q($sql, $onlyquery = false) {
87 if((! $this->db) || (! $this->connected))
92 $stamp1 = microtime(true);
95 $result = @$this->db->query($sql);
97 $result = @mysql_query($sql,$this->db);
99 $stamp2 = microtime(true);
100 $duration = (float)($stamp2-$stamp1);
102 $a->save_timestamp($stamp1, "database");
104 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
105 if (($duration > $a->config["system"]["db_loglimit"])) {
106 $duration = round($duration, 3);
107 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
108 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
109 basename($backtrace[1]["file"])."\t".
110 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
111 substr($sql, 0, 2000)."\n", FILE_APPEND);
117 $this->error = $this->db->error;
119 elseif(mysql_errno($this->db))
120 $this->error = mysql_error($this->db);
122 if(strlen($this->error)) {
123 logger('dba: ' . $this->error);
130 if($result === false)
132 elseif($result === true)
136 $mesg = $result->num_rows . ' results' . EOL;
138 $mesg = mysql_num_rows($result) . ' results' . EOL;
141 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
142 . (($this->error) ? ' error: ' . $this->error : '')
145 logger('dba: ' . $str );
149 * If dbfail.out exists, we will write any failed calls directly to it,
150 * regardless of any logging that may or may nor be in effect.
151 * These usually indicate SQL syntax errors that need to be resolved.
154 if($result === false) {
155 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
156 if(file_exists('dbfail.out'))
157 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
160 if(($result === true) || ($result === false))
164 $this->result = $result;
170 if($result->num_rows) {
171 while($x = $result->fetch_array(MYSQLI_ASSOC))
173 $result->free_result();
177 if(mysql_num_rows($result)) {
178 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
180 mysql_free_result($result);
184 //$a->save_timestamp($stamp1, "database");
187 logger('dba: ' . printable(print_r($r, true)));
191 public function qfetch() {
196 if($this->result->num_rows)
197 $x = $this->result->fetch_array(MYSQLI_ASSOC);
199 if(mysql_num_rows($this->result))
200 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
206 public function qclose() {
209 $this->result->free_result();
211 mysql_free_result($this->result);
215 public function dbg($dbg) {
219 public function escape($str) {
220 if($this->db && $this->connected) {
222 return @$this->db->real_escape_string($str);
224 return @mysql_real_escape_string($str,$this->db);
228 function __destruct() {
233 mysql_close($this->db);
237 if(! function_exists('printable')) {
238 function printable($s) {
239 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
240 $s = str_replace("\x00",'.',$s);
241 if(x($_SERVER,'SERVER_NAME'))
242 $s = escape_tags($s);
246 // Procedural functions
247 if(! function_exists('dbg')) {
248 function dbg($state) {
254 if(! function_exists('dbesc')) {
255 function dbesc($str) {
257 if($db && $db->connected)
258 return($db->escape($str));
260 return(str_replace("'","\\'",$str));
265 // Function: q($sql,$args);
266 // Description: execute SQL query with printf style args.
267 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
270 if(! function_exists('q')) {
274 $args = func_get_args();
277 if($db && $db->connected) {
278 $stmt = @vsprintf($sql,$args); // Disabled warnings
279 //logger("dba: q: $stmt", LOGGER_ALL);
281 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
282 return $db->q($stmt);
287 * This will happen occasionally trying to store the
288 * session data after abnormal program termination
291 logger('dba: no database: ' . print_r($args,true));
298 * Raw db query, no arguments
302 if(! function_exists('dbq')) {
306 if($db && $db->connected)
314 // Caller is responsible for ensuring that any integer arguments to
315 // dbesc_array are actually integers and not malformed strings containing
316 // SQL injection vectors. All integer array elements should be specifically
317 // cast to int to avoid trouble.
320 if(! function_exists('dbesc_array_cb')) {
321 function dbesc_array_cb(&$item, $key) {
323 $item = dbesc($item);
327 if(! function_exists('dbesc_array')) {
328 function dbesc_array(&$arr) {
329 if(is_array($arr) && count($arr)) {
330 array_walk($arr,'dbesc_array_cb');
335 function dba_timer() {
336 return microtime(true);