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