]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Merge pull request #3569 from tobiasd/20170702-delete
[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         public  $errorno = 0;
25         public  $affected_rows = 0;
26         private $_server_info = '';
27         private static $in_transaction = false;
28         private static $dbo;
29         private static $relation = array();
30
31         function __construct($serveraddr, $user, $pass, $db, $install = false) {
32                 $a = get_app();
33
34                 $stamp1 = microtime(true);
35
36                 $serveraddr = trim($serveraddr);
37
38                 $serverdata = explode(':', $serveraddr);
39                 $server = $serverdata[0];
40
41                 if (count($serverdata) > 1) {
42                         $port = trim($serverdata[1]);
43                 }
44
45                 $server = trim($server);
46                 $user = trim($user);
47                 $pass = trim($pass);
48                 $db = trim($db);
49
50                 if (!(strlen($server) && strlen($user))) {
51                         $this->connected = false;
52                         $this->db = null;
53                         return;
54                 }
55
56                 if ($install) {
57                         if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
58                                 if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
59                                         $this->error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
60                                         $this->connected = false;
61                                         $this->db = null;
62                                         return;
63                                 }
64                         }
65                 }
66
67                 if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
68                         $this->driver = 'pdo';
69                         $connect = "mysql:host=".$server.";dbname=".$db;
70
71                         if (isset($port)) {
72                                 $connect .= ";port=".$port;
73                         }
74
75                         if (isset($a->config["system"]["db_charset"])) {
76                                 $connect .= ";charset=".$a->config["system"]["db_charset"];
77                         }
78                         $this->db = @new PDO($connect, $user, $pass);
79                         if (!$this->db->errorCode()) {
80                                 $this->connected = true;
81                         }
82                 } elseif (class_exists('mysqli')) {
83                         $this->driver = 'mysqli';
84                         $this->db = @new mysqli($server, $user, $pass, $db, $port);
85                         if (!mysqli_connect_errno()) {
86                                 $this->connected = true;
87
88                                 if (isset($a->config["system"]["db_charset"])) {
89                                         $this->db->set_charset($a->config["system"]["db_charset"]);
90                                 }
91                         }
92                 } elseif (function_exists('mysql_connect')) {
93                         $this->driver = 'mysql';
94                         $this->db = mysql_connect($serveraddr, $user, $pass);
95                         if ($this->db && mysql_select_db($db, $this->db)) {
96                                 $this->connected = true;
97
98                                 if (isset($a->config["system"]["db_charset"])) {
99                                         mysql_set_charset($a->config["system"]["db_charset"], $this->db);
100                                 }
101                         }
102                 } else {
103                         // No suitable SQL driver was found.
104                         if (!$install) {
105                                 system_unavailable();
106                         }
107                 }
108
109                 if (!$this->connected) {
110                         $this->db = null;
111                         if (!$install) {
112                                 system_unavailable();
113                         }
114                 }
115                 $a->save_timestamp($stamp1, "network");
116
117                 self::$dbo = $this;
118         }
119
120         /**
121          * @brief Returns the MySQL server version string
122          *
123          * This function discriminate between the deprecated mysql API and the current
124          * object-oriented mysqli API. Example of returned string: 5.5.46-0+deb8u1
125          *
126          * @return string
127          */
128         public function server_info() {
129                 if ($this->_server_info == '') {
130                         switch ($this->driver) {
131                                 case 'pdo':
132                                         $this->_server_info = $this->db->getAttribute(PDO::ATTR_SERVER_VERSION);
133                                         break;
134                                 case 'mysqli':
135                                         $this->_server_info = $this->db->server_info;
136                                         break;
137                                 case 'mysql':
138                                         $this->_server_info = mysql_get_server_info($this->db);
139                                         break;
140                         }
141                 }
142                 return $this->_server_info;
143         }
144
145         /**
146          * @brief Returns the selected database name
147          *
148          * @return string
149          */
150         public function database_name() {
151                 $r = $this->q("SELECT DATABASE() AS `db`");
152
153                 return $r[0]['db'];
154         }
155
156         /**
157          * @brief Analyze a database query and log this if some conditions are met.
158          *
159          * @param string $query The database query that will be analyzed
160          */
161         public function log_index($query) {
162                 $a = get_app();
163
164                 if ($a->config["system"]["db_log_index"] == "") {
165                         return;
166                 }
167
168                 // Don't explain an explain statement
169                 if (strtolower(substr($query, 0, 7)) == "explain") {
170                         return;
171                 }
172
173                 // Only do the explain on "select", "update" and "delete"
174                 if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
175                         return;
176                 }
177
178                 $r = $this->q("EXPLAIN ".$query);
179                 if (!dbm::is_result($r)) {
180                         return;
181                 }
182
183                 $watchlist = explode(',', $a->config["system"]["db_log_index_watch"]);
184                 $blacklist = explode(',', $a->config["system"]["db_log_index_blacklist"]);
185
186                 foreach ($r AS $row) {
187                         if ((intval($a->config["system"]["db_loglimit_index"]) > 0)) {
188                                 $log = (in_array($row['key'], $watchlist) &&
189                                         ($row['rows'] >= intval($a->config["system"]["db_loglimit_index"])));
190                         } else {
191                                 $log = false;
192                         }
193
194                         if ((intval($a->config["system"]["db_loglimit_index_high"]) > 0) && ($row['rows'] >= intval($a->config["system"]["db_loglimit_index_high"]))) {
195                                 $log = true;
196                         }
197
198                         if (in_array($row['key'], $blacklist) || ($row['key'] == "")) {
199                                 $log = false;
200                         }
201
202                         if ($log) {
203                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
204                                 @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
205                                                 $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
206                                                 basename($backtrace[1]["file"])."\t".
207                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
208                                                 substr($query, 0, 2000)."\n", FILE_APPEND);
209                         }
210                 }
211         }
212
213         public function q($sql, $onlyquery = false) {
214                 $a = get_app();
215
216                 if (!$this->db || !$this->connected) {
217                         return false;
218                 }
219
220                 $this->error = '';
221
222                 $connstr = ($this->connected() ? "Connected" : "Disonnected");
223
224                 $stamp1 = microtime(true);
225
226                 $orig_sql = $sql;
227
228                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
229                         $sql = "/*".$a->callstack()." */ ".$sql;
230                 }
231
232                 $columns = 0;
233
234                 switch ($this->driver) {
235                         case 'pdo':
236                                 $result = @$this->db->query($sql);
237                                 // Is used to separate between queries that returning data - or not
238                                 if (!is_bool($result)) {
239                                         $columns = $result->columnCount();
240                                 }
241                                 break;
242                         case 'mysqli':
243                                 $result = @$this->db->query($sql);
244                                 break;
245                         case 'mysql':
246                                 $result = @mysql_query($sql,$this->db);
247                                 break;
248                 }
249                 $stamp2 = microtime(true);
250                 $duration = (float)($stamp2 - $stamp1);
251
252                 $a->save_timestamp($stamp1, "database");
253
254                 if (strtolower(substr($orig_sql, 0, 6)) != "select") {
255                         $a->save_timestamp($stamp1, "database_write");
256                 }
257                 if (x($a->config,'system') && x($a->config['system'],'db_log')) {
258                         if (($duration > $a->config["system"]["db_loglimit"])) {
259                                 $duration = round($duration, 3);
260                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
261                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
262                                                 basename($backtrace[1]["file"])."\t".
263                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
264                                                 substr($sql, 0, 2000)."\n", FILE_APPEND);
265                         }
266                 }
267
268                 switch ($this->driver) {
269                         case 'pdo':
270                                 $errorInfo = $this->db->errorInfo();
271                                 if ($errorInfo) {
272                                         $this->error = $errorInfo[2];
273                                         $this->errorno = $errorInfo[1];
274                                 }
275                                 break;
276                         case 'mysqli':
277                                 if ($this->db->errno) {
278                                         $this->error = $this->db->error;
279                                         $this->errorno = $this->db->errno;
280                                 }
281                                 break;
282                         case 'mysql':
283                                 if (mysql_errno($this->db)) {
284                                         $this->error = mysql_error($this->db);
285                                         $this->errorno = mysql_errno($this->db);
286                                 }
287                                 break;
288                 }
289                 if (strlen($this->error)) {
290                         logger('DB Error ('.$connstr.') '.$this->errorno.': '.$this->error);
291                 }
292
293                 if ($this->debug) {
294
295                         $mesg = '';
296
297                         if ($result === false) {
298                                 $mesg = 'false';
299                         } elseif ($result === true) {
300                                 $mesg = 'true';
301                         } else {
302                                 switch ($this->driver) {
303                                         case 'pdo':
304                                                 $mesg = $result->rowCount().' results'.EOL;
305                                                 break;
306                                         case 'mysqli':
307                                                 $mesg = $result->num_rows.' results'.EOL;
308                                                 break;
309                                         case 'mysql':
310                                                 $mesg = mysql_num_rows($result).' results'.EOL;
311                                                 break;
312                                 }
313                         }
314
315                         $str =  'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg
316                                 . (($this->error) ? ' error: ' . $this->error : '')
317                                 . EOL;
318
319                         logger('dba: ' . $str );
320                 }
321
322                 /**
323                  * If dbfail.out exists, we will write any failed calls directly to it,
324                  * regardless of any logging that may or may nor be in effect.
325                  * These usually indicate SQL syntax errors that need to be resolved.
326                  */
327
328                 if ($result === false) {
329                         logger('dba: ' . printable($sql) . ' returned false.' . "\n" . $this->error);
330                         if (file_exists('dbfail.out')) {
331                                 file_put_contents('dbfail.out', datetime_convert() . "\n" . printable($sql) . ' returned false' . "\n" . $this->error . "\n", FILE_APPEND);
332                         }
333                 }
334
335                 if (is_bool($result)) {
336                         return $result;
337                 }
338                 if ($onlyquery) {
339                         $this->result = $result;
340                         return true;
341                 }
342
343                 $r = array();
344                 switch ($this->driver) {
345                         case 'pdo':
346                                 while ($x = $result->fetch(PDO::FETCH_ASSOC)) {
347                                         $r[] = $x;
348                                 }
349                                 $result->closeCursor();
350                                 break;
351                         case 'mysqli':
352                                 while ($x = $result->fetch_array(MYSQLI_ASSOC)) {
353                                         $r[] = $x;
354                                 }
355                                 $result->free_result();
356                                 break;
357                         case 'mysql':
358                                 while ($x = mysql_fetch_array($result, MYSQL_ASSOC)) {
359                                         $r[] = $x;
360                                 }
361                                 mysql_free_result($result);
362                                 break;
363                 }
364
365                 // PDO doesn't return "true" on successful operations - like mysqli does
366                 // Emulate this behaviour by checking if the query returned data and had columns
367                 // This should be reliable enough
368                 if (($this->driver == 'pdo') && (count($r) == 0) && ($columns == 0)) {
369                         return true;
370                 }
371
372                 //$a->save_timestamp($stamp1, "database");
373
374                 if ($this->debug) {
375                         logger('dba: ' . printable(print_r($r, true)));
376                 }
377                 return($r);
378         }
379
380         public function dbg($dbg) {
381                 $this->debug = $dbg;
382         }
383
384         public function escape($str) {
385                 if ($this->db && $this->connected) {
386                         switch ($this->driver) {
387                                 case 'pdo':
388                                         return substr(@$this->db->quote($str, PDO::PARAM_STR), 1, -1);
389                                 case 'mysqli':
390                                         return @$this->db->real_escape_string($str);
391                                 case 'mysql':
392                                         return @mysql_real_escape_string($str,$this->db);
393                         }
394                 }
395         }
396
397         function connected() {
398                 switch ($this->driver) {
399                         case 'pdo':
400                                 // Not sure if this really is working like expected
401                                 $connected = ($this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) != "");
402                                 break;
403                         case 'mysqli':
404                                 $connected = $this->db->ping();
405                                 break;
406                         case 'mysql':
407                                 $connected = mysql_ping($this->db);
408                                 break;
409                 }
410                 return $connected;
411         }
412
413         function insert_id() {
414                 switch ($this->driver) {
415                         case 'pdo':
416                                 $id = $this->db->lastInsertId();
417                                 break;
418                         case 'mysqli':
419                                 $id = $this->db->insert_id;
420                                 break;
421                         case 'mysql':
422                                 $id = mysql_insert_id($this->db);
423                                 break;
424                 }
425                 return $id;
426         }
427
428         function __destruct() {
429                 if ($this->db) {
430                         switch ($this->driver) {
431                                 case 'pdo':
432                                         $this->db = null;
433                                         break;
434                                 case 'mysqli':
435                                         $this->db->close();
436                                         break;
437                                 case 'mysql':
438                                         mysql_close($this->db);
439                                         break;
440                         }
441                 }
442         }
443
444         /**
445          * @brief Replaces ANY_VALUE() function by MIN() function,
446          *  if the database server does not support ANY_VALUE().
447          *
448          * Considerations for Standard SQL, or MySQL with ONLY_FULL_GROUP_BY (default since 5.7.5).
449          * ANY_VALUE() is available from MySQL 5.7.5 https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html
450          * A standard fall-back is to use MIN().
451          *
452          * @param string $sql An SQL string without the values
453          * @return string The input SQL string modified if necessary.
454          */
455         public function any_value_fallback($sql) {
456                 $server_info = $this->server_info();
457                 if (version_compare($server_info, '5.7.5', '<') ||
458                         (stripos($server_info, 'MariaDB') !== false)) {
459                         $sql = str_ireplace('ANY_VALUE(', 'MIN(', $sql);
460                 }
461                 return $sql;
462         }
463
464         /**
465          * @brief beautifies the query - useful for "SHOW PROCESSLIST"
466          *
467          * This is safe when we bind the parameters later.
468          * The parameter values aren't part of the SQL.
469          *
470          * @param string $sql An SQL string without the values
471          * @return string The input SQL string modified if necessary.
472          */
473         public function clean_query($sql) {
474                 $search = array("\t", "\n", "\r", "  ");
475                 $replace = array(' ', ' ', ' ', ' ');
476                 do {
477                         $oldsql = $sql;
478                         $sql = str_replace($search, $replace, $sql);
479                 } while ($oldsql != $sql);
480
481                 return $sql;
482         }
483
484
485         /**
486          * @brief Replaces the ? placeholders with the parameters in the $args array
487          *
488          * @param string $sql SQL query
489          * @param array $args The parameters that are to replace the ? placeholders
490          * @return string The replaced SQL query
491          */
492         static private function replace_parameters($sql, $args) {
493                 $offset = 0;
494                 foreach ($args AS $param => $value) {
495                         if (is_int($args[$param]) || is_float($args[$param])) {
496                                 $replace = intval($args[$param]);
497                         } else {
498                                 $replace = "'".self::$dbo->escape($args[$param])."'";
499                         }
500
501                         $pos = strpos($sql, '?', $offset);
502                         if ($pos !== false) {
503                                 $sql = substr_replace($sql, $replace, $pos, 1);
504                         }
505                         $offset = $pos + strlen($replace);
506                 }
507                 return $sql;
508         }
509
510         /**
511          * @brief Executes a prepared statement that returns data
512          * @usage Example: $r = p("SELECT * FROM `item` WHERE `guid` = ?", $guid);
513          * @param string $sql SQL statement
514          * @return object statement object
515          */
516         static public function p($sql) {
517                 $a = get_app();
518
519                 $stamp1 = microtime(true);
520
521                 $args = func_get_args();
522                 unset($args[0]);
523
524                 // When the second function parameter is an array then use this as the parameter array
525                 if ((count($args) > 0) && (is_array($args[1]))) {
526                         $params = $args[1];
527                 } else {
528                         $params = $args;
529                 }
530
531                 // Renumber the array keys to be sure that they fit
532                 $i = 0;
533                 $args = array();
534                 foreach ($params AS $param) {
535                         $args[++$i] = $param;
536                 }
537
538                 if (!self::$dbo || !self::$dbo->connected) {
539                         return false;
540                 }
541
542                 if (substr_count($sql, '?') != count($args)) {
543                         // Question: Should we continue or stop the query here?
544                         logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG);
545                 }
546
547                 $sql = self::$dbo->clean_query($sql);
548                 $sql = self::$dbo->any_value_fallback($sql);
549
550                 if (x($a->config,'system') && x($a->config['system'], 'db_callstack')) {
551                         $sql = "/*".$a->callstack()." */ ".$sql;
552                 }
553
554                 self::$dbo->error = '';
555                 self::$dbo->errorno = 0;
556                 self::$dbo->affected_rows = 0;
557
558                 switch (self::$dbo->driver) {
559                         case 'pdo':
560                                 if (!$stmt = self::$dbo->db->prepare($sql)) {
561                                         $errorInfo = self::$dbo->db->errorInfo();
562                                         self::$dbo->error = $errorInfo[2];
563                                         self::$dbo->errorno = $errorInfo[1];
564                                         $retval = false;
565                                         break;
566                                 }
567
568                                 foreach ($args AS $param => $value) {
569                                         $stmt->bindParam($param, $args[$param]);
570                                 }
571
572                                 if (!$stmt->execute()) {
573                                         $errorInfo = $stmt->errorInfo();
574                                         self::$dbo->error = $errorInfo[2];
575                                         self::$dbo->errorno = $errorInfo[1];
576                                         $retval = false;
577                                 } else {
578                                         $retval = $stmt;
579                                         self::$dbo->affected_rows = $retval->rowCount();
580                                 }
581                                 break;
582                         case 'mysqli':
583                                 $stmt = self::$dbo->db->stmt_init();
584
585                                 if (!$stmt->prepare($sql)) {
586                                         self::$dbo->error = $stmt->error;
587                                         self::$dbo->errorno = $stmt->errno;
588                                         $retval = false;
589                                         break;
590                                 }
591
592                                 $params = '';
593                                 $values = array();
594                                 foreach ($args AS $param => $value) {
595                                         if (is_int($args[$param])) {
596                                                 $params .= 'i';
597                                         } elseif (is_float($args[$param])) {
598                                                 $params .= 'd';
599                                         } elseif (is_string($args[$param])) {
600                                                 $params .= 's';
601                                         } else {
602                                                 $params .= 'b';
603                                         }
604                                         $values[] = &$args[$param];
605                                 }
606
607                                 if (count($values) > 0) {
608                                         array_unshift($values, $params);
609                                         call_user_func_array(array($stmt, 'bind_param'), $values);
610                                 }
611
612                                 if (!$stmt->execute()) {
613                                         self::$dbo->error = self::$dbo->db->error;
614                                         self::$dbo->errorno = self::$dbo->db->errno;
615                                         $retval = false;
616                                 } else {
617                                         $stmt->store_result();
618                                         $retval = $stmt;
619                                         self::$dbo->affected_rows = $retval->affected_rows;
620                                 }
621                                 break;
622                         case 'mysql':
623                                 // For the old "mysql" functions we cannot use prepared statements
624                                 $retval = mysql_query(self::replace_parameters($sql, $args), self::$dbo->db);
625                                 if (mysql_errno(self::$dbo->db)) {
626                                         self::$dbo->error = mysql_error(self::$dbo->db);
627                                         self::$dbo->errorno = mysql_errno(self::$dbo->db);
628                                 } else {
629                                         self::$dbo->affected_rows = mysql_affected_rows($retval);
630
631                                         // Due to missing mysql_* support this here wasn't tested at all
632                                         // See here: http://php.net/manual/en/function.mysql-num-rows.php
633                                         if (self::$dbo->affected_rows <= 0) {
634                                                 self::$dbo->affected_rows = mysql_num_rows($retval);
635                                         }
636                                 }
637                                 break;
638                 }
639
640                 if (self::$dbo->errorno != 0) {
641                         $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
642                         $called_from = array_shift($trace);
643
644                         // We are having an own error logging in the function "p"
645                         if ($called_from['function'] != 'p') {
646                                 // We have to preserve the error code, somewhere in the logging it get lost
647                                 $error = self::$dbo->error;
648                                 $errorno = self::$dbo->errorno;
649
650                                 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
651                                         $a->callstack(8))."\n".self::replace_parameters($sql, $args);
652
653                                 self::$dbo->error = $error;
654                                 self::$dbo->errorno = $errorno;
655                         }
656                 }
657
658                 $a->save_timestamp($stamp1, 'database');
659
660                 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
661
662                         $stamp2 = microtime(true);
663                         $duration = (float)($stamp2 - $stamp1);
664
665                         if (($duration > $a->config["system"]["db_loglimit"])) {
666                                 $duration = round($duration, 3);
667                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
668
669                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
670                                                 basename($backtrace[1]["file"])."\t".
671                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
672                                                 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
673                         }
674                 }
675                 return $retval;
676         }
677
678         /**
679          * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
680          *
681          * @param string $sql SQL statement
682          * @return boolean Was the query successfull? False is returned only if an error occurred
683          */
684         static public function e($sql) {
685                 $a = get_app();
686
687                 $stamp = microtime(true);
688
689                 $args = func_get_args();
690
691                 // In a case of a deadlock we are repeating the query 20 times
692                 $timeout = 20;
693
694                 do {
695                         $stmt = call_user_func_array('self::p', $args);
696
697                         if (is_bool($stmt)) {
698                                 $retval = $stmt;
699                         } elseif (is_object($stmt)) {
700                                 $retval = true;
701                         } else {
702                                 $retval = false;
703                         }
704
705                         self::close($stmt);
706
707                 } while ((self::$dbo->errorno == 1213) && (--$timeout > 0));
708
709                 if (self::$dbo->errorno != 0) {
710                         // We have to preserve the error code, somewhere in the logging it get lost
711                         $error = self::$dbo->error;
712                         $errorno = self::$dbo->errorno;
713
714                         logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
715                                 $a->callstack(8))."\n".self::replace_parameters($sql, $args);
716
717                         self::$dbo->error = $error;
718                         self::$dbo->errorno = $errorno;
719                 }
720
721                 $a->save_timestamp($stamp, "database_write");
722
723                 return $retval;
724         }
725
726         /**
727          * @brief Check if data exists
728          *
729          * @param string $sql SQL statement
730          * @return boolean Are there rows for that query?
731          */
732         static public function exists($sql) {
733                 $args = func_get_args();
734
735                 $stmt = call_user_func_array('self::p', $args);
736
737                 if (is_bool($stmt)) {
738                         $retval = $stmt;
739                 } else {
740                         $retval = (self::num_rows($stmt) > 0);
741                 }
742
743                 self::close($stmt);
744
745                 return $retval;
746         }
747
748         /**
749          * @brief Fetches the first row
750          *
751          * @param string $sql SQL statement
752          * @return array first row of query
753          */
754         static public function fetch_first($sql) {
755                 $args = func_get_args();
756
757                 $stmt = call_user_func_array('self::p', $args);
758
759                 if (is_bool($stmt)) {
760                         $retval = $stmt;
761                 } else {
762                         $retval = self::fetch($stmt);
763                 }
764
765                 self::close($stmt);
766
767                 return $retval;
768         }
769
770         /**
771          * @brief Returns the number of affected rows of the last statement
772          *
773          * @return int Number of rows
774          */
775         static public function affected_rows() {
776                 return self::$dbo->affected_rows;
777         }
778
779         /**
780          * @brief Returns the number of rows of a statement
781          *
782          * @param object Statement object
783          * @return int Number of rows
784          */
785         static public function num_rows($stmt) {
786                 if (!is_object($stmt)) {
787                         return 0;
788                 }
789                 switch (self::$dbo->driver) {
790                         case 'pdo':
791                                 return $stmt->rowCount();
792                         case 'mysqli':
793                                 return $stmt->num_rows;
794                         case 'mysql':
795                                 return mysql_num_rows($stmt);
796                 }
797                 return 0;
798         }
799
800         /**
801          * @brief Fetch a single row
802          *
803          * @param object $stmt statement object
804          * @return array current row
805          */
806         static public function fetch($stmt) {
807                 if (!is_object($stmt)) {
808                         return false;
809                 }
810
811                 switch (self::$dbo->driver) {
812                         case 'pdo':
813                                 return $stmt->fetch(PDO::FETCH_ASSOC);
814                         case 'mysqli':
815                                 // This code works, but is slow
816
817                                 // Bind the result to a result array
818                                 $cols = array();
819
820                                 $cols_num = array();
821                                 for ($x = 0; $x < $stmt->field_count; $x++) {
822                                         $cols[] = &$cols_num[$x];
823                                 }
824
825                                 call_user_func_array(array($stmt, 'bind_result'), $cols);
826
827                                 if (!$stmt->fetch()) {
828                                         return false;
829                                 }
830
831                                 // The slow part:
832                                 // We need to get the field names for the array keys
833                                 // It seems that there is no better way to do this.
834                                 $result = $stmt->result_metadata();
835                                 $fields = $result->fetch_fields();
836
837                                 $columns = array();
838                                 foreach ($cols_num AS $param => $col) {
839                                         $columns[$fields[$param]->name] = $col;
840                                 }
841                                 return $columns;
842                         case 'mysql':
843                                 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
844                 }
845         }
846
847         /**
848          * @brief Insert a row into a table
849          *
850          * @param string $table Table name
851          * @param array $param parameter array
852          *
853          * @return boolean was the insert successfull?
854          */
855         static public function insert($table, $param) {
856                 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
857                         substr(str_repeat("?, ", count($param)), 0, -2).");";
858
859                 return self::e($sql, $param);
860         }
861
862         /**
863          * @brief Locks a table for exclusive write access
864          *
865          * This function can be extended in the future to accept a table array as well.
866          *
867          * @param string $table Table name
868          *
869          * @return boolean was the lock successful?
870          */
871         static public function lock($table) {
872                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
873                 self::e("SET autocommit=0");
874                 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
875                 if (!$success) {
876                         self::e("SET autocommit=1");
877                 } else {
878                         self::$in_transaction = true;
879                 }
880                 return $success;
881         }
882
883         /**
884          * @brief Unlocks all locked tables
885          *
886          * @return boolean was the unlock successful?
887          */
888         static public function unlock() {
889                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
890                 self::e("COMMIT");
891                 $success = self::e("UNLOCK TABLES");
892                 self::e("SET autocommit=1");
893                 self::$in_transaction = false;
894                 return $success;
895         }
896
897         /**
898          * @brief Starts a transaction
899          *
900          * @return boolean Was the command executed successfully?
901          */
902         static public function transaction() {
903                 if (!self::e('COMMIT')) {
904                         return false;
905                 }
906                 if (!self::e('START TRANSACTION')) {
907                         return false;
908                 }
909                 self::$in_transaction = true;
910                 return true;
911         }
912
913         /**
914          * @brief Does a commit
915          *
916          * @return boolean Was the command executed successfully?
917          */
918         static public function commit() {
919                 if (!self::e('COMMIT')) {
920                         return false;
921                 }
922                 self::$in_transaction = false;
923                 return true;
924         }
925
926         /**
927          * @brief Does a rollback
928          *
929          * @return boolean Was the command executed successfully?
930          */
931         static public function rollback() {
932                 if (!self::e('ROLLBACK')) {
933                         return false;
934                 }
935                 self::$in_transaction = false;
936                 return true;
937         }
938
939         /**
940          * @brief Build the array with the table relations
941          *
942          * The array is build from the database definitions in dbstructure.php
943          *
944          * This process must only be started once, since the value is cached.
945          */
946         static private function build_relation_data() {
947                 $definition = db_definition();
948
949                 foreach ($definition AS $table => $structure) {
950                         foreach ($structure['fields'] AS $field => $field_struct) {
951                                 if (isset($field_struct['relation'])) {
952                                         foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
953                                                 self::$relation[$rel_table][$rel_field][$table][] = $field;
954                                         }
955                                 }
956                         }
957                 }
958         }
959
960         /**
961          * @brief Delete a row from a table
962          *
963          * @param string $table Table name
964          * @param array $param parameter array
965          * @param boolean $in_process Internal use: Only do a commit after the last delete
966          * @param array $callstack Internal use: prevent endless loops
967          *
968          * @return boolean|array was the delete successfull? When $in_process is set: deletion data
969          */
970         static public function delete($table, $param, $in_process = false, &$callstack = array()) {
971
972                 $commands = array();
973
974                 // Create a key for the loop prevention
975                 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
976
977                 // We quit when this key already exists in the callstack.
978                 if (isset($callstack[$key])) {
979                         return $commands;
980                 }
981
982                 $callstack[$key] = true;
983
984                 $table = self::$dbo->escape($table);
985
986                 $commands[$key] = array('table' => $table, 'param' => $param);
987
988                 // To speed up the whole process we cache the table relations
989                 if (count(self::$relation) == 0) {
990                         self::build_relation_data();
991                 }
992
993                 // Is there a relation entry for the table?
994                 if (isset(self::$relation[$table])) {
995                         // We only allow a simple "one field" relation.
996                         $field = array_keys(self::$relation[$table])[0];
997                         $rel_def = array_values(self::$relation[$table])[0];
998
999                         // Create a key for preventing double queries
1000                         $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
1001
1002                         // When the search field is the relation field, we don't need to fetch the rows
1003                         // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
1004                         if ((count($param) == 1) && ($field == array_keys($param)[0])) {
1005                                 foreach ($rel_def AS $rel_table => $rel_fields) {
1006                                         foreach ($rel_fields AS $rel_field) {
1007                                                 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
1008                                                 $commands = array_merge($commands, $retval);
1009                                         }
1010                                 }
1011                         // We quit when this key already exists in the callstack.
1012                         } elseif (!isset($callstack[$qkey])) {
1013
1014                                 $callstack[$qkey] = true;
1015
1016                                 // Fetch all rows that are to be deleted
1017                                 $sql = "SELECT ".self::$dbo->escape($field)." FROM `".$table."` WHERE `".
1018                                 implode("` = ? AND `", array_keys($param))."` = ?";
1019
1020                                 $data = self::p($sql, $param);
1021                                 while ($row = self::fetch($data)) {
1022                                         // Now we accumulate the delete commands
1023                                         $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
1024                                         $commands = array_merge($commands, $retval);
1025                                 }
1026
1027                                 // Since we had split the delete command we don't need the original command anymore
1028                                 unset($commands[$key]);
1029                         }
1030                 }
1031
1032                 if (!$in_process) {
1033                         // Now we finalize the process
1034                         $do_transaction = !self::$in_transaction;
1035
1036                         if ($do_transaction) {
1037                                 self::transaction();
1038                         }
1039
1040                         $compacted = array();
1041                         $counter = array();
1042                         foreach ($commands AS $command) {
1043                                 if (count($command['param']) > 1) {
1044                                         $sql = "DELETE FROM `".$command['table']."` WHERE `".
1045                                                 implode("` = ? AND `", array_keys($command['param']))."` = ?";
1046
1047                                         logger(self::replace_parameters($sql, $command['param']), LOGGER_DATA);
1048
1049                                         if (!self::e($sql, $command['param'])) {
1050                                                 if ($do_transaction) {
1051                                                         self::rollback();
1052                                                 }
1053                                                 return false;
1054                                         }
1055                                 } else {
1056                                         $key_table = $command['table'];
1057                                         $key_param = array_keys($command['param'])[0];
1058                                         $value = array_values($command['param'])[0];
1059
1060                                         // Split the SQL queries in chunks of 100 values
1061                                         // We do the $i stuff here to make the code better readable
1062                                         $i = $counter[$key_table][$key_param];
1063                                         if (count($compacted[$key_table][$key_param][$i]) > 100) {
1064                                                 ++$i;
1065                                         }
1066
1067                                         $compacted[$key_table][$key_param][$i][$value] = $value;
1068                                         $counter[$key_table][$key_param] = $i;
1069                                 }
1070                         }
1071                         foreach ($compacted AS $table => $values) {
1072                                 foreach ($values AS $field => $field_value_list) {
1073                                         foreach ($field_value_list AS $field_values) {
1074                                                 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1075                                                         substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1076
1077                                                 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
1078
1079                                                 if (!self::e($sql, $field_values)) {
1080                                                         if ($do_transaction) {
1081                                                                 self::rollback();
1082                                                         }
1083                                                         return false;
1084                                                 }
1085                                         }
1086                                 }
1087                         }
1088                         if ($do_transaction) {
1089                                 self::commit();
1090                         }
1091                         return true;
1092                 }
1093
1094                 return $commands;
1095         }
1096
1097         /**
1098          * @brief Updates rows
1099          *
1100          * Updates rows in the database. When $old_fields is set to an array,
1101          * the system will only do an update if the fields in that array changed.
1102          *
1103          * Attention:
1104          * Only the values in $old_fields are compared.
1105          * This is an intentional behaviour.
1106          *
1107          * Example:
1108          * We include the timestamp field in $fields but not in $old_fields.
1109          * Then the row will only get the new timestamp when the other fields had changed.
1110          *
1111          * When $old_fields is set to a boolean value the system will do this compare itself.
1112          * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1113          *
1114          * Attention:
1115          * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1116          * When you set $old_fields to "true" then $fields must contain all relevant fields!
1117          *
1118          * @param string $table Table name
1119          * @param array $fields contains the fields that are updated
1120          * @param array $condition condition array with the key values
1121          * @param array|boolean $old_fields array with the old field values that are about to be replaced
1122          *
1123          * @return boolean was the update successfull?
1124          */
1125         static public function update($table, $fields, $condition, $old_fields = array()) {
1126
1127                 /** @todo We may use MySQL specific functions here:
1128                  * INSERT INTO `config` (`cat`, `k`, `v`) VALUES ('%s', '%s', '%s') ON DUPLICATE KEY UPDATE `v` = '%s'"
1129                  * But I think that it doesn't make sense here.
1130                 */
1131
1132                 $table = self::$dbo->escape($table);
1133
1134                 if (is_bool($old_fields)) {
1135                         $sql = "SELECT * FROM `".$table."` WHERE `".
1136                         implode("` = ? AND `", array_keys($condition))."` = ? LIMIT 1";
1137
1138                         $params = array();
1139                         foreach ($condition AS $value) {
1140                                 $params[] = $value;
1141                         }
1142
1143                         $do_insert = $old_fields;
1144
1145                         $old_fields = self::fetch_first($sql, $params);
1146                         if (is_bool($old_fields)) {
1147                                 if ($do_insert) {
1148                                         return self::insert($table, $fields);
1149                                 }
1150                                 $old_fields = array();
1151                         }
1152                 }
1153
1154                 $do_update = (count($old_fields) == 0);
1155
1156                 foreach ($old_fields AS $fieldname => $content) {
1157                         if (isset($fields[$fieldname])) {
1158                                 if ($fields[$fieldname] == $content) {
1159                                         unset($fields[$fieldname]);
1160                                 } else {
1161                                         $do_update = true;
1162                                 }
1163                         }
1164                 }
1165
1166                 if (!$do_update || (count($fields) == 0)) {
1167                         return true;
1168                 }
1169
1170                 $sql = "UPDATE `".$table."` SET `".
1171                         implode("` = ?, `", array_keys($fields))."` = ? WHERE `".
1172                         implode("` = ? AND `", array_keys($condition))."` = ?";
1173
1174                 $params = array();
1175                 foreach ($fields AS $value) {
1176                         $params[] = $value;
1177                 }
1178                 foreach ($condition AS $value) {
1179                         $params[] = $value;
1180                 }
1181
1182                 return self::e($sql, $params);
1183         }
1184
1185         /**
1186          * @brief Select rows from a table
1187          *
1188          * @param string $table Table name
1189          * @param array $fields array of selected fields
1190          * @param array $condition array of fields for condition
1191          * @param array $params array of several parameters
1192          *
1193          * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1194          *
1195          * Example:
1196          * $table = "item";
1197          * $fields = array("id", "uri", "uid", "network");
1198          * $condition = array("uid" => 1, "network" => 'dspr');
1199          * $params = array("order" => array("id", "received" => true), "limit" => 1);
1200          *
1201          * $data = dba::select($table, $fields, $condition, $params);
1202          */
1203         static public function select($table, $fields = array(), $condition = array(), $params = array()) {
1204                 if ($table == '') {
1205                         return false;
1206                 }
1207
1208                 if (count($fields) > 0) {
1209                         $select_fields = "`".implode("`, `", array_values($fields))."`";
1210                 } else {
1211                         $select_fields = "*";
1212                 }
1213
1214                 if (count($condition) > 0) {
1215                         $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1216                 } else {
1217                         $condition_string = "";
1218                 }
1219
1220                 $param_string = '';
1221                 $single_row = false;
1222
1223                 if (isset($params['order'])) {
1224                         $param_string .= " ORDER BY ";
1225                         foreach ($params['order'] AS $fields => $order) {
1226                                 if (!is_int($fields)) {
1227                                         $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1228                                 } else {
1229                                         $param_string .= "`".$order."`, ";
1230                                 }
1231                         }
1232                         $param_string = substr($param_string, 0, -2);
1233                 }
1234
1235                 if (isset($params['limit'])) {
1236                         if (is_int($params['limit'])) {
1237                                 $param_string .= " LIMIT ".$params['limit'];
1238                                 $single_row =($params['limit'] == 1);
1239                         }
1240                 }
1241
1242                 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1243
1244                 $result = self::p($sql, $condition);
1245
1246                 if (is_bool($result) || !$single_row) {
1247                         return $result;
1248                 } else {
1249                         $row = self::fetch($result);
1250                         self::close($result);
1251                         return $row;
1252                 }
1253         }
1254
1255         /**
1256          * @brief Closes the current statement
1257          *
1258          * @param object $stmt statement object
1259          * @return boolean was the close successfull?
1260          */
1261         static public function close($stmt) {
1262                 if (!is_object($stmt)) {
1263                         return false;
1264                 }
1265
1266                 switch (self::$dbo->driver) {
1267                         case 'pdo':
1268                                 return $stmt->closeCursor();
1269                         case 'mysqli':
1270                                 return $stmt->free_result();
1271                                 return $stmt->close();
1272                         case 'mysql':
1273                                 return mysql_free_result($stmt);
1274                 }
1275         }
1276 }
1277
1278 function printable($s) {
1279         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
1280         $s = str_replace("\x00",'.',$s);
1281         if (x($_SERVER,'SERVER_NAME')) {
1282                 $s = escape_tags($s);
1283         }
1284         return $s;
1285 }
1286
1287 // Procedural functions
1288 function dbg($state) {
1289         global $db;
1290
1291         if ($db) {
1292                 $db->dbg($state);
1293         }
1294 }
1295
1296 function dbesc($str) {
1297         global $db;
1298
1299         if ($db && $db->connected) {
1300                 return($db->escape($str));
1301         } else {
1302                 return(str_replace("'","\\'",$str));
1303         }
1304 }
1305
1306 // Function: q($sql,$args);
1307 // Description: execute SQL query with printf style args.
1308 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
1309 //                   'user', 1);
1310 function q($sql) {
1311         global $db;
1312         $args = func_get_args();
1313         unset($args[0]);
1314
1315         if ($db && $db->connected) {
1316                 $sql = $db->clean_query($sql);
1317                 $sql = $db->any_value_fallback($sql);
1318                 $stmt = @vsprintf($sql,$args); // Disabled warnings
1319                 //logger("dba: q: $stmt", LOGGER_ALL);
1320                 if ($stmt === false)
1321                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1322
1323                 $db->log_index($stmt);
1324
1325                 return $db->q($stmt);
1326         }
1327
1328         /**
1329          *
1330          * This will happen occasionally trying to store the
1331          * session data after abnormal program termination
1332          *
1333          */
1334         logger('dba: no database: ' . print_r($args,true));
1335         return false;
1336 }
1337
1338 /**
1339  * @brief Performs a query with "dirty reads"
1340  *
1341  * By doing dirty reads (reading uncommitted data) no locks are performed
1342  * This function can be used to fetch data that doesn't need to be reliable.
1343  *
1344  * @param $args Query parameters (1 to N parameters of different types)
1345  * @return array Query array
1346  */
1347 function qu($sql) {
1348         global $db;
1349
1350         $args = func_get_args();
1351         unset($args[0]);
1352
1353         if ($db && $db->connected) {
1354                 $sql = $db->clean_query($sql);
1355                 $sql = $db->any_value_fallback($sql);
1356                 $stmt = @vsprintf($sql,$args); // Disabled warnings
1357                 if ($stmt === false)
1358                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1359
1360                 $db->log_index($stmt);
1361
1362                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
1363                 $retval = $db->q($stmt);
1364                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
1365                 return $retval;
1366         }
1367
1368         /**
1369          *
1370          * This will happen occasionally trying to store the
1371          * session data after abnormal program termination
1372          *
1373          */
1374         logger('dba: no database: ' . print_r($args,true));
1375         return false;
1376 }
1377
1378 /**
1379  *
1380  * Raw db query, no arguments
1381  *
1382  */
1383 function dbq($sql) {
1384         global $db;
1385
1386         if ($db && $db->connected) {
1387                 $ret = $db->q($sql);
1388         } else {
1389                 $ret = false;
1390         }
1391         return $ret;
1392 }
1393
1394 // Caller is responsible for ensuring that any integer arguments to
1395 // dbesc_array are actually integers and not malformed strings containing
1396 // SQL injection vectors. All integer array elements should be specifically
1397 // cast to int to avoid trouble.
1398 function dbesc_array_cb(&$item, $key) {
1399         if (is_string($item))
1400                 $item = dbesc($item);
1401 }
1402
1403 function dbesc_array(&$arr) {
1404         if (is_array($arr) && count($arr)) {
1405                 array_walk($arr,'dbesc_array_cb');
1406         }
1407 }
1408
1409 function dba_timer() {
1410         return microtime(true);
1411 }