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