3 # if PDO is avaible for mysql, use the new database abstraction
4 # TODO: PDO is disabled for release 3.3. We need to investigate why
5 # the update from 3.2 fails with pdo
7 if(class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
8 require_once("library/dddbl2/dddbl.php");
9 require_once("include/dba_pdo.php");
14 require_once('include/datetime.php');
17 * @class MySQL database class
19 * For debugging, insert 'dbg(1);' anywhere in the program flow.
20 * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
21 * When logging, all binary info is converted to text and html entities are escaped so that
22 * the debugging stream is safe to view within both terminals and web pages.
26 if(! class_exists('dba')) {
32 public $mysqli = true;
33 public $connected = false;
34 public $error = false;
36 function __construct($server,$user,$pass,$db,$install = false) {
39 $stamp1 = microtime(true);
41 $server = trim($server);
46 if (!(strlen($server) && strlen($user))){
47 $this->connected = false;
53 if(strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
54 if(! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
55 $this->error = sprintf( t('Cannot locate DNS info for database server \'%s\''), $server);
56 $this->connected = false;
63 if(class_exists('mysqli')) {
64 $this->db = @new mysqli($server,$user,$pass,$db);
65 if(! mysqli_connect_errno()) {
66 $this->connected = true;
70 $this->mysqli = false;
71 $this->db = mysql_connect($server,$user,$pass);
72 if($this->db && mysql_select_db($db,$this->db)) {
73 $this->connected = true;
76 if(! $this->connected) {
82 $a->save_timestamp($stamp1, "network");
85 public function getdb() {
89 public function q($sql, $onlyquery = false) {
92 if((! $this->db) || (! $this->connected))
97 $stamp1 = microtime(true);
100 $result = @$this->db->query($sql);
102 $result = @mysql_query($sql,$this->db);
104 $stamp2 = microtime(true);
105 $duration = (float)($stamp2-$stamp1);
107 $a->save_timestamp($stamp1, "database");
109 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
110 if (($duration > $a->config["system"]["db_loglimit"])) {
111 $duration = round($duration, 3);
112 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
113 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
114 basename($backtrace[1]["file"])."\t".
115 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
116 substr($sql, 0, 2000)."\n", FILE_APPEND);
122 $this->error = $this->db->error;
124 elseif(mysql_errno($this->db))
125 $this->error = mysql_error($this->db);
127 if(strlen($this->error)) {
128 logger('dba: ' . $this->error);
135 if($result === false)
137 elseif($result === true)
141 $mesg = $result->num_rows . ' results' . EOL;
143 $mesg = mysql_num_rows($result) . ' results' . EOL;
146 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
147 . (($this->error) ? ' error: ' . $this->error : '')
150 logger('dba: ' . $str );
154 * If dbfail.out exists, we will write any failed calls directly to it,
155 * regardless of any logging that may or may nor be in effect.
156 * These usually indicate SQL syntax errors that need to be resolved.
159 if($result === false) {
160 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
161 if(file_exists('dbfail.out'))
162 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
165 if(($result === true) || ($result === false))
169 $this->result = $result;
175 if($result->num_rows) {
176 while($x = $result->fetch_array(MYSQLI_ASSOC))
178 $result->free_result();
182 if(mysql_num_rows($result)) {
183 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
185 mysql_free_result($result);
189 //$a->save_timestamp($stamp1, "database");
192 logger('dba: ' . printable(print_r($r, true)));
196 public function qfetch() {
201 if($this->result->num_rows)
202 $x = $this->result->fetch_array(MYSQLI_ASSOC);
204 if(mysql_num_rows($this->result))
205 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
211 public function qclose() {
214 $this->result->free_result();
216 mysql_free_result($this->result);
220 public function dbg($dbg) {
224 public function escape($str) {
225 if($this->db && $this->connected) {
227 return @$this->db->real_escape_string($str);
229 return @mysql_real_escape_string($str,$this->db);
234 * Checks if $array is a filled array with at least one entry.
236 * @param $array mixed A filled array with at least one entry
237 * @return Whether $array is a filled array
239 public function is_result ($array) {
240 return (is_array($array) && count($array) > 0);
243 function __destruct() {
248 mysql_close($this->db);
252 if(! function_exists('printable')) {
253 function printable($s) {
254 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
255 $s = str_replace("\x00",'.',$s);
256 if(x($_SERVER,'SERVER_NAME'))
257 $s = escape_tags($s);
261 // Procedural functions
262 if(! function_exists('dbg')) {
263 function dbg($state) {
269 if(! function_exists('dbesc')) {
270 function dbesc($str) {
272 if($db && $db->connected)
273 return($db->escape($str));
275 return(str_replace("'","\\'",$str));
280 // Function: q($sql,$args);
281 // Description: execute SQL query with printf style args.
282 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
285 if(! function_exists('q')) {
289 $args = func_get_args();
292 if($db && $db->connected) {
293 $stmt = @vsprintf($sql,$args); // Disabled warnings
294 //logger("dba: q: $stmt", LOGGER_ALL);
296 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
297 return $db->q($stmt);
302 * This will happen occasionally trying to store the
303 * session data after abnormal program termination
306 logger('dba: no database: ' . print_r($args,true));
313 * Raw db query, no arguments
317 if(! function_exists('dbq')) {
321 if($db && $db->connected)
329 // Caller is responsible for ensuring that any integer arguments to
330 // dbesc_array are actually integers and not malformed strings containing
331 // SQL injection vectors. All integer array elements should be specifically
332 // cast to int to avoid trouble.
335 if(! function_exists('dbesc_array_cb')) {
336 function dbesc_array_cb(&$item, $key) {
338 $item = dbesc($item);
342 if(! function_exists('dbesc_array')) {
343 function dbesc_array(&$arr) {
344 if(is_array($arr) && count($arr)) {
345 array_walk($arr,'dbesc_array_cb');
350 function dba_timer() {
351 return microtime(true);