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