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