3 require_once('include/datetime.php');
9 * For debugging, insert 'dbg(1);' anywhere in the program flow.
10 * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
11 * When logging, all binary info is converted to text and html entities are escaped so that
12 * the debugging stream is safe to view within both terminals and web pages.
16 if(! class_exists('dba')) {
21 public $mysqli = true;
22 public $connected = false;
23 public $error = false;
25 function __construct($server,$user,$pass,$db,$install = false) {
28 $stamp1 = microtime(true);
30 $server = trim($server);
35 if (!(strlen($server) && strlen($user))){
36 $this->connected = false;
42 if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
43 if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
44 $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
45 $this->connected = false;
52 if(class_exists('mysqli')) {
53 $this->db = @new mysqli($server,$user,$pass,$db);
54 if(! mysqli_connect_errno()) {
55 $this->connected = true;
59 $this->mysqli = false;
60 $this->db = mysql_connect($server,$user,$pass);
61 if($this->db && mysql_select_db($db,$this->db)) {
62 $this->connected = true;
65 if(! $this->connected) {
71 $a->save_timestamp($stamp1, "network");
74 public function getdb() {
78 public function q($sql) {
81 if((! $this->db) || (! $this->connected))
86 $stamp1 = microtime(true);
89 $result = @$this->db->query($sql);
91 $result = @mysql_query($sql,$this->db);
93 $stamp2 = microtime(true);
94 $duration = (float)($stamp2-$stamp1);
96 $a->save_timestamp($stamp1, "database");
98 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
99 if (($duration > $a->config["system"]["db_loglimit"])) {
100 $duration = round($duration, 3);
101 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
102 @file_put_contents($a->config["system"]["db_log"], $duration."\t".
103 basename($backtrace[1]["file"])."\t".
104 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
105 substr($sql, 0, 2000)."\n", FILE_APPEND);
111 $this->error = $this->db->error;
113 elseif(mysql_errno($this->db))
114 $this->error = mysql_error($this->db);
116 if(strlen($this->error)) {
117 logger('dba: ' . $this->error);
124 if($result === false)
126 elseif($result === true)
130 $mesg = $result->num_rows . ' results' . EOL;
132 $mesg = mysql_num_rows($result) . ' results' . EOL;
135 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
136 . (($this->error) ? ' error: ' . $this->error : '')
139 logger('dba: ' . $str );
143 * If dbfail.out exists, we will write any failed calls directly to it,
144 * regardless of any logging that may or may nor be in effect.
145 * These usually indicate SQL syntax errors that need to be resolved.
148 if($result === false) {
149 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
150 if(file_exists('dbfail.out'))
151 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
154 if(($result === true) || ($result === false))
159 if($result->num_rows) {
160 while($x = $result->fetch_array(MYSQLI_ASSOC))
162 $result->free_result();
166 if(mysql_num_rows($result)) {
167 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
169 mysql_free_result($result);
173 //$a->save_timestamp($stamp1, "database");
176 logger('dba: ' . printable(print_r($r, true)));
180 public function dbg($dbg) {
184 public function escape($str) {
185 if($this->db && $this->connected) {
187 return @$this->db->real_escape_string($str);
189 return @mysql_real_escape_string($str,$this->db);
193 function __destruct() {
198 mysql_close($this->db);
202 if(! function_exists('printable')) {
203 function printable($s) {
204 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
205 $s = str_replace("\x00",'.',$s);
206 if(x($_SERVER,'SERVER_NAME'))
207 $s = escape_tags($s);
211 // Procedural functions
212 if(! function_exists('dbg')) {
213 function dbg($state) {
219 if(! function_exists('dbesc')) {
220 function dbesc($str) {
222 if($db && $db->connected)
223 return($db->escape($str));
225 return(str_replace("'","\\'",$str));
230 // Function: q($sql,$args);
231 // Description: execute SQL query with printf style args.
232 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
235 if(! function_exists('q')) {
239 $args = func_get_args();
242 if($db && $db->connected) {
243 $stmt = @vsprintf($sql,$args); // Disabled warnings
244 //logger("dba: q: $stmt", LOGGER_ALL);
246 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
247 return $db->q($stmt);
252 * This will happen occasionally trying to store the
253 * session data after abnormal program termination
256 logger('dba: no database: ' . print_r($args,true));
263 * Raw db query, no arguments
267 if(! function_exists('dbq')) {
271 if($db && $db->connected)
279 // Caller is responsible for ensuring that any integer arguments to
280 // dbesc_array are actually integers and not malformed strings containing
281 // SQL injection vectors. All integer array elements should be specifically
282 // cast to int to avoid trouble.
285 if(! function_exists('dbesc_array_cb')) {
286 function dbesc_array_cb(&$item, $key) {
288 $item = dbesc($item);
292 if(! function_exists('dbesc_array')) {
293 function dbesc_array(&$arr) {
294 if(is_array($arr) && count($arr)) {
295 array_walk($arr,'dbesc_array_cb');
300 function dba_timer() {
301 return microtime(true);