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