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')) {
22 public $mysqli = true;
23 public $connected = false;
24 public $error = false;
26 function __construct($server,$user,$pass,$db,$install = false) {
29 $stamp1 = microtime(true);
31 $server = trim($server);
36 if (!(strlen($server) && strlen($user))){
37 $this->connected = false;
43 if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
44 if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
45 $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
46 $this->connected = false;
53 if(class_exists('mysqli')) {
54 $this->db = @new mysqli($server,$user,$pass,$db);
55 if(! mysqli_connect_errno()) {
56 $this->connected = true;
60 $this->mysqli = false;
61 $this->db = mysql_connect($server,$user,$pass);
62 if($this->db && mysql_select_db($db,$this->db)) {
63 $this->connected = true;
66 if(! $this->connected) {
72 $a->save_timestamp($stamp1, "network");
75 public function getdb() {
79 public function q($sql, $onlyquery = false) {
82 if((! $this->db) || (! $this->connected))
87 $stamp1 = microtime(true);
90 $result = @$this->db->query($sql);
92 $result = @mysql_query($sql,$this->db);
94 $stamp2 = microtime(true);
95 $duration = (float)($stamp2-$stamp1);
97 $a->save_timestamp($stamp1, "database");
99 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
100 if (($duration > $a->config["system"]["db_loglimit"])) {
101 $duration = round($duration, 3);
102 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
103 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
104 basename($backtrace[1]["file"])."\t".
105 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
106 substr($sql, 0, 2000)."\n", FILE_APPEND);
112 $this->error = $this->db->error;
114 elseif(mysql_errno($this->db))
115 $this->error = mysql_error($this->db);
117 if(strlen($this->error)) {
118 logger('dba: ' . $this->error);
125 if($result === false)
127 elseif($result === true)
131 $mesg = $result->num_rows . ' results' . EOL;
133 $mesg = mysql_num_rows($result) . ' results' . EOL;
136 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
137 . (($this->error) ? ' error: ' . $this->error : '')
140 logger('dba: ' . $str );
144 * If dbfail.out exists, we will write any failed calls directly to it,
145 * regardless of any logging that may or may nor be in effect.
146 * These usually indicate SQL syntax errors that need to be resolved.
149 if($result === false) {
150 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
151 if(file_exists('dbfail.out'))
152 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
155 if(($result === true) || ($result === false))
159 $this->result = $result;
165 if($result->num_rows) {
166 while($x = $result->fetch_array(MYSQLI_ASSOC))
168 $result->free_result();
172 if(mysql_num_rows($result)) {
173 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
175 mysql_free_result($result);
179 //$a->save_timestamp($stamp1, "database");
182 logger('dba: ' . printable(print_r($r, true)));
186 public function qfetch() {
191 if($this->result->num_rows)
192 $x = $this->result->fetch_array(MYSQLI_ASSOC);
194 if(mysql_num_rows($this->result))
195 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
201 public function qclose() {
204 $this->result->free_result();
206 mysql_free_result($this->result);
210 public function dbg($dbg) {
214 public function escape($str) {
215 if($this->db && $this->connected) {
217 return @$this->db->real_escape_string($str);
219 return @mysql_real_escape_string($str,$this->db);
223 function __destruct() {
228 mysql_close($this->db);
232 if(! function_exists('printable')) {
233 function printable($s) {
234 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
235 $s = str_replace("\x00",'.',$s);
236 if(x($_SERVER,'SERVER_NAME'))
237 $s = escape_tags($s);
241 // Procedural functions
242 if(! function_exists('dbg')) {
243 function dbg($state) {
249 if(! function_exists('dbesc')) {
250 function dbesc($str) {
252 if($db && $db->connected)
253 return($db->escape($str));
255 return(str_replace("'","\\'",$str));
260 // Function: q($sql,$args);
261 // Description: execute SQL query with printf style args.
262 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
265 if(! function_exists('q')) {
269 $args = func_get_args();
272 if($db && $db->connected) {
273 $stmt = @vsprintf($sql,$args); // Disabled warnings
274 //logger("dba: q: $stmt", LOGGER_ALL);
276 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
277 return $db->q($stmt);
282 * This will happen occasionally trying to store the
283 * session data after abnormal program termination
286 logger('dba: no database: ' . print_r($args,true));
293 * Raw db query, no arguments
297 if(! function_exists('dbq')) {
301 if($db && $db->connected)
309 // Caller is responsible for ensuring that any integer arguments to
310 // dbesc_array are actually integers and not malformed strings containing
311 // SQL injection vectors. All integer array elements should be specifically
312 // cast to int to avoid trouble.
315 if(! function_exists('dbesc_array_cb')) {
316 function dbesc_array_cb(&$item, $key) {
318 $item = dbesc($item);
322 if(! function_exists('dbesc_array')) {
323 function dbesc_array(&$arr) {
324 if(is_array($arr) && count($arr)) {
325 array_walk($arr,'dbesc_array_cb');
330 function dba_timer() {
331 return microtime(true);