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