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;
68 //mysqli_set_charset($this->db, 'utf8');
72 $this->mysqli = false;
73 $this->db = mysql_connect($server,$user,$pass);
74 if($this->db && mysql_select_db($db,$this->db)) {
75 $this->connected = true;
76 //mysql_set_charset('utf8', $this->db);
79 if(! $this->connected) {
85 $a->save_timestamp($stamp1, "network");
88 public function getdb() {
92 public function q($sql, $onlyquery = false) {
95 if((! $this->db) || (! $this->connected))
100 $stamp1 = microtime(true);
103 $result = @$this->db->query($sql);
105 $result = @mysql_query($sql,$this->db);
107 $stamp2 = microtime(true);
108 $duration = (float)($stamp2-$stamp1);
110 $a->save_timestamp($stamp1, "database");
112 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
113 if (($duration > $a->config["system"]["db_loglimit"])) {
114 $duration = round($duration, 3);
115 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
116 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
117 basename($backtrace[1]["file"])."\t".
118 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
119 substr($sql, 0, 2000)."\n", FILE_APPEND);
125 $this->error = $this->db->error;
127 elseif(mysql_errno($this->db))
128 $this->error = mysql_error($this->db);
130 if(strlen($this->error)) {
131 logger('dba: ' . $this->error);
138 if($result === false)
140 elseif($result === true)
144 $mesg = $result->num_rows . ' results' . EOL;
146 $mesg = mysql_num_rows($result) . ' results' . EOL;
149 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
150 . (($this->error) ? ' error: ' . $this->error : '')
153 logger('dba: ' . $str );
157 * If dbfail.out exists, we will write any failed calls directly to it,
158 * regardless of any logging that may or may nor be in effect.
159 * These usually indicate SQL syntax errors that need to be resolved.
162 if($result === false) {
163 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
164 if(file_exists('dbfail.out'))
165 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
168 if(($result === true) || ($result === false))
172 $this->result = $result;
178 if($result->num_rows) {
179 while($x = $result->fetch_array(MYSQLI_ASSOC))
181 $result->free_result();
185 if(mysql_num_rows($result)) {
186 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
188 mysql_free_result($result);
192 //$a->save_timestamp($stamp1, "database");
195 logger('dba: ' . printable(print_r($r, true)));
199 public function qfetch() {
204 if($this->result->num_rows)
205 $x = $this->result->fetch_array(MYSQLI_ASSOC);
207 if(mysql_num_rows($this->result))
208 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
214 public function qclose() {
217 $this->result->free_result();
219 mysql_free_result($this->result);
223 public function dbg($dbg) {
227 public function escape($str) {
228 if($this->db && $this->connected) {
230 return @$this->db->real_escape_string($str);
232 return @mysql_real_escape_string($str,$this->db);
236 function __destruct() {
241 mysql_close($this->db);
245 if(! function_exists('printable')) {
246 function printable($s) {
247 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
248 $s = str_replace("\x00",'.',$s);
249 if(x($_SERVER,'SERVER_NAME'))
250 $s = escape_tags($s);
254 // Procedural functions
255 if(! function_exists('dbg')) {
256 function dbg($state) {
262 if(! function_exists('dbesc')) {
263 function dbesc($str) {
265 if($db && $db->connected)
266 return($db->escape($str));
268 return(str_replace("'","\\'",$str));
273 // Function: q($sql,$args);
274 // Description: execute SQL query with printf style args.
275 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
278 if(! function_exists('q')) {
282 $args = func_get_args();
285 if($db && $db->connected) {
286 $stmt = @vsprintf($sql,$args); // Disabled warnings
287 //logger("dba: q: $stmt", LOGGER_ALL);
289 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
290 return $db->q($stmt);
295 * This will happen occasionally trying to store the
296 * session data after abnormal program termination
299 logger('dba: no database: ' . print_r($args,true));
306 * Raw db query, no arguments
310 if(! function_exists('dbq')) {
314 if($db && $db->connected)
322 // Caller is responsible for ensuring that any integer arguments to
323 // dbesc_array are actually integers and not malformed strings containing
324 // SQL injection vectors. All integer array elements should be specifically
325 // cast to int to avoid trouble.
328 if(! function_exists('dbesc_array_cb')) {
329 function dbesc_array_cb(&$item, $key) {
331 $item = dbesc($item);
335 if(! function_exists('dbesc_array')) {
336 function dbesc_array(&$arr) {
337 if(is_array($arr) && count($arr)) {
338 array_walk($arr,'dbesc_array_cb');
343 function dba_timer() {
344 return microtime(true);