]> git.mxchange.org Git - friendica.git/blob - include/dba.php
There is now a memory limit for the poller
[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 = "'".self::$dbo->escape($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                 // When the second function parameter is an array then use this as the parameter array
486                 if ((count($args) == 1) AND (is_array($args[1]))) {
487                         $params = $args[1];
488                         $i = 0;
489                         foreach ($params AS $param) {
490                                 $args[++$i] = $param;
491                         }
492                 }
493
494                 if (!self::$dbo OR !self::$dbo->connected) {
495                         return false;
496                 }
497
498                 $sql = self::$dbo->any_value_fallback($sql);
499
500                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
501                         $sql = "/*".$a->callstack()." */ ".$sql;
502                 }
503
504                 self::$dbo->error = '';
505                 self::$dbo->errorno = 0;
506
507                 switch (self::$dbo->driver) {
508                         case 'pdo':
509                                 if (!$stmt = self::$dbo->db->prepare($sql)) {
510                                         $errorInfo = self::$dbo->db->errorInfo();
511                                         self::$dbo->error = $errorInfo[2];
512                                         self::$dbo->errorno = $errorInfo[1];
513                                         $retval = false;
514                                         break;
515                                 }
516
517                                 foreach ($args AS $param => $value) {
518                                         $stmt->bindParam($param, $args[$param]);
519                                 }
520
521                                 if (!$stmt->execute()) {
522                                         $errorInfo = self::$dbo->db->errorInfo();
523                                         self::$dbo->error = $errorInfo[2];
524                                         self::$dbo->errorno = $errorInfo[1];
525                                         $retval = false;
526                                 } else {
527                                         $retval = $stmt;
528                                 }
529                                 break;
530                         case 'mysqli':
531                                 $stmt = self::$dbo->db->stmt_init();
532
533                                 if (!$stmt->prepare($sql)) {
534                                         self::$dbo->error = self::$dbo->db->error;
535                                         self::$dbo->errorno = self::$dbo->db->errno;
536                                         $retval = false;
537                                         break;
538                                 }
539
540                                 $params = '';
541                                 $values = array();
542                                 foreach ($args AS $param => $value) {
543                                         if (is_int($args[$param])) {
544                                                 $params .= 'i';
545                                         } elseif (is_float($args[$param])) {
546                                                 $params .= 'd';
547                                         } elseif (is_string($args[$param])) {
548                                                 $params .= 's';
549                                         } else {
550                                                 $params .= 'b';
551                                         }
552                                         $values[] = &$args[$param];
553                                 }
554
555                                 array_unshift($values, $params);
556
557                                 call_user_func_array(array($stmt, 'bind_param'), $values);
558
559                                 if (!$stmt->execute()) {
560                                         self::$dbo->error = self::$dbo->db->error;
561                                         self::$dbo->errorno = self::$dbo->db->errno;
562                                         $retval = false;
563                                 } else {
564                                         $stmt->store_result();
565                                         $retval = $stmt;
566                                 }
567                                 break;
568                         case 'mysql':
569                                 // For the old "mysql" functions we cannot use prepared statements
570                                 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
571                                 if (mysql_errno(self::$dbo->db)) {
572                                         self::$dbo->error = mysql_error(self::$dbo->db);
573                                         self::$dbo->errorno = mysql_errno(self::$dbo->db);
574                                 }
575                                 break;
576                 }
577
578                 if (self::$dbo->errorno != 0) {
579                         logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error);
580                 }
581
582                 $a->save_timestamp($stamp1, 'database');
583
584                 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
585
586                         $stamp2 = microtime(true);
587                         $duration = (float)($stamp2 - $stamp1);
588
589                         if (($duration > $a->config["system"]["db_loglimit"])) {
590                                 $duration = round($duration, 3);
591                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
592
593                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
594                                                 basename($backtrace[1]["file"])."\t".
595                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
596                                                 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
597                         }
598                 }
599                 return $retval;
600         }
601
602         /**
603          * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
604          *
605          * @param string $sql SQL statement
606          * @return boolean Was the query successfull? False is returned only if an error occurred
607          */
608         static public function e($sql) {
609                 $a = get_app();
610
611                 $stamp = microtime(true);
612
613                 $args = func_get_args();
614
615                 $stmt = call_user_func_array('self::p', $args);
616
617                 if (is_bool($stmt)) {
618                         $retval = $stmt;
619                 } elseif (is_object($stmt)) {
620                         $retval = true;
621                 } else {
622                         $retval = false;
623                 }
624
625                 self::close($stmt);
626
627                 $a->save_timestamp($stamp, "database_write");
628
629                 return $retval;
630         }
631
632         /**
633          * @brief Check if data exists
634          *
635          * @param string $sql SQL statement
636          * @return boolean Are there rows for that query?
637          */
638         static public function exists($sql) {
639                 $args = func_get_args();
640
641                 $stmt = call_user_func_array('self::p', $args);
642
643                 if (is_bool($stmt)) {
644                         $retval = $stmt;
645                 } else {
646                         $retval = (self::num_rows($stmt) > 0);
647                 }
648
649                 self::close($stmt);
650
651                 return $retval;
652         }
653
654         /**
655          * @brief Fetches the first row
656          *
657          * @param string $sql SQL statement
658          * @return array first row of query
659          */
660         static public function fetch_first($sql) {
661                 $args = func_get_args();
662
663                 $stmt = call_user_func_array('self::p', $args);
664
665                 if (is_bool($stmt)) {
666                         $retval = $stmt;
667                 } else {
668                         $retval = self::fetch($stmt);
669                 }
670
671                 self::close($stmt);
672
673                 return $retval;
674         }
675
676         /**
677          * @brief Returns the number of rows of a statement
678          *
679          * @param object Statement object
680          * @return int Number of rows
681          */
682         static public function num_rows($stmt) {
683                 switch (self::$dbo->driver) {
684                         case 'pdo':
685                                 return $stmt->rowCount();
686                         case 'mysqli':
687                                 return $stmt->num_rows;
688                         case 'mysql':
689                                 return mysql_num_rows($stmt);
690                 }
691                 return 0;
692         }
693
694         /**
695          * @brief Fetch a single row
696          *
697          * @param object $stmt statement object
698          * @return array current row
699          */
700         static public function fetch($stmt) {
701                 if (!is_object($stmt)) {
702                         return false;
703                 }
704
705                 switch (self::$dbo->driver) {
706                         case 'pdo':
707                                 return $stmt->fetch(PDO::FETCH_ASSOC);
708                         case 'mysqli':
709                                 // This code works, but is slow
710
711                                 // Bind the result to a result array
712                                 $cols = array();
713
714                                 $cols_num = array();
715                                 for ($x = 0; $x < $stmt->field_count; $x++) {
716                                         $cols[] = &$cols_num[$x];
717                                 }
718
719                                 call_user_func_array(array($stmt, 'bind_result'), $cols);
720
721                                 if (!$stmt->fetch()) {
722                                         return false;
723                                 }
724
725                                 // The slow part:
726                                 // We need to get the field names for the array keys
727                                 // It seems that there is no better way to do this.
728                                 $result = $stmt->result_metadata();
729                                 $fields = $result->fetch_fields();
730
731                                 $columns = array();
732                                 foreach ($cols_num AS $param => $col) {
733                                         $columns[$fields[$param]->name] = $col;
734                                 }
735                                 return $columns;
736                         case 'mysql':
737                                 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
738                 }
739         }
740
741         /**
742          * @brief Insert a row into a table
743          *
744          * @param string $table Table name
745          * @param array $param parameter array
746          *
747          * @return boolean was the insert successfull?
748          */
749         static public function insert($table, $param) {
750                 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
751                         substr(str_repeat("?, ", count($param)), 0, -2).");";
752
753                 return self::e($sql, $param);
754         }
755
756         /**
757          * @brief Updates rows
758          *
759          * @param string $table Table name
760          * @param array $fields contains the fields that are updated
761          * @param array $condition condition array with the key values
762          *
763          * @return boolean was the update successfull?
764          */
765         static public function update($table, $fields, $condition) {
766
767                 $sql = "UPDATE `".self::$dbo->escape($table)."` SET `".
768                         implode("` = ?, `", array_keys($fields))."` = ? WHERE `".
769                         implode("` = ? AND `", array_keys($condition))."` = ?";
770
771                 $params = array();
772                 foreach ($fields AS $value) {
773                         $params[] = $value;
774                 }
775                 foreach ($condition AS $value) {
776                         $params[] = $value;
777                 }
778
779                 return self::e($sql, $params);
780         }
781
782         /**
783          * @brief Closes the current statement
784          *
785          * @param object $stmt statement object
786          * @return boolean was the close successfull?
787          */
788         static public function close($stmt) {
789                 if (!is_object($stmt)) {
790                         return false;
791                 }
792
793                 switch (self::$dbo->driver) {
794                         case 'pdo':
795                                 return $stmt->closeCursor();
796                         case 'mysqli':
797                                 return $stmt->free_result();
798                                 return $stmt->close();
799                         case 'mysql':
800                                 return mysql_free_result($stmt);
801                 }
802         }
803 }
804
805 function printable($s) {
806         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
807         $s = str_replace("\x00",'.',$s);
808         if (x($_SERVER,'SERVER_NAME')) {
809                 $s = escape_tags($s);
810         }
811         return $s;
812 }
813
814 // Procedural functions
815 function dbg($state) {
816         global $db;
817
818         if ($db) {
819                 $db->dbg($state);
820         }
821 }
822
823 function dbesc($str) {
824         global $db;
825
826         if ($db && $db->connected) {
827                 return($db->escape($str));
828         } else {
829                 return(str_replace("'","\\'",$str));
830         }
831 }
832
833 // Function: q($sql,$args);
834 // Description: execute SQL query with printf style args.
835 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
836 //                   'user', 1);
837 function q($sql) {
838         global $db;
839         $args = func_get_args();
840         unset($args[0]);
841
842         if ($db && $db->connected) {
843                 $sql = $db->any_value_fallback($sql);
844                 $stmt = @vsprintf($sql,$args); // Disabled warnings
845                 //logger("dba: q: $stmt", LOGGER_ALL);
846                 if ($stmt === false)
847                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
848
849                 $db->log_index($stmt);
850
851                 return $db->q($stmt);
852         }
853
854         /**
855          *
856          * This will happen occasionally trying to store the
857          * session data after abnormal program termination
858          *
859          */
860         logger('dba: no database: ' . print_r($args,true));
861         return false;
862 }
863
864 /**
865  * @brief Performs a query with "dirty reads"
866  *
867  * By doing dirty reads (reading uncommitted data) no locks are performed
868  * This function can be used to fetch data that doesn't need to be reliable.
869  *
870  * @param $args Query parameters (1 to N parameters of different types)
871  * @return array Query array
872  */
873 function qu($sql) {
874         global $db;
875
876         $args = func_get_args();
877         unset($args[0]);
878
879         if ($db && $db->connected) {
880                 $sql = $db->any_value_fallback($sql);
881                 $stmt = @vsprintf($sql,$args); // Disabled warnings
882                 if ($stmt === false)
883                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
884
885                 $db->log_index($stmt);
886
887                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
888                 $retval = $db->q($stmt);
889                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
890                 return $retval;
891         }
892
893         /**
894          *
895          * This will happen occasionally trying to store the
896          * session data after abnormal program termination
897          *
898          */
899         logger('dba: no database: ' . print_r($args,true));
900         return false;
901 }
902
903 /**
904  *
905  * Raw db query, no arguments
906  *
907  */
908 function dbq($sql) {
909         global $db;
910
911         if ($db && $db->connected) {
912                 $ret = $db->q($sql);
913         } else {
914                 $ret = false;
915         }
916         return $ret;
917 }
918
919 // Caller is responsible for ensuring that any integer arguments to
920 // dbesc_array are actually integers and not malformed strings containing
921 // SQL injection vectors. All integer array elements should be specifically
922 // cast to int to avoid trouble.
923 function dbesc_array_cb(&$item, $key) {
924         if (is_string($item))
925                 $item = dbesc($item);
926 }
927
928 function dbesc_array(&$arr) {
929         if (is_array($arr) && count($arr)) {
930                 array_walk($arr,'dbesc_array_cb');
931         }
932 }
933
934 function dba_timer() {
935         return microtime(true);
936 }