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;
68 //mysqli_set_charset($this->db, 'utf8');
70 if (isset($a->config["system"]["db_charset"])) {
71 $this->db->set_charset($a->config["system"]["db_charset"]);
74 $this->mysqli = false;
75 $this->db = mysql_connect($server,$user,$pass);
76 if ($this->db && mysql_select_db($db,$this->db)) {
77 $this->connected = true;
78 //mysql_set_charset('utf8', $this->db);
80 if (isset($a->config["system"]["db_charset"]))
81 mysql_set_charset($a->config["system"]["db_charset"], $this->db);
83 if (!$this->connected) {
90 $a->save_timestamp($stamp1, "network");
93 public function getdb() {
98 * @brief Returns the MySQL server version string
100 * This function discriminate between the deprecated mysql API and the current
101 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
105 public function server_info() {
107 $return = $this->db->server_info;
109 $return = mysql_get_server_info($this->db);
115 * @brief Returns the number of rows
119 public function num_rows() {
120 if (!$this->result) {
125 $return = $this->result->num_rows;
127 $return = mysql_num_rows($this->result);
132 public function q($sql, $onlyquery = false) {
135 if (!$this->db || !$this->connected) {
141 // Check the connection (This can reconnect the connection - if configured)
143 $connected = $this->db->ping();
145 $connected = mysql_ping($this->db);
147 $connstr = ($connected ? "Connected" : "Disonnected");
149 $stamp1 = microtime(true);
153 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
154 $sql = "/*".$a->callstack()." */ ".$sql;
158 $result = @$this->db->query($sql);
160 $result = @mysql_query($sql,$this->db);
162 $stamp2 = microtime(true);
163 $duration = (float)($stamp2-$stamp1);
165 $a->save_timestamp($stamp1, "database");
167 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
168 $a->save_timestamp($stamp1, "database_write");
170 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
171 if (($duration > $a->config["system"]["db_loglimit"])) {
172 $duration = round($duration, 3);
173 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
174 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
175 basename($backtrace[1]["file"])."\t".
176 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
177 substr($sql, 0, 2000)."\n", FILE_APPEND);
182 if ($this->db->errno) {
183 $this->error = $this->db->error;
184 $this->errorno = $this->db->errno;
186 } elseif (mysql_errno($this->db)) {
187 $this->error = mysql_error($this->db);
188 $this->errorno = mysql_errno($this->db);
191 if (strlen($this->error)) {
192 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
199 if ($result === false) {
201 } elseif ($result === true) {
205 $mesg = $result->num_rows . ' results' . EOL;
207 $mesg = mysql_num_rows($result) . ' results' . EOL;
211 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
212 . (($this->error) ? ' error: ' . $this->error : '')
215 logger('dba: ' . $str );
219 * If dbfail.out exists, we will write any failed calls directly to it,
220 * regardless of any logging that may or may nor be in effect.
221 * These usually indicate SQL syntax errors that need to be resolved.
224 if ($result === false) {
225 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
226 if (file_exists('dbfail.out')) {
227 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
231 if (($result === true) || ($result === false)) {
235 $this->result = $result;
241 if ($result->num_rows) {
242 while($x = $result->fetch_array(MYSQLI_ASSOC))
244 $result->free_result();
247 if (mysql_num_rows($result)) {
248 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
250 mysql_free_result($result);
254 //$a->save_timestamp($stamp1, "database");
257 logger('dba: ' . printable(print_r($r, true)));
262 public function qfetch() {
267 if ($this->result->num_rows)
268 $x = $this->result->fetch_array(MYSQLI_ASSOC);
270 if (mysql_num_rows($this->result))
271 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
277 public function qclose() {
280 $this->result->free_result();
282 mysql_free_result($this->result);
287 public function dbg($dbg) {
291 public function escape($str) {
292 if ($this->db && $this->connected) {
294 return @$this->db->real_escape_string($str);
296 return @mysql_real_escape_string($str,$this->db);
301 function connected() {
303 $connected = $this->db->ping();
305 $connected = mysql_ping($this->db);
310 function __destruct() {
315 mysql_close($this->db);
321 if (! function_exists('printable')) {
322 function printable($s) {
323 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
324 $s = str_replace("\x00",'.',$s);
325 if (x($_SERVER,'SERVER_NAME')) {
326 $s = escape_tags($s);
331 // Procedural functions
332 if (! function_exists('dbg')) {
333 function dbg($state) {
340 if (! function_exists('dbesc')) {
341 function dbesc($str) {
343 if ($db && $db->connected) {
344 return($db->escape($str));
346 return(str_replace("'","\\'",$str));
352 // Function: q($sql,$args);
353 // Description: execute SQL query with printf style args.
354 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
357 if (! function_exists('q')) {
361 $args = func_get_args();
364 if ($db && $db->connected) {
365 $stmt = @vsprintf($sql,$args); // Disabled warnings
366 //logger("dba: q: $stmt", LOGGER_ALL);
368 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
369 return $db->q($stmt);
374 * This will happen occasionally trying to store the
375 * session data after abnormal program termination
378 logger('dba: no database: ' . print_r($args,true));
384 * @brief Performs a query with "dirty reads"
386 * By doing dirty reads (reading uncommitted data) no locks are performed
387 * This function can be used to fetch data that doesn't need to be reliable.
389 * @param $args Query parameters (1 to N parameters of different types)
390 * @return array Query array
395 $args = func_get_args();
398 if ($db && $db->connected) {
399 $stmt = @vsprintf($sql,$args); // Disabled warnings
401 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
402 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
403 $retval = $db->q($stmt);
404 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
410 * This will happen occasionally trying to store the
411 * session data after abnormal program termination
414 logger('dba: no database: ' . print_r($args,true));
421 * Raw db query, no arguments
425 if (! function_exists('dbq')) {
429 if ($db && $db->connected) {
438 // Caller is responsible for ensuring that any integer arguments to
439 // dbesc_array are actually integers and not malformed strings containing
440 // SQL injection vectors. All integer array elements should be specifically
441 // cast to int to avoid trouble.
444 if (! function_exists('dbesc_array_cb')) {
445 function dbesc_array_cb(&$item, $key) {
446 if (is_string($item))
447 $item = dbesc($item);
451 if (! function_exists('dbesc_array')) {
452 function dbesc_array(&$arr) {
453 if (is_array($arr) && count($arr)) {
454 array_walk($arr,'dbesc_array_cb');
459 function dba_timer() {
460 return microtime(true);