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