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);
233 function __destruct() {
238 mysql_close($this->db);
242 if(! function_exists('printable')) {
243 function printable($s) {
244 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
245 $s = str_replace("\x00",'.',$s);
246 if(x($_SERVER,'SERVER_NAME'))
247 $s = escape_tags($s);
251 // Procedural functions
252 if(! function_exists('dbg')) {
253 function dbg($state) {
259 if(! function_exists('dbesc')) {
260 function dbesc($str) {
262 if($db && $db->connected)
263 return($db->escape($str));
265 return(str_replace("'","\\'",$str));
270 // Function: q($sql,$args);
271 // Description: execute SQL query with printf style args.
272 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
275 if(! function_exists('q')) {
279 $args = func_get_args();
282 if($db && $db->connected) {
283 $stmt = @vsprintf($sql,$args); // Disabled warnings
284 //logger("dba: q: $stmt", LOGGER_ALL);
286 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
287 return $db->q($stmt);
292 * This will happen occasionally trying to store the
293 * session data after abnormal program termination
296 logger('dba: no database: ' . print_r($args,true));
303 * Raw db query, no arguments
307 if(! function_exists('dbq')) {
311 if($db && $db->connected)
319 // Caller is responsible for ensuring that any integer arguments to
320 // dbesc_array are actually integers and not malformed strings containing
321 // SQL injection vectors. All integer array elements should be specifically
322 // cast to int to avoid trouble.
325 if(! function_exists('dbesc_array_cb')) {
326 function dbesc_array_cb(&$item, $key) {
328 $item = dbesc($item);
332 if(! function_exists('dbesc_array')) {
333 function dbesc_array(&$arr) {
334 if(is_array($arr) && count($arr)) {
335 array_walk($arr,'dbesc_array_cb');
340 function dba_timer() {
341 return microtime(true);