]> git.mxchange.org Git - friendica.git/blob - include/dba.php
New function for affected rows
[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                                 break;
632                 }
633
634                 if (self::$dbo->errorno != 0) {
635                         $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
636                         $called_from = array_shift($trace);
637
638                         // We are having an own error logging in the function "p"
639                         if ($called_from['function'] != 'p') {
640                                 // We have to preserve the error code, somewhere in the logging it get lost
641                                 $error = self::$dbo->error;
642                                 $errorno = self::$dbo->errorno;
643
644                                 logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
645                                         $a->callstack(8))."\n".self::replace_parameters($sql, $args);
646
647                                 self::$dbo->error = $error;
648                                 self::$dbo->errorno = $errorno;
649                         }
650                 }
651
652                 $a->save_timestamp($stamp1, 'database');
653
654                 if (x($a->config,'system') && x($a->config['system'], 'db_log')) {
655
656                         $stamp2 = microtime(true);
657                         $duration = (float)($stamp2 - $stamp1);
658
659                         if (($duration > $a->config["system"]["db_loglimit"])) {
660                                 $duration = round($duration, 3);
661                                 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
662
663                                 @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
664                                                 basename($backtrace[1]["file"])."\t".
665                                                 $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
666                                                 substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
667                         }
668                 }
669                 return $retval;
670         }
671
672         /**
673          * @brief Executes a prepared statement like UPDATE or INSERT that doesn't return data
674          *
675          * @param string $sql SQL statement
676          * @return boolean Was the query successfull? False is returned only if an error occurred
677          */
678         static public function e($sql) {
679                 $a = get_app();
680
681                 $stamp = microtime(true);
682
683                 $args = func_get_args();
684
685                 // In a case of a deadlock we are repeating the query 20 times
686                 $timeout = 20;
687
688                 do {
689                         $stmt = call_user_func_array('self::p', $args);
690
691                         if (is_bool($stmt)) {
692                                 $retval = $stmt;
693                         } elseif (is_object($stmt)) {
694                                 $retval = true;
695                         } else {
696                                 $retval = false;
697                         }
698
699                         self::close($stmt);
700
701                 } while ((self::$dbo->errorno == 1213) && (--$timeout > 0));
702
703                 if (self::$dbo->errorno != 0) {
704                         // We have to preserve the error code, somewhere in the logging it get lost
705                         $error = self::$dbo->error;
706                         $errorno = self::$dbo->errorno;
707
708                         logger('DB Error '.self::$dbo->errorno.': '.self::$dbo->error."\n".
709                                 $a->callstack(8))."\n".self::replace_parameters($sql, $args);
710
711                         self::$dbo->error = $error;
712                         self::$dbo->errorno = $errorno;
713                 }
714
715                 $a->save_timestamp($stamp, "database_write");
716
717                 return $retval;
718         }
719
720         /**
721          * @brief Check if data exists
722          *
723          * @param string $sql SQL statement
724          * @return boolean Are there rows for that query?
725          */
726         static public function exists($sql) {
727                 $args = func_get_args();
728
729                 $stmt = call_user_func_array('self::p', $args);
730
731                 if (is_bool($stmt)) {
732                         $retval = $stmt;
733                 } else {
734                         $retval = (self::num_rows($stmt) > 0);
735                 }
736
737                 self::close($stmt);
738
739                 return $retval;
740         }
741
742         /**
743          * @brief Fetches the first row
744          *
745          * @param string $sql SQL statement
746          * @return array first row of query
747          */
748         static public function fetch_first($sql) {
749                 $args = func_get_args();
750
751                 $stmt = call_user_func_array('self::p', $args);
752
753                 if (is_bool($stmt)) {
754                         $retval = $stmt;
755                 } else {
756                         $retval = self::fetch($stmt);
757                 }
758
759                 self::close($stmt);
760
761                 return $retval;
762         }
763
764         /**
765          * @brief Returns the number of affected rows of the last statement
766          *
767          * @return int Number of rows
768          */
769         static public function affected_rows() {
770                 return self::$dbo->affected_rows;
771         }
772
773         /**
774          * @brief Returns the number of rows of a statement
775          *
776          * @param object Statement object
777          * @return int Number of rows
778          */
779         static public function num_rows($stmt) {
780                 if (!is_object($stmt)) {
781                         return 0;
782                 }
783                 switch (self::$dbo->driver) {
784                         case 'pdo':
785                                 return $stmt->rowCount();
786                         case 'mysqli':
787                                 return $stmt->num_rows;
788                         case 'mysql':
789                                 return mysql_num_rows($stmt);
790                 }
791                 return 0;
792         }
793
794         /**
795          * @brief Fetch a single row
796          *
797          * @param object $stmt statement object
798          * @return array current row
799          */
800         static public function fetch($stmt) {
801                 if (!is_object($stmt)) {
802                         return false;
803                 }
804
805                 switch (self::$dbo->driver) {
806                         case 'pdo':
807                                 return $stmt->fetch(PDO::FETCH_ASSOC);
808                         case 'mysqli':
809                                 // This code works, but is slow
810
811                                 // Bind the result to a result array
812                                 $cols = array();
813
814                                 $cols_num = array();
815                                 for ($x = 0; $x < $stmt->field_count; $x++) {
816                                         $cols[] = &$cols_num[$x];
817                                 }
818
819                                 call_user_func_array(array($stmt, 'bind_result'), $cols);
820
821                                 if (!$stmt->fetch()) {
822                                         return false;
823                                 }
824
825                                 // The slow part:
826                                 // We need to get the field names for the array keys
827                                 // It seems that there is no better way to do this.
828                                 $result = $stmt->result_metadata();
829                                 $fields = $result->fetch_fields();
830
831                                 $columns = array();
832                                 foreach ($cols_num AS $param => $col) {
833                                         $columns[$fields[$param]->name] = $col;
834                                 }
835                                 return $columns;
836                         case 'mysql':
837                                 return mysql_fetch_array(self::$dbo->result, MYSQL_ASSOC);
838                 }
839         }
840
841         /**
842          * @brief Insert a row into a table
843          *
844          * @param string $table Table name
845          * @param array $param parameter array
846          *
847          * @return boolean was the insert successfull?
848          */
849         static public function insert($table, $param) {
850                 $sql = "INSERT INTO `".self::$dbo->escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
851                         substr(str_repeat("?, ", count($param)), 0, -2).");";
852
853                 return self::e($sql, $param);
854         }
855
856         /**
857          * @brief Locks a table for exclusive write access
858          *
859          * This function can be extended in the future to accept a table array as well.
860          *
861          * @param string $table Table name
862          *
863          * @return boolean was the lock successful?
864          */
865         static public function lock($table) {
866                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
867                 self::e("SET autocommit=0");
868                 $success = self::e("LOCK TABLES `".self::$dbo->escape($table)."` WRITE");
869                 if (!$success) {
870                         self::e("SET autocommit=1");
871                 } else {
872                         self::$in_transaction = true;
873                 }
874                 return $success;
875         }
876
877         /**
878          * @brief Unlocks all locked tables
879          *
880          * @return boolean was the unlock successful?
881          */
882         static public function unlock() {
883                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
884                 self::e("COMMIT");
885                 $success = self::e("UNLOCK TABLES");
886                 self::e("SET autocommit=1");
887                 self::$in_transaction = false;
888                 return $success;
889         }
890
891         /**
892          * @brief Starts a transaction
893          *
894          * @return boolean Was the command executed successfully?
895          */
896         static public function transaction() {
897                 if (!self::e('COMMIT')) {
898                         return false;
899                 }
900                 if (!self::e('START TRANSACTION')) {
901                         return false;
902                 }
903                 self::$in_transaction = true;
904                 return true;
905         }
906
907         /**
908          * @brief Does a commit
909          *
910          * @return boolean Was the command executed successfully?
911          */
912         static public function commit() {
913                 if (!self::e('COMMIT')) {
914                         return false;
915                 }
916                 self::$in_transaction = false;
917                 return true;
918         }
919
920         /**
921          * @brief Does a rollback
922          *
923          * @return boolean Was the command executed successfully?
924          */
925         static public function rollback() {
926                 if (!self::e('ROLLBACK')) {
927                         return false;
928                 }
929                 self::$in_transaction = false;
930                 return true;
931         }
932
933         /**
934          * @brief Build the array with the table relations
935          *
936          * The array is build from the database definitions in dbstructure.php
937          *
938          * This process must only be started once, since the value is cached.
939          */
940         static private function build_relation_data() {
941                 $definition = db_definition();
942
943                 foreach ($definition AS $table => $structure) {
944                         foreach ($structure['fields'] AS $field => $field_struct) {
945                                 if (isset($field_struct['relation'])) {
946                                         foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
947                                                 self::$relation[$rel_table][$rel_field][$table][] = $field;
948                                         }
949                                 }
950                         }
951                 }
952         }
953
954         /**
955          * @brief Delete a row from a table
956          *
957          * @param string $table Table name
958          * @param array $param parameter array
959          * @param boolean $in_process Internal use: Only do a commit after the last delete
960          * @param array $callstack Internal use: prevent endless loops
961          *
962          * @return boolean|array was the delete successfull? When $in_process is set: deletion data
963          */
964         static public function delete($table, $param, $in_process = false, &$callstack = array()) {
965
966                 $commands = array();
967
968                 // Create a key for the loop prevention
969                 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
970
971                 // We quit when this key already exists in the callstack.
972                 if (isset($callstack[$key])) {
973                         return $commands;
974                 }
975
976                 $callstack[$key] = true;
977
978                 $table = self::$dbo->escape($table);
979
980                 $commands[$key] = array('table' => $table, 'param' => $param);
981
982                 // To speed up the whole process we cache the table relations
983                 if (count(self::$relation) == 0) {
984                         self::build_relation_data();
985                 }
986
987                 // Is there a relation entry for the table?
988                 if (isset(self::$relation[$table])) {
989                         // We only allow a simple "one field" relation.
990                         $field = array_keys(self::$relation[$table])[0];
991                         $rel_def = array_values(self::$relation[$table])[0];
992
993                         // Create a key for preventing double queries
994                         $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
995
996                         // When the search field is the relation field, we don't need to fetch the rows
997                         // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
998                         if ((count($param) == 1) && ($field == array_keys($param)[0])) {
999                                 foreach ($rel_def AS $rel_table => $rel_fields) {
1000                                         foreach ($rel_fields AS $rel_field) {
1001                                                 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
1002                                                 $commands = array_merge($commands, $retval);
1003                                         }
1004                                 }
1005                         // We quit when this key already exists in the callstack.
1006                         } elseif (!isset($callstack[$qkey])) {
1007
1008                                 $callstack[$qkey] = true;
1009
1010                                 // Fetch all rows that are to be deleted
1011                                 $sql = "SELECT ".self::$dbo->escape($field)." FROM `".$table."` WHERE `".
1012                                 implode("` = ? AND `", array_keys($param))."` = ?";
1013
1014                                 $data = self::p($sql, $param);
1015                                 while ($row = self::fetch($data)) {
1016                                         // Now we accumulate the delete commands
1017                                         $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
1018                                         $commands = array_merge($commands, $retval);
1019                                 }
1020
1021                                 // Since we had split the delete command we don't need the original command anymore
1022                                 unset($commands[$key]);
1023                         }
1024                 }
1025
1026                 if (!$in_process) {
1027                         // Now we finalize the process
1028                         $do_transaction = !self::$in_transaction;
1029
1030                         if ($do_transaction) {
1031                                 self::transaction();
1032                         }
1033
1034                         $compacted = array();
1035                         $counter = array();
1036                         foreach ($commands AS $command) {
1037                                 if (count($command['param']) > 1) {
1038                                         $sql = "DELETE FROM `".$command['table']."` WHERE `".
1039                                                 implode("` = ? AND `", array_keys($command['param']))."` = ?";
1040
1041                                         logger(dba::replace_parameters($sql, $command['param']), LOGGER_DATA);
1042
1043                                         if (!self::e($sql, $command['param'])) {
1044                                                 if ($do_transaction) {
1045                                                         self::rollback();
1046                                                 }
1047                                                 return false;
1048                                         }
1049                                 } else {
1050                                         $key_table = $command['table'];
1051                                         $key_param = array_keys($command['param'])[0];
1052                                         $value = array_values($command['param'])[0];
1053
1054                                         // Split the SQL queries in chunks of 100 values
1055                                         // We do the $i stuff here to make the code better readable
1056                                         $i = $counter[$key_table][$key_param];
1057                                         if (count($compacted[$key_table][$key_param][$i]) > 100) {
1058                                                 ++$i;
1059                                         }
1060
1061                                         $compacted[$key_table][$key_param][$i][$value] = $value;
1062                                         $counter[$key_table][$key_param] = $i;
1063                                 }
1064                         }
1065                         foreach ($compacted AS $table => $values) {
1066                                 foreach ($values AS $field => $field_value_list) {
1067                                         foreach ($field_value_list AS $field_values) {
1068                                                 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
1069                                                         substr(str_repeat("?, ", count($field_values)), 0, -2).");";
1070
1071                                                 logger(dba::replace_parameters($sql, $field_values), LOGGER_DATA);
1072
1073                                                 if (!self::e($sql, $field_values)) {
1074                                                         if ($do_transaction) {
1075                                                                 self::rollback();
1076                                                         }
1077                                                         return false;
1078                                                 }
1079                                         }
1080                                 }
1081                         }
1082                         if ($do_transaction) {
1083                                 self::commit();
1084                         }
1085                         return true;
1086                 }
1087
1088                 return $commands;
1089         }
1090
1091         /**
1092          * @brief Updates rows
1093          *
1094          * Updates rows in the database. When $old_fields is set to an array,
1095          * the system will only do an update if the fields in that array changed.
1096          *
1097          * Attention:
1098          * Only the values in $old_fields are compared.
1099          * This is an intentional behaviour.
1100          *
1101          * Example:
1102          * We include the timestamp field in $fields but not in $old_fields.
1103          * Then the row will only get the new timestamp when the other fields had changed.
1104          *
1105          * When $old_fields is set to a boolean value the system will do this compare itself.
1106          * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1107          *
1108          * Attention:
1109          * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1110          * When you set $old_fields to "true" then $fields must contain all relevant fields!
1111          *
1112          * @param string $table Table name
1113          * @param array $fields contains the fields that are updated
1114          * @param array $condition condition array with the key values
1115          * @param array|boolean $old_fields array with the old field values that are about to be replaced
1116          *
1117          * @return boolean was the update successfull?
1118          */
1119         static public function update($table, $fields, $condition, $old_fields = array()) {
1120
1121                 /** @todo We may use MySQL specific functions here:
1122                  * INSERT INTO `config` (`cat`, `k`, `v`) VALUES ('%s', '%s', '%s') ON DUPLICATE KEY UPDATE `v` = '%s'"
1123                  * But I think that it doesn't make sense here.
1124                 */
1125
1126                 $table = self::$dbo->escape($table);
1127
1128                 if (is_bool($old_fields)) {
1129                         $sql = "SELECT * FROM `".$table."` WHERE `".
1130                         implode("` = ? AND `", array_keys($condition))."` = ? LIMIT 1";
1131
1132                         $params = array();
1133                         foreach ($condition AS $value) {
1134                                 $params[] = $value;
1135                         }
1136
1137                         $do_insert = $old_fields;
1138
1139                         $old_fields = self::fetch_first($sql, $params);
1140                         if (is_bool($old_fields)) {
1141                                 if ($do_insert) {
1142                                         return self::insert($table, $fields);
1143                                 }
1144                                 $old_fields = array();
1145                         }
1146                 }
1147
1148                 $do_update = (count($old_fields) == 0);
1149
1150                 foreach ($old_fields AS $fieldname => $content) {
1151                         if (isset($fields[$fieldname])) {
1152                                 if ($fields[$fieldname] == $content) {
1153                                         unset($fields[$fieldname]);
1154                                 } else {
1155                                         $do_update = true;
1156                                 }
1157                         }
1158                 }
1159
1160                 if (!$do_update || (count($fields) == 0)) {
1161                         return true;
1162                 }
1163
1164                 $sql = "UPDATE `".$table."` SET `".
1165                         implode("` = ?, `", array_keys($fields))."` = ? WHERE `".
1166                         implode("` = ? AND `", array_keys($condition))."` = ?";
1167
1168                 $params = array();
1169                 foreach ($fields AS $value) {
1170                         $params[] = $value;
1171                 }
1172                 foreach ($condition AS $value) {
1173                         $params[] = $value;
1174                 }
1175
1176                 return self::e($sql, $params);
1177         }
1178
1179         /**
1180          * @brief Select rows from a table
1181          *
1182          * @param string $table Table name
1183          * @param array $fields array of selected fields
1184          * @param array $condition array of fields for condition
1185          * @param array $params array of several parameters
1186          *
1187          * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1188          *
1189          * Example:
1190          * $table = "item";
1191          * $fields = array("id", "uri", "uid", "network");
1192          * $condition = array("uid" => 1, "network" => 'dspr');
1193          * $params = array("order" => array("id", "received" => true), "limit" => 1);
1194          *
1195          * $data = dba::select($table, $fields, $condition, $params);
1196          */
1197         static public function select($table, $fields = array(), $condition = array(), $params = array()) {
1198                 if ($table == '') {
1199                         return false;
1200                 }
1201
1202                 if (count($fields) > 0) {
1203                         $select_fields = "`".implode("`, `", array_values($fields))."`";
1204                 } else {
1205                         $select_fields = "*";
1206                 }
1207
1208                 if (count($condition) > 0) {
1209                         $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1210                 } else {
1211                         $condition_string = "";
1212                 }
1213
1214                 $param_string = '';
1215                 $single_row = false;
1216
1217                 if (isset($params['order'])) {
1218                         $param_string .= " ORDER BY ";
1219                         foreach ($params['order'] AS $fields => $order) {
1220                                 if (!is_int($fields)) {
1221                                         $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1222                                 } else {
1223                                         $param_string .= "`".$order."`, ";
1224                                 }
1225                         }
1226                         $param_string = substr($param_string, 0, -2);
1227                 }
1228
1229                 if (isset($params['limit'])) {
1230                         if (is_int($params['limit'])) {
1231                                 $param_string .= " LIMIT ".$params['limit'];
1232                                 $single_row =($params['limit'] == 1);
1233                         }
1234                 }
1235
1236                 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1237
1238                 $result = self::p($sql, $condition);
1239
1240                 if (is_bool($result) || !$single_row) {
1241                         return $result;
1242                 } else {
1243                         $row = self::fetch($result);
1244                         self::close($result);
1245                         return $row;
1246                 }
1247         }
1248
1249         /**
1250          * @brief Closes the current statement
1251          *
1252          * @param object $stmt statement object
1253          * @return boolean was the close successfull?
1254          */
1255         static public function close($stmt) {
1256                 if (!is_object($stmt)) {
1257                         return false;
1258                 }
1259
1260                 switch (self::$dbo->driver) {
1261                         case 'pdo':
1262                                 return $stmt->closeCursor();
1263                         case 'mysqli':
1264                                 return $stmt->free_result();
1265                                 return $stmt->close();
1266                         case 'mysql':
1267                                 return mysql_free_result($stmt);
1268                 }
1269         }
1270 }
1271
1272 function printable($s) {
1273         $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
1274         $s = str_replace("\x00",'.',$s);
1275         if (x($_SERVER,'SERVER_NAME')) {
1276                 $s = escape_tags($s);
1277         }
1278         return $s;
1279 }
1280
1281 // Procedural functions
1282 function dbg($state) {
1283         global $db;
1284
1285         if ($db) {
1286                 $db->dbg($state);
1287         }
1288 }
1289
1290 function dbesc($str) {
1291         global $db;
1292
1293         if ($db && $db->connected) {
1294                 return($db->escape($str));
1295         } else {
1296                 return(str_replace("'","\\'",$str));
1297         }
1298 }
1299
1300 // Function: q($sql,$args);
1301 // Description: execute SQL query with printf style args.
1302 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
1303 //                   'user', 1);
1304 function q($sql) {
1305         global $db;
1306         $args = func_get_args();
1307         unset($args[0]);
1308
1309         if ($db && $db->connected) {
1310                 $sql = $db->clean_query($sql);
1311                 $sql = $db->any_value_fallback($sql);
1312                 $stmt = @vsprintf($sql,$args); // Disabled warnings
1313                 //logger("dba: q: $stmt", LOGGER_ALL);
1314                 if ($stmt === false)
1315                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1316
1317                 $db->log_index($stmt);
1318
1319                 return $db->q($stmt);
1320         }
1321
1322         /**
1323          *
1324          * This will happen occasionally trying to store the
1325          * session data after abnormal program termination
1326          *
1327          */
1328         logger('dba: no database: ' . print_r($args,true));
1329         return false;
1330 }
1331
1332 /**
1333  * @brief Performs a query with "dirty reads"
1334  *
1335  * By doing dirty reads (reading uncommitted data) no locks are performed
1336  * This function can be used to fetch data that doesn't need to be reliable.
1337  *
1338  * @param $args Query parameters (1 to N parameters of different types)
1339  * @return array Query array
1340  */
1341 function qu($sql) {
1342         global $db;
1343
1344         $args = func_get_args();
1345         unset($args[0]);
1346
1347         if ($db && $db->connected) {
1348                 $sql = $db->clean_query($sql);
1349                 $sql = $db->any_value_fallback($sql);
1350                 $stmt = @vsprintf($sql,$args); // Disabled warnings
1351                 if ($stmt === false)
1352                         logger('dba: vsprintf error: ' . print_r(debug_backtrace(),true), LOGGER_DEBUG);
1353
1354                 $db->log_index($stmt);
1355
1356                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");
1357                 $retval = $db->q($stmt);
1358                 $db->q("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;");
1359                 return $retval;
1360         }
1361
1362         /**
1363          *
1364          * This will happen occasionally trying to store the
1365          * session data after abnormal program termination
1366          *
1367          */
1368         logger('dba: no database: ' . print_r($args,true));
1369         return false;
1370 }
1371
1372 /**
1373  *
1374  * Raw db query, no arguments
1375  *
1376  */
1377 function dbq($sql) {
1378         global $db;
1379
1380         if ($db && $db->connected) {
1381                 $ret = $db->q($sql);
1382         } else {
1383                 $ret = false;
1384         }
1385         return $ret;
1386 }
1387
1388 // Caller is responsible for ensuring that any integer arguments to
1389 // dbesc_array are actually integers and not malformed strings containing
1390 // SQL injection vectors. All integer array elements should be specifically
1391 // cast to int to avoid trouble.
1392 function dbesc_array_cb(&$item, $key) {
1393         if (is_string($item))
1394                 $item = dbesc($item);
1395 }
1396
1397 function dbesc_array(&$arr) {
1398         if (is_array($arr) && count($arr)) {
1399                 array_walk($arr,'dbesc_array_cb');
1400         }
1401 }
1402
1403 function dba_timer() {
1404         return microtime(true);
1405 }