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) {
88 $a->save_timestamp($stamp1, "network");
91 public function getdb() {
96 * @brief Returns the MySQL server version string
98 * This function discriminate between the deprecated mysql API and the current
99 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
103 public function server_info() {
105 $return = $this->db->server_info;
107 $return = mysql_get_server_info($this->db);
113 * @brief Returns the number of rows
117 public function num_rows() {
118 if (!$this->result) {
123 $return = $this->result->num_rows;
125 $return = mysql_num_rows($this->result);
130 public function q($sql, $onlyquery = false) {
133 if (!$this->db || !$this->connected) {
139 // Check the connection (This can reconnect the connection - if configured)
141 $connected = $this->db->ping();
143 $connected = mysql_ping($this->db);
145 $connstr = ($connected ? "Connected" : "Disonnected");
147 $stamp1 = microtime(true);
151 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
152 $sql = "/*".$a->callstack()." */ ".$sql;
156 $result = @$this->db->query($sql);
158 $result = @mysql_query($sql,$this->db);
160 $stamp2 = microtime(true);
161 $duration = (float)($stamp2-$stamp1);
163 $a->save_timestamp($stamp1, "database");
165 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
166 $a->save_timestamp($stamp1, "database_write");
168 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
169 if (($duration > $a->config["system"]["db_loglimit"])) {
170 $duration = round($duration, 3);
171 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
172 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
173 basename($backtrace[1]["file"])."\t".
174 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
175 substr($sql, 0, 2000)."\n", FILE_APPEND);
180 if ($this->db->errno) {
181 $this->error = $this->db->error;
182 $this->errorno = $this->db->errno;
184 } elseif (mysql_errno($this->db)) {
185 $this->error = mysql_error($this->db);
186 $this->errorno = mysql_errno($this->db);
189 if (strlen($this->error)) {
190 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
197 if ($result === false) {
199 } elseif ($result === true) {
203 $mesg = $result->num_rows . ' results' . EOL;
205 $mesg = mysql_num_rows($result) . ' results' . EOL;
209 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
210 . (($this->error) ? ' error: ' . $this->error : '')
213 logger('dba: ' . $str );
217 * If dbfail.out exists, we will write any failed calls directly to it,
218 * regardless of any logging that may or may nor be in effect.
219 * These usually indicate SQL syntax errors that need to be resolved.
222 if ($result === false) {
223 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
224 if (file_exists('dbfail.out'))
225 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
228 if (($result === true) || ($result === false))
232 $this->result = $result;
238 if ($result->num_rows) {
239 while($x = $result->fetch_array(MYSQLI_ASSOC))
241 $result->free_result();
244 if (mysql_num_rows($result)) {
245 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
247 mysql_free_result($result);
251 //$a->save_timestamp($stamp1, "database");
254 logger('dba: ' . printable(print_r($r, true)));
258 public function qfetch() {
263 if ($this->result->num_rows)
264 $x = $this->result->fetch_array(MYSQLI_ASSOC);
266 if (mysql_num_rows($this->result))
267 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
273 public function qclose() {
276 $this->result->free_result();
278 mysql_free_result($this->result);
283 public function dbg($dbg) {
287 public function escape($str) {
288 if ($this->db && $this->connected) {
290 return @$this->db->real_escape_string($str);
292 return @mysql_real_escape_string($str,$this->db);
297 function connected() {
299 $connected = $this->db->ping();
301 $connected = mysql_ping($this->db);
306 function __destruct() {
311 mysql_close($this->db);
317 if (! function_exists('printable')) {
318 function printable($s) {
319 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
320 $s = str_replace("\x00",'.',$s);
321 if (x($_SERVER,'SERVER_NAME'))
322 $s = escape_tags($s);
326 // Procedural functions
327 if (! function_exists('dbg')) {
328 function dbg($state) {
334 if (! function_exists('dbesc')) {
335 function dbesc($str) {
337 if ($db && $db->connected) {
338 return($db->escape($str));
340 return(str_replace("'","\\'",$str));
346 // Function: q($sql,$args);
347 // Description: execute SQL query with printf style args.
348 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
351 if (! function_exists('q')) {
355 $args = func_get_args();
358 if ($db && $db->connected) {
359 $stmt = @vsprintf($sql,$args); // Disabled warnings
360 //logger("dba: q: $stmt", LOGGER_ALL);
362 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
363 return $db->q($stmt);
368 * This will happen occasionally trying to store the
369 * session data after abnormal program termination
372 logger('dba: no database: ' . print_r($args,true));
378 * @brief Performs a query with "dirty reads"
380 * By doing dirty reads (reading uncommitted data) no locks are performed
381 * This function can be used to fetch data that doesn't need to be reliable.
383 * @param $args Query parameters (1 to N parameters of different types)
384 * @return array Query array
389 $args = func_get_args();
392 if ($db && $db->connected) {
393 $stmt = @vsprintf($sql,$args); // Disabled warnings
395 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
396 $db->q("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
397 $retval = $db->q($stmt);
404 * This will happen occasionally trying to store the
405 * session data after abnormal program termination
408 logger('dba: no database: ' . print_r($args,true));
415 * Raw db query, no arguments
419 if (! function_exists('dbq')) {
423 if ($db && $db->connected) {
432 // Caller is responsible for ensuring that any integer arguments to
433 // dbesc_array are actually integers and not malformed strings containing
434 // SQL injection vectors. All integer array elements should be specifically
435 // cast to int to avoid trouble.
438 if (! function_exists('dbesc_array_cb')) {
439 function dbesc_array_cb(&$item, $key) {
440 if (is_string($item))
441 $item = dbesc($item);
445 if (! function_exists('dbesc_array')) {
446 function dbesc_array(&$arr) {
447 if (is_array($arr) && count($arr)) {
448 array_walk($arr,'dbesc_array_cb');
453 function dba_timer() {
454 return microtime(true);