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