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() {
95 * @brief Returns the MySQL server version string
97 * This function discriminate between the deprecated mysql API and the current
98 * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
102 public function server_info() {
104 $return = $this->db->server_info;
106 $return = mysql_get_server_info($this->db);
112 * @brief Returns the number of rows
116 public function num_rows() {
121 $return = $this->result->num_rows;
123 $return = mysql_num_rows($this->result);
128 public function q($sql, $onlyquery = false) {
131 if ((!$this->db) || (!$this->connected))
136 // Check the connection (This can reconnect the connection - if configured)
138 $connected = $this->db->ping();
140 $connected = mysql_ping($this->db);
142 $connstr = ($connected ? "Connected": "Disonnected");
144 $stamp1 = microtime(true);
148 if (x($a->config,'system') && x($a->config['system'],'db_callstack')) {
149 $sql = "/*".$a->callstack()." */ ".$sql;
153 $result = @$this->db->query($sql);
155 $result = @mysql_query($sql,$this->db);
157 $stamp2 = microtime(true);
158 $duration = (float)($stamp2-$stamp1);
160 $a->save_timestamp($stamp1, "database");
162 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
163 $a->save_timestamp($stamp1, "database_write");
165 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
166 if (($duration > $a->config["system"]["db_loglimit"])) {
167 $duration = round($duration, 3);
168 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
169 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
170 basename($backtrace[1]["file"])."\t".
171 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
172 substr($sql, 0, 2000)."\n", FILE_APPEND);
177 if ($this->db->errno) {
178 $this->error = $this->db->error;
179 $this->errorno = $this->db->errno;
181 } elseif (mysql_errno($this->db)) {
182 $this->error = mysql_error($this->db);
183 $this->errorno = mysql_errno($this->db);
186 if (strlen($this->error)) {
187 logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
194 if ($result === false) {
196 } elseif ($result === true) {
200 $mesg = $result->num_rows . ' results' . EOL;
202 $mesg = mysql_num_rows($result) . ' results' . EOL;
206 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
207 . (($this->error) ? ' error: ' . $this->error : '')
210 logger('dba: ' . $str );
214 * If dbfail.out exists, we will write any failed calls directly to it,
215 * regardless of any logging that may or may nor be in effect.
216 * These usually indicate SQL syntax errors that need to be resolved.
219 if ($result === false) {
220 logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
221 if (file_exists('dbfail.out'))
222 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
225 if (($result === true) || ($result === false))
229 $this->result = $result;
235 if ($result->num_rows) {
236 while($x = $result->fetch_array(MYSQLI_ASSOC))
238 $result->free_result();
241 if (mysql_num_rows($result)) {
242 while($x = mysql_fetch_array($result, MYSQL_ASSOC))
244 mysql_free_result($result);
248 //$a->save_timestamp($stamp1, "database");
251 logger('dba: ' . printable(print_r($r, true)));
255 public function qfetch() {
260 if ($this->result->num_rows)
261 $x = $this->result->fetch_array(MYSQLI_ASSOC);
263 if (mysql_num_rows($this->result))
264 $x = mysql_fetch_array($this->result, MYSQL_ASSOC);
270 public function qclose() {
273 $this->result->free_result();
275 mysql_free_result($this->result);
279 public function dbg($dbg) {
283 public function escape($str) {
284 if ($this->db && $this->connected) {
286 return @$this->db->real_escape_string($str);
288 return @mysql_real_escape_string($str,$this->db);
293 function connected() {
295 $connected = $this->db->ping();
297 $connected = mysql_ping($this->db);
302 function __destruct() {
307 mysql_close($this->db);
313 if (! function_exists('printable')) {
314 function printable($s) {
315 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
316 $s = str_replace("\x00",'.',$s);
317 if (x($_SERVER,'SERVER_NAME'))
318 $s = escape_tags($s);
322 // Procedural functions
323 if (! function_exists('dbg')) {
324 function dbg($state) {
330 if (! function_exists('dbesc')) {
331 function dbesc($str) {
333 if ($db && $db->connected) {
334 return($db->escape($str));
336 return(str_replace("'","\\'",$str));
342 // Function: q($sql,$args);
343 // Description: execute SQL query with printf style args.
344 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
347 if (! function_exists('q')) {
351 $args = func_get_args();
354 if ($db && $db->connected) {
355 $stmt = @vsprintf($sql,$args); // Disabled warnings
356 //logger("dba: q: $stmt", LOGGER_ALL);
358 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
359 return $db->q($stmt);
364 * This will happen occasionally trying to store the
365 * session data after abnormal program termination
368 logger('dba: no database: ' . print_r($args,true));
374 * @brief Performs a query with "dirty reads"
376 * By doing dirty reads (reading uncommitted data) no locks are performed
377 * This function can be used to fetch data that doesn't need to be reliable.
379 * @param $args Query parameters (1 to N parameters of different types)
380 * @return array Query array
385 $args = func_get_args();
388 if ($db && $db->connected) {
389 $stmt = @vsprintf($sql,$args); // Disabled warnings
391 logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
392 $db->q("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
393 $retval = $db->q($stmt);
400 * This will happen occasionally trying to store the
401 * session data after abnormal program termination
404 logger('dba: no database: ' . print_r($args,true));
411 * Raw db query, no arguments
415 if (! function_exists('dbq')) {
419 if ($db && $db->connected) {
428 // Caller is responsible for ensuring that any integer arguments to
429 // dbesc_array are actually integers and not malformed strings containing
430 // SQL injection vectors. All integer array elements should be specifically
431 // cast to int to avoid trouble.
434 if (! function_exists('dbesc_array_cb')) {
435 function dbesc_array_cb(&$item, $key) {
436 if (is_string($item))
437 $item = dbesc($item);
441 if (! function_exists('dbesc_array')) {
442 function dbesc_array(&$arr) {
443 if (is_array($arr) && count($arr)) {
444 array_walk($arr,'dbesc_array_cb');
449 function dba_timer() {
450 return microtime(true);