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