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(x($a->config,'system') && x($a->config['system'],'db_log')) {
111 if (($duration > $a->config["system"]["db_loglimit"])) {
112 $duration = round($duration, 3);
113 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
114 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
115 basename($backtrace[1]["file"])."\t".
116 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
117 substr($sql, 0, 2000)."\n", FILE_APPEND);
123 $this->error = $this->db->error;
125 elseif(mysql_errno($this->db))
126 $this->error = mysql_error($this->db);
128 if(strlen($this->error)) {
129 logger('dba: ' . $this->error);
136 if($result === false)
138 elseif($result === true)
142 $mesg = $result->num_rows . ' results' . EOL;
144 $mesg = mysql_num_rows($result) . ' results' . EOL;
147 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
148 . (($this->error) ? ' error: ' . $this->error : '')
151 logger('dba: ' . $str );
155 * If dbfail.out exists, we will write any failed calls directly to it,
156 * regardless of any logging that may or may nor be in effect.
157 * These usually indicate SQL syntax errors that need to be resolved.
160 if($result === false) {
161 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
162 if(file_exists('dbfail.out'))
163 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
166 if(($result === true) || ($result === false))
170 $this->result = $result;
176 if($result->num_rows) {
177 while($x = $result->fetch_array(MYSQLI_ASSOC))
179 $result->free_result();
183 if(mysql_num_rows($result)) {
184 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
186 mysql_free_result($result);
190 //$a->save_timestamp($stamp1, "database");
193 logger('dba: ' . printable(print_r($r, true)));
197 public function qfetch() {
202 if($this->result->num_rows)
203 $x = $this->result->fetch_array(MYSQLI_ASSOC);
205 if(mysql_num_rows($this->result))
206 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
212 public function qclose() {
215 $this->result->free_result();
217 mysql_free_result($this->result);
221 public function dbg($dbg) {
225 public function escape($str) {
226 if($this->db && $this->connected) {
228 return @$this->db->real_escape_string($str);
230 return @mysql_real_escape_string($str,$this->db);
234 function __destruct() {
239 mysql_close($this->db);
243 if(! function_exists('printable')) {
244 function printable($s) {
245 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
246 $s = str_replace("\x00",'.',$s);
247 if(x($_SERVER,'SERVER_NAME'))
248 $s = escape_tags($s);
252 // Procedural functions
253 if(! function_exists('dbg')) {
254 function dbg($state) {
260 if(! function_exists('dbesc')) {
261 function dbesc($str) {
263 if($db && $db->connected)
264 return($db->escape($str));
266 return(str_replace("'","\\'",$str));
271 // Function: q($sql,$args);
272 // Description: execute SQL query with printf style args.
273 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
276 if(! function_exists('q')) {
280 $args = func_get_args();
283 if($db && $db->connected) {
284 $stmt = @vsprintf($sql,$args); // Disabled warnings
285 //logger("dba: q: $stmt", LOGGER_ALL);
287 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
288 return $db->q($stmt);
293 * This will happen occasionally trying to store the
294 * session data after abnormal program termination
297 logger('dba: no database: ' . print_r($args,true));
304 * Raw db query, no arguments
308 if(! function_exists('dbq')) {
312 if($db && $db->connected)
320 // Caller is responsible for ensuring that any integer arguments to
321 // dbesc_array are actually integers and not malformed strings containing
322 // SQL injection vectors. All integer array elements should be specifically
323 // cast to int to avoid trouble.
326 if(! function_exists('dbesc_array_cb')) {
327 function dbesc_array_cb(&$item, $key) {
329 $item = dbesc($item);
333 if(! function_exists('dbesc_array')) {
334 function dbesc_array(&$arr) {
335 if(is_array($arr) && count($arr)) {
336 array_walk($arr,'dbesc_array_cb');
341 function dba_timer() {
342 return microtime(true);