]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Salmons with Mastodon seem to work now
[friendica.git] / include / dba.php
1 <?php
2 require_once("dbm.php");
3 require_once('include/datetime.php');
4
5 /**
6  * @class MySQL database class
7  *
8  * For debugging, insert 'dbg(1);' anywhere in the program flow.
9  * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
10  * When logging, all binary info is converted to text and html entities are escaped so that
11  * the debugging stream is safe to view within both terminals and web pages.
12  *
13  * This class is for the low level database stuff that does driver specific things.
14  */
15
16 class dba {
17
18         private $debug = 0;
19         private $db;
20         private $result;
21         private $driver;
22         public  $connected = false;
23         public  $error = false;
24         private $_server_info = '';
25         private static $dbo;
26
27         function __construct($server, $user, $pass, $db, $install = false) {
28                 $a = get_app();
29
30                 $stamp1 = microtime(true);
31
32                 $server = trim($server);
33                 $user = trim($user);
34                 $pass = trim($pass);
35                 $db = trim($db);
36
37                 if (!(strlen($server) && strlen($user))) {
38                         $this->connected = false;
39                         $this->db = null;
40                         return;
41                 }
42
43                 if ($install) {
44                         if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
45                                 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
46                                         $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
47                                         $this->connected = false;
48                                         $this->db = null;
49                                         return;
50                                 }
51                         }
52                 }
53
54                 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
55                         $this->driver = 'pdo';
56                         $connect = "mysql:host=".$server.";dbname=".$db;
57                         if (isset($a->config["system"]["db_charset"])) {
58                                 $connect .= ";charset=".$a->config["system"]["db_charset"];
59                         }
60                         $this->db = @new PDO($connect, $user, $pass);
61                         if (!$this->db->errorCode()) {
62                                 $this->connected = true;
63                         }
64                 } elseif (class_exists('mysqli')) {
65                         $this->driver = 'mysqli';
66                         $this->db = @new mysqli($server,$user,$pass,$db);
67                         if (!mysqli_connect_errno()) {
68                                 $this->connected = true;
69
70                                 if (isset($a->config["system"]["db_charset"])) {
71                                         $this->db->set_charset($a->config["system"]["db_charset"]);
72                                 }
73                         }
74                 } elseif (function_exists('mysql_connect')) {
75                         $this->driver = 'mysql';
76                         $this->db = mysql_connect($server,$user,$pass);
77                         if ($this->db && mysql_select_db($db,$this->db)) {
78                                 $this->connected = true;
79
80                                 if (isset($a->config["system"]["db_charset"])) {
81                                         mysql_set_charset($a->config["system"]["db_charset"], $this->db);
82                                 }
83                         }
84                 } else {
85                         // No suitable SQL driver was found.
86                         if (!$install) {
87                                 system_unavailable();
88                         }
89                 }
90
91                 if (!$this->connected) {
92                         $this->db = null;
93                         if (!$install) {
94                                 system_unavailable();
95                         }
96                 }
97                 $a->save_timestamp($stamp1, "network");
98
99                 self::$dbo = $this;
100         }
101
102         /**
103          * @brief Returns the MySQL server version string
104          * 
105          * This function discriminate between the deprecated mysql API and the current
106          * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
107          *
108          * @return string
109          */
110         public function server_info() {
111                 if ($this->_server_info == '') {
112                         switch ($this->driver) {
113                                 case 'pdo':
114                                         $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
115                                         break;
116                                 case 'mysqli':
117                                         $this->_server_info = $this->db->server_info;
118                                         break;
119                                 case 'mysql':
120                                         $this->_server_info = mysql_get_server_info($this->db);
121                                         break;
122                         }
123                 }
124                 return $this->_server_info;
125         }
126
127         /**
128          * @brief Returns the selected database name
129          *
130          * @return string
131          */
132         public function database_name() {
133                 $r = $this->q("SELECT DATABASE() AS `db`");
134
135                 return $r[0]['db'];
136         }
137
138         /**
139          * @brief Analyze a database query and log this if some conditions are met.
140          *
141          * @param string $query The database query that will be analyzed
142          */
143         public function log_index($query) {
144                 $a = get_app();
145
146                 if ($a->config["system"]["db_log_index"] == "") {
147                         return;
148                 }
149
150                 // Don't explain an explain statement
151                 if (strtolower(substr($query, 0, 7)) == "explain") {
152                         return;
153                 }
154
155                 // Only do the explain on "select", "update" and "delete"
156                 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
157                         return;
158                 }
159
160                 $r = $this->q("EXPLAIN ".$query);
161                 if (!dbm::is_result($r)) {
162                         return;
163                 }
164
165                 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
166                 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
167
168                 foreach ($r AS $row) {
169                         if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
170                                 $log = (in_array($row['key'], $watchlist) AND
171                                         ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
172                         } else {
173                                 $log = false;
174                         }
175
176                         if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) AND ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
177                                 $log = true;
178                         }
179
180                         if (in_array($row['key'], $blacklist) OR ($row['key'] == "")) {
181                                 $log = false;
182                         }
183
184                         if ($log) {
185                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
186                                 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
187                                                 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
188                                                 basename($backtrace[1]["file"])."\t".
189                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
190                                                 substr($query, 0, 2000)."\n", FILE_APPEND);
191                         }
192                 }
193         }
194
195         public function q($sql, $onlyquery = false) {
196                 $a = get_app();
197
198                 if (!$this->db || !$this->connected) {
199                         return false;
200                 }
201
202                 $this->error = '';
203
204                 $connstr = ($this->connected() ? "Connected" : "Disonnected");
205
206                 $stamp1 = microtime(true);
207
208                 $orig_sql = $sql;
209
210                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
211                         $sql = "/*".$a->callstack()." */ ".$sql;
212                 }
213
214                 $columns = 0;
215
216                 switch ($this->driver) {
217                         case 'pdo':
218                                 $result = @$this->db->query($sql);
219                                 // Is used to separate between queries that returning data - or not
220                                 if (!is_bool($result)) {
221                                         $columns = $result->columnCount();
222                                 }
223                                 break;
224                         case 'mysqli':
225                                 $result = @$this->db->query($sql);
226                                 break;
227                         case 'mysql':
228                                 $result = @mysql_query($sql,$this->db);
229                                 break;
230                 }
231                 $stamp2 = microtime(true);
232                 $duration = (float)($stamp2 - $stamp1);
233
234                 $a->save_timestamp($stamp1, "database");
235
236                 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
237                         $a->save_timestamp($stamp1, "database_write");
238                 }
239                 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
240                         if (($duration > $a->config["system"]["db_loglimit"])) {
241                                 $duration = round($duration, 3);
242                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
243                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
244                                                 basename($backtrace[1]["file"])."\t".
245                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
246                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
247                         }
248                 }
249
250                 switch ($this->driver) {
251                         case 'pdo':
252                                 $errorInfo = $this->db->errorInfo();
253                                 if ($errorInfo) {
254                                         $this->error = $errorInfo[2];
255                                         $this->errorno = $errorInfo[1];
256                                 }
257                                 break;
258                         case 'mysqli':
259                                 if ($this->db->errno) {
260                                         $this->error = $this->db->error;
261                                         $this->errorno = $this->db->errno;
262                                 }
263                                 break;
264                         case 'mysql':
265                                 if (mysql_errno($this->db)) {
266                                         $this->error = mysql_error($this->db);
267                                         $this->errorno = mysql_errno($this->db);
268                                 }
269                                 break;
270                 }
271                 if (strlen($this->error)) {
272                         logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
273                 }
274
275                 if ($this->debug) {
276
277                         $mesg = '';
278
279                         if ($result === false) {
280                                 $mesg = 'false';
281                         } elseif ($result === true) {
282                                 $mesg = 'true';
283                         } else {
284                                 switch ($this->driver) {
285                                         case 'pdo':
286                                                 $mesg = $result->rowCount().' results'.EOL;
287                                                 break;
288                                         case 'mysqli':
289                                                 $mesg = $result->num_rows.' results'.EOL;
290                                                 break;
291                                         case 'mysql':
292                                                 $mesg = mysql_num_rows($result).' results'.EOL;
293                                                 break;
294                                 }
295                         }
296
297                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
298                                 . (($this->error) ? ' error: ' . $this->error : '')
299                                 . EOL;
300
301                         logger('dba: ' . $str );
302                 }
303
304                 /**
305                  * If dbfail.out exists, we will write any failed calls directly to it,
306                  * regardless of any logging that may or may nor be in effect.
307                  * These usually indicate SQL syntax errors that need to be resolved.
308                  */
309
310                 if ($result === false) {
311                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
312                         if (file_exists('dbfail.out')) {
313                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
314                         }
315                 }
316
317                 if (is_bool($result)) {
318                         return $result;
319                 }
320                 if ($onlyquery) {
321                         $this->result = $result;
322                         return true;
323                 }
324
325                 $r = array();
326                 switch ($this->driver) {
327                         case 'pdo':
328                                 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
329                                         $r[] = $x;
330                                 }
331                                 $result->closeCursor();
332                                 break;
333                         case 'mysqli':
334                                 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
335                                         $r[] = $x;
336                                 }
337                                 $result->free_result();
338                                 break;
339                         case 'mysql':
340                                 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
341                                         $r[] = $x;
342                                 }
343                                 mysql_free_result($result);
344                                 break;
345                 }
346
347                 // PDO doesn't return "true" on successful operations - like mysqli does
348                 // Emulate this behaviour by checking if the query returned data and had columns
349                 // This should be reliable enough
350                 if (($this->driver == 'pdo') AND (count($r) == 0) AND ($columns == 0)) {
351                         return true;
352                 }
353
354                 //$a->save_timestamp($stamp1, "database");
355
356                 if ($this->debug) {
357                         logger('dba: ' . printable(print_r($r, true)));
358                 }
359                 return($r);
360         }
361
362         public function dbg($dbg) {
363                 $this->debug = $dbg;
364         }
365
366         public function escape($str) {
367                 if ($this->db && $this->connected) {
368                         switch ($this->driver) {
369                                 case 'pdo':
370                                         return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
371                                 case 'mysqli':
372                                         return @$this->db->real_escape_string($str);
373                                 case 'mysql':
374                                         return @mysql_real_escape_string($str,$this->db);
375                         }
376                 }
377         }
378
379         function connected() {
380                 switch ($this->driver) {
381                         case 'pdo':
382                                 // Not sure if this really is working like expected
383                                 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
384                                 break;
385                         case 'mysqli':
386                                 $connected = $this->db->ping();
387                                 break;
388                         case 'mysql':
389                                 $connected = mysql_ping($this->db);
390                                 break;
391                 }
392                 return $connected;
393         }
394
395         function insert_id() {
396                 switch ($this->driver) {
397                         case 'pdo':
398                                 $id = $this->db->lastInsertId();
399                                 break;
400                         case 'mysqli':
401                                 $id = $this->db->insert_id;
402                                 break;
403                         case 'mysql':
404                                 $id = mysql_insert_id($this->db);
405                                 break;
406                 }
407                 return $id;
408         }
409
410         function __destruct() {
411                 if ($this->db) {
412                         switch ($this->driver) {
413                                 case 'pdo':
414                                         $this->db = null;
415                                         break;
416                                 case 'mysqli':
417                                         $this->db->close();
418                                         break;
419                                 case 'mysql':
420                                         mysql_close($this->db);
421                                         break;
422                         }
423                 }
424         }
425
426         /**
427          * @brief Replaces ANY_VALUE() function by MIN() function,
428          *  if the database server does not support ANY_VALUE().
429          *
430          * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
431          * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
432          * A standard fall-back is to use MIN().
433          *
434          * @param string $sql An SQL string without the values
435          * @return string The input SQL string modified if necessary.
436          */
437         public function any_value_fallback($sql) {
438                 $server_info = $this->server_info();
439                 if (version_compare($server_info, '5.7.5', '<') ||
440                         (stripos($server_info, 'MariaDB') !== false)) {
441                         $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
442                 }
443                 return $sql;
444         }
445
446         /**
447          * @brief Replaces the ? placeholders with the parameters in the $args array
448          *
449          * @param string $sql SQL query
450          * @param array $args The parameters that are to replace the ? placeholders
451          * @return string The replaced SQL query
452          */
453         static private function replace_parameters($sql, $args) {
454                 $offset = 0;
455                 foreach ($args AS $param => $value) {
456                         if (is_int($args[$param]) OR is_float($args[$param])) {
457                                 $replace = intval($args[$param]);
458                         } else {
459                                 $replace = "'".dbesc($args[$param])."'";
460                         }
461
462                         $pos = strpos($sql, '?', $offset);
463                         if ($pos !== false) {
464                                 $sql = substr_replace($sql, $replace, $pos, 1);
465                         }
466                         $offset = $pos + strlen($replace);
467                 }
468                 return $sql;
469         }
470
471         /**
472          * @brief Executes a prepared statement that returns data
473          * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
474          * @param string $sql SQL statement
475          * @return object statement object
476          */
477         static public function p($sql) {
478                 $a = get_app();
479
480                 $stamp1 = microtime(true);
481
482                 $args = func_get_args();
483                 unset($args[0]);
484
485                 if (!self::$dbo OR !self::$dbo->connected) {
486                         return false;
487                 }
488
489                 $sql = self::$dbo->any_value_fallback($sql);
490
491                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
492                         $sql = "/*".$a->callstack()." */ ".$sql;
493                 }
494
495                 self::$dbo->error = '';
496                 self::$dbo->errorno = 0;
497
498                 switch (self::$dbo->driver) {
499                         case 'pdo':
500                                 if (!$stmt = self::$dbo->db->prepare($sql)) {
501                                         $errorInfo = self::$dbo->db->errorInfo();
502                                         self::$dbo->error = $errorInfo[2];
503                                         self::$dbo->errorno = $errorInfo[1];
504                                         $retval = false;
505                                         break;
506                                 }
507
508                                 foreach ($args AS $param => $value) {
509                                         $stmt->bindParam($param, $args[$param]);
510                                 }
511
512                                 if (!$stmt->execute()) {
513                                         $errorInfo = self::$dbo->db->errorInfo();
514                                         self::$dbo->error = $errorInfo[2];
515                                         self::$dbo->errorno = $errorInfo[1];
516                                         $retval = false;
517                                 } else {
518                                         $retval = $stmt;
519                                 }
520                                 break;
521                         case 'mysqli':
522                                 $stmt = self::$dbo->db->stmt_init();
523
524                                 if (!$stmt->prepare($sql)) {
525                                         self::$dbo->error = self::$dbo->db->error;
526                                         self::$dbo->errorno = self::$dbo->db->errno;
527                                         $retval = false;
528                                         break;
529                                 }
530
531                                 $params = '';
532                                 $values = array();
533                                 foreach ($args AS $param => $value) {
534                                         if (is_int($args[$param])) {
535                                                 $params .= 'i';
536                                         } elseif (is_float($args[$param])) {
537                                                 $params .= 'd';
538                                         } elseif (is_string($args[$param])) {
539                                                 $params .= 's';
540                                         } else {
541                                                 $params .= 'b';
542                                         }
543                                         $values[] = &$args[$param];
544                                 }
545
546                                 array_unshift($values, $params);
547
548                                 call_user_func_array(array($stmt, 'bind_param'), $values);
549
550                                 if (!$stmt->execute()) {
551                                         self::$dbo->error = self::$dbo->db->error;
552                                         self::$dbo->errorno = self::$dbo->db->errno;
553                                         $retval = false;
554                                 } else {
555                                         $stmt->store_result();
556                                         $retval = $stmt;
557                                 }
558                                 break;
559                         case 'mysql':
560                                 // For the old "mysql" functions we cannot use prepared statements
561                                 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
562                                 if (mysql_errno(self::$dbo->db)) {
563                                         self::$dbo->error = mysql_error(self::$dbo->db);
564                                         self::$dbo->errorno = mysql_errno(self::$dbo->db);
565                                 }
566                                 break;
567                 }
568
569                 if (self::$dbo->errorno != 0) {
570                         logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error);
571                 }
572
573                 $a->save_timestamp($stamp1, 'database');
574
575                 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
576
577                         $stamp2 = microtime(true);
578                         $duration = (float)($stamp2 - $stamp1);
579
580                         if (($duration > $a->config["system"]["db_loglimit"])) {
581                                 $duration = round($duration, 3);
582                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
583
584                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
585                                                 basename($backtrace[1]["file"])."\t".
586                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
587                                                 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
588                         }
589                 }
590                 return $retval;
591         }
592
593         /**
594          * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
595          *
596          * @param string $sql SQL statement
597          * @return boolean Was the query successfull? False is returned only if an error occurred
598          */
599         static public function e($sql) {
600                 $a = get_app();
601
602                 $stamp = microtime(true);
603
604                 $args = func_get_args();
605
606                 $stmt = call_user_func_array('self::p', $args);
607
608                 if (is_bool($stmt)) {
609                         $retval = $stmt;
610                 } elseif (is_object($stmt)) {
611                         $retval = true;
612                 } else {
613                         $retval = false;
614                 }
615
616                 self::close($stmt);
617
618                 $a->save_timestamp($stamp, "database_write");
619
620                 return $retval;
621         }
622
623         /**
624          * @brief Check if data exists
625          *
626          * @param string $sql SQL statement
627          * @return boolean Are there rows for that query?
628          */
629         static public function exists($sql) {
630                 $args = func_get_args();
631
632                 $stmt = call_user_func_array('self::p', $args);
633
634                 if (is_bool($stmt)) {
635                         $retval = $stmt;
636                 } else {
637                         $retval = (self::num_rows($stmt) > 0);
638                 }
639
640                 self::close($stmt);
641
642                 return $retval;
643         }
644
645         /**
646          * @brief Fetches the first row
647          *
648          * @param string $sql SQL statement
649          * @return array first row of query
650          */
651         static public function fetch_first($sql) {
652                 $args = func_get_args();
653
654                 $stmt = call_user_func_array('self::p', $args);
655
656                 if (is_bool($stmt)) {
657                         $retval = $stmt;
658                 } else {
659                         $retval = self::fetch($stmt);
660                 }
661
662                 self::close($stmt);
663
664                 return $retval;
665         }
666
667         /**
668          * @brief Returns the number of rows of a statement
669          *
670          * @param object Statement object
671          * @return int Number of rows
672          */
673         static public function num_rows($stmt) {
674                 switch (self::$dbo->driver) {
675                         case 'pdo':
676                                 return $stmt->rowCount();
677                         case 'mysqli':
678                                 return $stmt->num_rows;
679                         case 'mysql':
680                                 return mysql_num_rows($stmt);
681                 }
682                 return 0;
683         }
684
685         /**
686          * @brief Fetch a single row
687          *
688          * @param object $stmt statement object
689          * @return array current row
690          */
691         static public function fetch($stmt) {
692                 if (!is_object($stmt)) {
693                         return false;
694                 }
695
696                 switch (self::$dbo->driver) {
697                         case 'pdo':
698                                 return $stmt->fetch(PDO::FETCH_ASSOC);
699                         case 'mysqli':
700                                 // This code works, but is slow
701
702                                 // Bind the result to a result array
703                                 $cols = array();
704
705                                 $cols_num = array();
706                                 for ($x = 0; $x < $stmt->field_count; $x++) {
707                                         $cols[] = &$cols_num[$x];
708                                 }
709
710                                 call_user_func_array(array($stmt, 'bind_result'), $cols);
711
712                                 if (!$stmt->fetch()) {
713                                         return false;
714                                 }
715
716                                 // The slow part:
717                                 // We need to get the field names for the array keys
718                                 // It seems that there is no better way to do this.
719                                 $result = $stmt->result_metadata();
720                                 $fields = $result->fetch_fields();
721
722                                 $columns = array();
723                                 foreach ($cols_num AS $param => $col) {
724                                         $columns[$fields[$param]->name] = $col;
725                                 }
726                                 return $columns;
727                         case 'mysql':
728                                 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
729                 }
730         }
731
732         /**
733          * @brief Insert a row into a table
734          *
735          * @param string $table Table name
736          * @param array $param parameter array
737          *
738          * @return boolean was the insert successfull?
739          */
740         static public function insert($table, $param) {
741                 $sql = "INSERT INTO `".$table."` (`".implode("`, `", array_keys($param))."`) VALUES (".
742                         substr(str_repeat("?, ", count($param)), 0, -2).");";
743
744                 $sql = self::replace_parameters($sql, $param);
745
746                 return self::e($sql);
747         }
748
749         /**
750          * @brief Closes the current statement
751          *
752          * @param object $stmt statement object
753          * @return boolean was the close successfull?
754          */
755         static public function close($stmt) {
756                 if (!is_object($stmt)) {
757                         return false;
758                 }
759
760                 switch (self::$dbo->driver) {
761                         case 'pdo':
762                                 return $stmt->closeCursor();
763                         case 'mysqli':
764                                 return $stmt->free_result();
765                                 return $stmt->close();
766                         case 'mysql':
767                                 return mysql_free_result($stmt);
768                 }
769         }
770 }
771
772 function printable($s) {
773         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
774         $s = str_replace("\x00",'.',$s);
775         if (x($_SERVER,'SERVER_NAME')) {
776                 $s = escape_tags($s);
777         }
778         return $s;
779 }
780
781 // Procedural functions
782 function dbg($state) {
783         global $db;
784
785         if ($db) {
786                 $db->dbg($state);
787         }
788 }
789
790 function dbesc($str) {
791         global $db;
792
793         if ($db && $db->connected) {
794                 return($db->escape($str));
795         } else {
796                 return(str_replace("'","\\'",$str));
797         }
798 }
799
800 // Function: q($sql,$args);
801 // Description: execute SQL query with printf style args.
802 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
803 //                   'user', 1);
804 function q($sql) {
805         global $db;
806         $args = func_get_args();
807         unset($args[0]);
808
809         if ($db && $db->connected) {
810                 $sql = $db->any_value_fallback($sql);
811                 $stmt = @vsprintf($sql,$args); // Disabled warnings
812                 //logger("dba: q: $stmt", LOGGER_ALL);
813                 if ($stmt === false)
814                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
815
816                 $db->log_index($stmt);
817
818                 return $db->q($stmt);
819         }
820
821         /**
822          *
823          * This will happen occasionally trying to store the
824          * session data after abnormal program termination
825          *
826          */
827         logger('dba: no database: ' . print_r($args,true));
828         return false;
829 }
830
831 /**
832  * @brief Performs a query with "dirty reads"
833  *
834  * By doing dirty reads (reading uncommitted data) no locks are performed
835  * This function can be used to fetch data that doesn't need to be reliable.
836  *
837  * @param $args Query parameters (1 to N parameters of different types)
838  * @return array Query array
839  */
840 function qu($sql) {
841         global $db;
842
843         $args = func_get_args();
844         unset($args[0]);
845
846         if ($db && $db->connected) {
847                 $sql = $db->any_value_fallback($sql);
848                 $stmt = @vsprintf($sql,$args); // Disabled warnings
849                 if ($stmt === false)
850                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
851
852                 $db->log_index($stmt);
853
854                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
855                 $retval = $db->q($stmt);
856                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
857                 return $retval;
858         }
859
860         /**
861          *
862          * This will happen occasionally trying to store the
863          * session data after abnormal program termination
864          *
865          */
866         logger('dba: no database: ' . print_r($args,true));
867         return false;
868 }
869
870 /**
871  *
872  * Raw db query, no arguments
873  *
874  */
875 function dbq($sql) {
876         global $db;
877
878         if ($db && $db->connected) {
879                 $ret = $db->q($sql);
880         } else {
881                 $ret = false;
882         }
883         return $ret;
884 }
885
886 // Caller is responsible for ensuring that any integer arguments to
887 // dbesc_array are actually integers and not malformed strings containing
888 // SQL injection vectors. All integer array elements should be specifically
889 // cast to int to avoid trouble.
890 function dbesc_array_cb(&$item, $key) {
891         if (is_string($item))
892                 $item = dbesc($item);
893 }
894
895 function dbesc_array(&$arr) {
896         if (is_array($arr) && count($arr)) {
897                 array_walk($arr,'dbesc_array_cb');
898         }
899 }
900
901 function dba_timer() {
902         return microtime(true);
903 }