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;
69 if (isset($a->config["system"]["db_charset"]))
70 $this->db->set_charset($a->config["system"]["db_charset"]);
73 $this->mysqli = false;
74 $this->db = mysql_connect($server,$user,$pass);
75 if($this->db && mysql_select_db($db,$this->db)) {
76 $this->connected = true;
78 if (isset($a->config["system"]["db_charset"]))
79 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
81 if(! $this->connected) {
87 $a->save_timestamp($stamp1, "network");
90 public function getdb() {
94 public function q($sql, $onlyquery = false) {
97 if((! $this->db) || (! $this->connected))
102 // Check the connection (This can reconnect the connection - if configured)
104 $connected = $this->db->ping();
106 $connected = mysql_ping($this->db);
108 $connstr = ($connected ? "Connected": "Disonnected");
110 $stamp1 = microtime(true);
113 $result = @$this->db->query($sql);
115 $result = @mysql_query($sql,$this->db);
117 $stamp2 = microtime(true);
118 $duration = (float)($stamp2-$stamp1);
120 $a->save_timestamp($stamp1, "database");
122 if (strtolower(substr($sql, 0, 6)) != "select")
123 $a->save_timestamp($stamp1, "database_write");
125 if(x($a->config,'system') && x($a->config['system'],'db_log')) {
126 if (($duration > $a->config["system"]["db_loglimit"])) {
127 $duration = round($duration, 3);
128 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
129 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
130 basename($backtrace[1]["file"])."\t".
131 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
132 substr($sql, 0, 2000)."\n", FILE_APPEND);
137 if($this->db->errno) {
138 $this->error = $this->db->error;
139 $this->errorno = $this->db->errno;
141 } elseif(mysql_errno($this->db)) {
142 $this->error = mysql_error($this->db);
143 $this->errorno = mysql_errno($this->db);
146 if(strlen($this->error)) {
147 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
154 if($result === false)
156 elseif($result === true)
160 $mesg = $result->num_rows . ' results' . EOL;
162 $mesg = mysql_num_rows($result) . ' results' . EOL;
165 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
166 . (($this->error) ? ' error: ' . $this->error : '')
169 logger('dba: ' . $str );
173 * If dbfail.out exists, we will write any failed calls directly to it,
174 * regardless of any logging that may or may nor be in effect.
175 * These usually indicate SQL syntax errors that need to be resolved.
178 if($result === false) {
179 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
180 if(file_exists('dbfail.out'))
181 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
184 if(($result === true) || ($result === false))
188 $this->result = $result;
194 if($result->num_rows) {
195 while($x = $result->fetch_array(MYSQLI_ASSOC))
197 $result->free_result();
201 if(mysql_num_rows($result)) {
202 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
204 mysql_free_result($result);
208 //$a->save_timestamp($stamp1, "database");
211 logger('dba: ' . printable(print_r($r, true)));
215 public function qfetch() {
220 if($this->result->num_rows)
221 $x = $this->result->fetch_array(MYSQLI_ASSOC);
223 if(mysql_num_rows($this->result))
224 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
230 public function qclose() {
233 $this->result->free_result();
235 mysql_free_result($this->result);
239 public function dbg($dbg) {
243 public function escape($str) {
244 if($this->db && $this->connected) {
246 return @$this->db->real_escape_string($str);
248 return @mysql_real_escape_string($str,$this->db);
252 function connected() {
254 $connected = $this->db->ping();
256 $connected = mysql_ping($this->db);
261 function __destruct() {
266 mysql_close($this->db);
270 if(! function_exists('printable')) {
271 function printable($s) {
272 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
273 $s = str_replace("\x00",'.',$s);
274 if(x($_SERVER,'SERVER_NAME'))
275 $s = escape_tags($s);
279 // Procedural functions
280 if(! function_exists('dbg')) {
281 function dbg($state) {
287 if(! function_exists('dbesc')) {
288 function dbesc($str) {
290 if($db && $db->connected)
291 return($db->escape($str));
293 return(str_replace("'","\\'",$str));
298 // Function: q($sql,$args);
299 // Description: execute SQL query with printf style args.
300 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
303 if(! function_exists('q')) {
307 $args = func_get_args();
310 if($db && $db->connected) {
311 $stmt = @vsprintf($sql,$args); // Disabled warnings
312 //logger("dba: q: $stmt", LOGGER_ALL);
314 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
315 return $db->q($stmt);
320 * This will happen occasionally trying to store the
321 * session data after abnormal program termination
324 logger('dba: no database: ' . print_r($args,true));
331 * Raw db query, no arguments
335 if(! function_exists('dbq')) {
339 if($db && $db->connected)
347 // Caller is responsible for ensuring that any integer arguments to
348 // dbesc_array are actually integers and not malformed strings containing
349 // SQL injection vectors. All integer array elements should be specifically
350 // cast to int to avoid trouble.
353 if(! function_exists('dbesc_array_cb')) {
354 function dbesc_array_cb(&$item, $key) {
356 $item = dbesc($item);
360 if(! function_exists('dbesc_array')) {
361 function dbesc_array(&$arr) {
362 if(is_array($arr) && count($arr)) {
363 array_walk($arr,'dbesc_array_cb');
368 function dba_timer() {
369 return microtime(true);