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;
71 $this->mysqli = false;
72 $this->db = mysql_connect($server,$user,$pass);
73 if($this->db && mysql_select_db($db,$this->db)) {
74 $this->connected = true;
77 if(! $this->connected) {
83 $a->save_timestamp($stamp1, "network");
86 public function getdb() {
90 public function q($sql, $onlyquery = false) {
93 if((! $this->db) || (! $this->connected))
98 $stamp1 = microtime(true);
101 $result = @$this->db->query($sql);
103 $result = @mysql_query($sql,$this->db);
105 $stamp2 = microtime(true);
106 $duration = (float)($stamp2-$stamp1);
108 $a->save_timestamp($stamp1, "database");
110 if (strtolower(substr($sql, 0, 6)) != "select")
111 $a->save_timestamp($stamp1, "database_write");
113 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
114 if (($duration > $a->config["system"]["db_loglimit"])) {
115 $duration = round($duration, 3);
116 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
117 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
118 basename($backtrace[1]["file"])."\t".
119 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
120 substr($sql, 0, 2000)."\n", FILE_APPEND);
126 $this->error = $this->db->error;
128 elseif(mysql_errno($this->db))
129 $this->error = mysql_error($this->db);
131 if(strlen($this->error)) {
132 logger('dba: ' . $this->error);
139 if($result === false)
141 elseif($result === true)
145 $mesg = $result->num_rows . ' results' . EOL;
147 $mesg = mysql_num_rows($result) . ' results' . EOL;
150 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
151 . (($this->error) ? ' error: ' . $this->error : '')
154 logger('dba: ' . $str );
158 * If dbfail.out exists, we will write any failed calls directly to it,
159 * regardless of any logging that may or may nor be in effect.
160 * These usually indicate SQL syntax errors that need to be resolved.
163 if($result === false) {
164 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
165 if(file_exists('dbfail.out'))
166 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
169 if(($result === true) || ($result === false))
173 $this->result = $result;
179 if($result->num_rows) {
180 while($x = $result->fetch_array(MYSQLI_ASSOC))
182 $result->free_result();
186 if(mysql_num_rows($result)) {
187 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
189 mysql_free_result($result);
193 //$a->save_timestamp($stamp1, "database");
196 logger('dba: ' . printable(print_r($r, true)));
200 public function qfetch() {
205 if($this->result->num_rows)
206 $x = $this->result->fetch_array(MYSQLI_ASSOC);
208 if(mysql_num_rows($this->result))
209 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
215 public function qclose() {
218 $this->result->free_result();
220 mysql_free_result($this->result);
224 public function dbg($dbg) {
228 public function escape($str) {
229 if($this->db && $this->connected) {
231 return @$this->db->real_escape_string($str);
233 return @mysql_real_escape_string($str,$this->db);
237 function __destruct() {
242 mysql_close($this->db);
246 if(! function_exists('printable')) {
247 function printable($s) {
248 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
249 $s = str_replace("\x00",'.',$s);
250 if(x($_SERVER,'SERVER_NAME'))
251 $s = escape_tags($s);
255 // Procedural functions
256 if(! function_exists('dbg')) {
257 function dbg($state) {
263 if(! function_exists('dbesc')) {
264 function dbesc($str) {
266 if($db && $db->connected)
267 return($db->escape($str));
269 return(str_replace("'","\\'",$str));
274 // Function: q($sql,$args);
275 // Description: execute SQL query with printf style args.
276 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
279 if(! function_exists('q')) {
283 $args = func_get_args();
286 if($db && $db->connected) {
287 $stmt = @vsprintf($sql,$args); // Disabled warnings
288 //logger("dba: q: $stmt", LOGGER_ALL);
290 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
291 return $db->q($stmt);
296 * This will happen occasionally trying to store the
297 * session data after abnormal program termination
300 logger('dba: no database: ' . print_r($args,true));
307 * Raw db query, no arguments
311 if(! function_exists('dbq')) {
315 if($db && $db->connected)
323 // Caller is responsible for ensuring that any integer arguments to
324 // dbesc_array are actually integers and not malformed strings containing
325 // SQL injection vectors. All integer array elements should be specifically
326 // cast to int to avoid trouble.
329 if(! function_exists('dbesc_array_cb')) {
330 function dbesc_array_cb(&$item, $key) {
332 $item = dbesc($item);
336 if(! function_exists('dbesc_array')) {
337 function dbesc_array(&$arr) {
338 if(is_array($arr) && count($arr)) {
339 array_walk($arr,'dbesc_array_cb');
344 function dba_timer() {
345 return microtime(true);