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 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
97 if (($duration > $a->config["system"]["db_loglimit"])) {
98 $duration = round($duration, 3);
99 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
100 @file_put_contents($a->config["system"]["db_log"], $duration."\t".
101 basename($backtrace[1]["file"])."\t".
102 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
103 substr($sql, 0, 2000)."\n", FILE_APPEND);
109 $this->error = $this->db->error;
111 elseif(mysql_errno($this->db))
112 $this->error = mysql_error($this->db);
114 if(strlen($this->error)) {
115 logger('dba: ' . $this->error);
122 if($result === false)
124 elseif($result === true)
128 $mesg = $result->num_rows . ' results' . EOL;
130 $mesg = mysql_num_rows($result) . ' results' . EOL;
133 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
134 . (($this->error) ? ' error: ' . $this->error : '')
137 logger('dba: ' . $str );
141 * If dbfail.out exists, we will write any failed calls directly to it,
142 * regardless of any logging that may or may nor be in effect.
143 * These usually indicate SQL syntax errors that need to be resolved.
146 if($result === false) {
147 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
148 if(file_exists('dbfail.out'))
149 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
152 if(($result === true) || ($result === false))
157 if($result->num_rows) {
158 while($x = $result->fetch_array(MYSQLI_ASSOC))
160 $result->free_result();
164 if(mysql_num_rows($result)) {
165 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
167 mysql_free_result($result);
171 $a->save_timestamp($stamp1, "database");
174 logger('dba: ' . printable(print_r($r, true)));
178 public function dbg($dbg) {
182 public function escape($str) {
183 if($this->db && $this->connected) {
185 return @$this->db->real_escape_string($str);
187 return @mysql_real_escape_string($str,$this->db);
191 function __destruct() {
196 mysql_close($this->db);
200 if(! function_exists('printable')) {
201 function printable($s) {
202 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
203 $s = str_replace("\x00",'.',$s);
204 if(x($_SERVER,'SERVER_NAME'))
205 $s = escape_tags($s);
209 // Procedural functions
210 if(! function_exists('dbg')) {
211 function dbg($state) {
217 if(! function_exists('dbesc')) {
218 function dbesc($str) {
220 if($db && $db->connected)
221 return($db->escape($str));
223 return(str_replace("'","\\'",$str));
228 // Function: q($sql,$args);
229 // Description: execute SQL query with printf style args.
230 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
233 if(! function_exists('q')) {
237 $args = func_get_args();
240 if($db && $db->connected) {
241 $stmt = @vsprintf($sql,$args); // Disabled warnings
242 //logger("dba: q: $stmt", LOGGER_ALL);
244 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
245 return $db->q($stmt);
250 * This will happen occasionally trying to store the
251 * session data after abnormal program termination
254 logger('dba: no database: ' . print_r($args,true));
261 * Raw db query, no arguments
265 if(! function_exists('dbq')) {
269 if($db && $db->connected)
277 // Caller is responsible for ensuring that any integer arguments to
278 // dbesc_array are actually integers and not malformed strings containing
279 // SQL injection vectors. All integer array elements should be specifically
280 // cast to int to avoid trouble.
283 if(! function_exists('dbesc_array_cb')) {
284 function dbesc_array_cb(&$item, $key) {
286 $item = dbesc($item);
290 if(! function_exists('dbesc_array')) {
291 function dbesc_array(&$arr) {
292 if(is_array($arr) && count($arr)) {
293 array_walk($arr,'dbesc_array_cb');
298 function dba_timer() {
299 return microtime(true);