]> git.mxchange.org Git - friendica.git/blob - include/dba.php
Some more replaced old database functions
[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                 $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
717                         substr(str_repeat("?, ", count($param)), 0, -2).")";
718
719                 if ($on_duplicate_update) {
720                         $sql .= " ON DUPLICATE KEY UPDATE `".implode("` = ?, `", array_keys($param))."` = ?";
721
722                         $values = array_values($param);
723                         $param = array_merge_recursive($values, $values);
724                 }
725
726                 return self::e($sql, $param);
727         }
728
729         /**
730          * @brief Fetch the id of the last insert command
731          *
732          * @return integer Last inserted id
733          */
734         public static function lastInsertId() {
735                 switch (self::$driver) {
736                         case 'pdo':
737                                 $id = self::$db->lastInsertId();
738                                 break;
739                         case 'mysqli':
740                                 $id = self::$db->insert_id;
741                                 break;
742                 }
743                 return $id;
744         }
745
746         /**
747          * @brief Locks a table for exclusive write access
748          *
749          * This function can be extended in the future to accept a table array as well.
750          *
751          * @param string $table Table name
752          *
753          * @return boolean was the lock successful?
754          */
755         public static function lock($table) {
756                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
757                 self::e("SET autocommit=0");
758                 $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
759                 if (!$success) {
760                         self::e("SET autocommit=1");
761                 } else {
762                         self::$in_transaction = true;
763                 }
764                 return $success;
765         }
766
767         /**
768          * @brief Unlocks all locked tables
769          *
770          * @return boolean was the unlock successful?
771          */
772         public static function unlock() {
773                 // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
774                 self::e("COMMIT");
775                 $success = self::e("UNLOCK TABLES");
776                 self::e("SET autocommit=1");
777                 self::$in_transaction = false;
778                 return $success;
779         }
780
781         /**
782          * @brief Starts a transaction
783          *
784          * @return boolean Was the command executed successfully?
785          */
786         public static function transaction() {
787                 if (!self::e('COMMIT')) {
788                         return false;
789                 }
790                 if (!self::e('START TRANSACTION')) {
791                         return false;
792                 }
793                 self::$in_transaction = true;
794                 return true;
795         }
796
797         /**
798          * @brief Does a commit
799          *
800          * @return boolean Was the command executed successfully?
801          */
802         public static function commit() {
803                 if (!self::e('COMMIT')) {
804                         return false;
805                 }
806                 self::$in_transaction = false;
807                 return true;
808         }
809
810         /**
811          * @brief Does a rollback
812          *
813          * @return boolean Was the command executed successfully?
814          */
815         public static function rollback() {
816                 if (!self::e('ROLLBACK')) {
817                         return false;
818                 }
819                 self::$in_transaction = false;
820                 return true;
821         }
822
823         /**
824          * @brief Build the array with the table relations
825          *
826          * The array is build from the database definitions in dbstructure.php
827          *
828          * This process must only be started once, since the value is cached.
829          */
830         private static function build_relation_data() {
831                 $definition = db_definition();
832
833                 foreach ($definition AS $table => $structure) {
834                         foreach ($structure['fields'] AS $field => $field_struct) {
835                                 if (isset($field_struct['relation'])) {
836                                         foreach ($field_struct['relation'] AS $rel_table => $rel_field) {
837                                                 self::$relation[$rel_table][$rel_field][$table][] = $field;
838                                         }
839                                 }
840                         }
841                 }
842         }
843
844         /**
845          * @brief Delete a row from a table
846          *
847          * @param string $table Table name
848          * @param array $param parameter array
849          * @param boolean $in_process Internal use: Only do a commit after the last delete
850          * @param array $callstack Internal use: prevent endless loops
851          *
852          * @return boolean|array was the delete successfull? When $in_process is set: deletion data
853          */
854         public static function delete($table, $param, $in_process = false, &$callstack = array()) {
855                 $commands = array();
856
857                 // Create a key for the loop prevention
858                 $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
859
860                 // We quit when this key already exists in the callstack.
861                 if (isset($callstack[$key])) {
862                         return $commands;
863                 }
864
865                 $callstack[$key] = true;
866
867                 $table = self::escape($table);
868
869                 $commands[$key] = array('table' => $table, 'param' => $param);
870
871                 // To speed up the whole process we cache the table relations
872                 if (count(self::$relation) == 0) {
873                         self::build_relation_data();
874                 }
875
876                 // Is there a relation entry for the table?
877                 if (isset(self::$relation[$table])) {
878                         // We only allow a simple "one field" relation.
879                         $field = array_keys(self::$relation[$table])[0];
880                         $rel_def = array_values(self::$relation[$table])[0];
881
882                         // Create a key for preventing double queries
883                         $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
884
885                         // When the search field is the relation field, we don't need to fetch the rows
886                         // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
887                         if ((count($param) == 1) && ($field == array_keys($param)[0])) {
888                                 foreach ($rel_def AS $rel_table => $rel_fields) {
889                                         foreach ($rel_fields AS $rel_field) {
890                                                 $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
891                                                 $commands = array_merge($commands, $retval);
892                                         }
893                                 }
894                         // We quit when this key already exists in the callstack.
895                         } elseif (!isset($callstack[$qkey])) {
896
897                                 $callstack[$qkey] = true;
898
899                                 // Fetch all rows that are to be deleted
900                                 $data = self::select($table, array($field), $param);
901
902                                 while ($row = self::fetch($data)) {
903                                         // Now we accumulate the delete commands
904                                         $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
905                                         $commands = array_merge($commands, $retval);
906                                 }
907
908                                 self::close($data);
909
910                                 // Since we had split the delete command we don't need the original command anymore
911                                 unset($commands[$key]);
912                         }
913                 }
914
915                 if (!$in_process) {
916                         // Now we finalize the process
917                         $do_transaction = !self::$in_transaction;
918
919                         if ($do_transaction) {
920                                 self::transaction();
921                         }
922
923                         $compacted = array();
924                         $counter = array();
925
926                         foreach ($commands AS $command) {
927                                 $condition = $command['param'];
928                                 $array_element = each($condition);
929                                 $array_key = $array_element['key'];
930                                 if (is_int($array_key)) {
931                                         $condition_string = " WHERE ".array_shift($condition);
932                                 } else {
933                                         $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
934                                 }
935
936                                 if ((count($command['param']) > 1) || is_int($array_key)) {
937                                         $sql = "DELETE FROM `".$command['table']."`".$condition_string;
938                                         logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
939
940                                         if (!self::e($sql, $condition)) {
941                                                 if ($do_transaction) {
942                                                         self::rollback();
943                                                 }
944                                                 return false;
945                                         }
946                                 } else {
947                                         $key_table = $command['table'];
948                                         $key_param = array_keys($command['param'])[0];
949                                         $value = array_values($command['param'])[0];
950
951                                         // Split the SQL queries in chunks of 100 values
952                                         // We do the $i stuff here to make the code better readable
953                                         $i = $counter[$key_table][$key_param];
954                                         if (count($compacted[$key_table][$key_param][$i]) > 100) {
955                                                 ++$i;
956                                         }
957
958                                         $compacted[$key_table][$key_param][$i][$value] = $value;
959                                         $counter[$key_table][$key_param] = $i;
960                                 }
961                         }
962                         foreach ($compacted AS $table => $values) {
963                                 foreach ($values AS $field => $field_value_list) {
964                                         foreach ($field_value_list AS $field_values) {
965                                                 $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
966                                                         substr(str_repeat("?, ", count($field_values)), 0, -2).");";
967
968                                                 logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
969
970                                                 if (!self::e($sql, $field_values)) {
971                                                         if ($do_transaction) {
972                                                                 self::rollback();
973                                                         }
974                                                         return false;
975                                                 }
976                                         }
977                                 }
978                         }
979                         if ($do_transaction) {
980                                 self::commit();
981                         }
982                         return true;
983                 }
984
985                 return $commands;
986         }
987
988         /**
989          * @brief Updates rows
990          *
991          * Updates rows in the database. When $old_fields is set to an array,
992          * the system will only do an update if the fields in that array changed.
993          *
994          * Attention:
995          * Only the values in $old_fields are compared.
996          * This is an intentional behaviour.
997          *
998          * Example:
999          * We include the timestamp field in $fields but not in $old_fields.
1000          * Then the row will only get the new timestamp when the other fields had changed.
1001          *
1002          * When $old_fields is set to a boolean value the system will do this compare itself.
1003          * When $old_fields is set to "true" the system will do an insert if the row doesn't exists.
1004          *
1005          * Attention:
1006          * Only set $old_fields to a boolean value when you are sure that you will update a single row.
1007          * When you set $old_fields to "true" then $fields must contain all relevant fields!
1008          *
1009          * @param string $table Table name
1010          * @param array $fields contains the fields that are updated
1011          * @param array $condition condition array with the key values
1012          * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
1013          *
1014          * @return boolean was the update successfull?
1015          */
1016         public static function update($table, $fields, $condition, $old_fields = array()) {
1017                 $table = self::escape($table);
1018
1019                 $array_element = each($condition);
1020                 $array_key = $array_element['key'];
1021                 if (is_int($array_key)) {
1022                         $condition_string = " WHERE ".array_shift($condition);
1023                 } else {
1024                         $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1025                 }
1026
1027                 if (is_bool($old_fields)) {
1028                         $do_insert = $old_fields;
1029
1030                         $old_fields = self::select($table, array(), $condition, array('limit' => 1));
1031
1032                         if (is_bool($old_fields)) {
1033                                 if ($do_insert) {
1034                                         $values = array_merge($condition, $fields);
1035                                         return self::insert($table, $values, $do_insert);
1036                                 }
1037                                 $old_fields = array();
1038                         }
1039                 }
1040
1041                 $do_update = (count($old_fields) == 0);
1042
1043                 foreach ($old_fields AS $fieldname => $content) {
1044                         if (isset($fields[$fieldname])) {
1045                                 if ($fields[$fieldname] == $content) {
1046                                         unset($fields[$fieldname]);
1047                                 } else {
1048                                         $do_update = true;
1049                                 }
1050                         }
1051                 }
1052
1053                 if (!$do_update || (count($fields) == 0)) {
1054                         return true;
1055                 }
1056
1057                 $sql = "UPDATE `".$table."` SET `".
1058                         implode("` = ?, `", array_keys($fields))."` = ?".$condition_string;
1059
1060                 $params1 = array_values($fields);
1061                 $params2 = array_values($condition);
1062                 $params = array_merge_recursive($params1, $params2);
1063
1064                 return self::e($sql, $params);
1065         }
1066
1067         /**
1068          * @brief Select rows from a table
1069          *
1070          * @param string $table Table name
1071          * @param array $fields array of selected fields
1072          * @param array $condition array of fields for condition
1073          * @param array $params array of several parameters
1074          *
1075          * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned
1076          *
1077          * Example:
1078          * $table = "item";
1079          * $fields = array("id", "uri", "uid", "network");
1080          *
1081          * $condition = array("uid" => 1, "network" => 'dspr');
1082          * or:
1083          * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr');
1084          *
1085          * $params = array("order" => array("id", "received" => true), "limit" => 1);
1086          *
1087          * $data = dba::select($table, $fields, $condition, $params);
1088          */
1089         public static function select($table, $fields = array(), $condition = array(), $params = array()) {
1090                 if ($table == '') {
1091                         return false;
1092                 }
1093
1094                 if (count($fields) > 0) {
1095                         $select_fields = "`".implode("`, `", array_values($fields))."`";
1096                 } else {
1097                         $select_fields = "*";
1098                 }
1099
1100                 if (count($condition) > 0) {
1101                         $array_element = each($condition);
1102                         $array_key = $array_element['key'];
1103                         if (is_int($array_key)) {
1104                                 $condition_string = " WHERE ".array_shift($condition);
1105                         } else {
1106                                 $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
1107                         }
1108                 } else {
1109                         $condition_string = "";
1110                 }
1111
1112                 $param_string = '';
1113                 $single_row = false;
1114
1115                 if (isset($params['order'])) {
1116                         $param_string .= " ORDER BY ";
1117                         foreach ($params['order'] AS $fields => $order) {
1118                                 if (!is_int($fields)) {
1119                                         $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
1120                                 } else {
1121                                         $param_string .= "`".$order."`, ";
1122                                 }
1123                         }
1124                         $param_string = substr($param_string, 0, -2);
1125                 }
1126
1127                 if (isset($params['limit']) && is_int($params['limit'])) {
1128                         $param_string .= " LIMIT ".$params['limit'];
1129                         $single_row = ($params['limit'] == 1);
1130                 }
1131
1132                 if (isset($params['only_query']) && $params['only_query']) {
1133                         $single_row = !$params['only_query'];
1134                 }
1135
1136                 $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
1137
1138                 $result = self::p($sql, $condition);
1139
1140                 if (is_bool($result) || !$single_row) {
1141                         return $result;
1142                 } else {
1143                         $row = self::fetch($result);
1144                         self::close($result);
1145                         return $row;
1146                 }
1147         }
1148
1149
1150         /**
1151          * @brief Fills an array with data from a query
1152          *
1153          * @param object $stmt statement object
1154          * @return array Data array
1155          */
1156         public static function inArray($stmt, $do_close = true) {
1157                 if (is_bool($stmt)) {
1158                         return $stmt;
1159                 }
1160
1161                 $data = array();
1162                 while ($row = self::fetch($stmt)) {
1163                         $data[] = $row;
1164                 }
1165                 if ($do_close) {
1166                         self::close($stmt);
1167                 }
1168                 return $data;
1169         }
1170
1171         /**
1172          * @brief Returns the error number of the last query
1173          *
1174          * @return string Error number (0 if no error)
1175          */
1176         public static function errorNo() {
1177                 return self::$errorno;
1178         }
1179
1180         /**
1181          * @brief Returns the error message of the last query
1182          *
1183          * @return string Error message ('' if no error)
1184          */
1185         public static function errorMessage() {
1186                 return self::$error;
1187         }
1188
1189         /**
1190          * @brief Closes the current statement
1191          *
1192          * @param object $stmt statement object
1193          * @return boolean was the close successfull?
1194          */
1195         public static function close($stmt) {
1196                 if (!is_object($stmt)) {
1197                         return false;
1198                 }
1199
1200                 switch (self::$driver) {
1201                         case 'pdo':
1202                                 return $stmt->closeCursor();
1203                         case 'mysqli':
1204                                 $stmt->free_result();
1205                                 return $stmt->close();
1206                 }
1207         }
1208 }
1209
1210 function dbesc($str) {
1211         if (dba::$connected) {
1212                 return(dba::escape($str));
1213         } else {
1214                 return(str_replace("'","\\'",$str));
1215         }
1216 }
1217
1218 /**
1219  * @brief execute SQL query with printf style args - deprecated
1220  *
1221  * Please use the dba:: functions instead:
1222  * dba::select, dba::exists, dba::insert
1223  * dba::delete, dba::update, dba::p, dba::e
1224  *
1225  * @param $args Query parameters (1 to N parameters of different types)
1226  * @return array Query array
1227  */
1228 function q($sql) {
1229         $args = func_get_args();
1230         unset($args[0]);
1231
1232         if (!dba::$connected) {
1233                 return false;
1234         }
1235
1236         $sql = dba::clean_query($sql);
1237         $sql = dba::any_value_fallback($sql);
1238
1239         $stmt = @vsprintf($sql, $args);
1240
1241         $ret = dba::p($stmt);
1242
1243         if (is_bool($ret)) {
1244                 return $ret;
1245         }
1246
1247         $columns = dba::columnCount($ret);
1248
1249         $data = dba::inArray($ret);
1250
1251         if ((count($data) == 0) && ($columns == 0)) {
1252                 return true;
1253         }
1254
1255         return $data;
1256 }
1257
1258 function dba_timer() {
1259         return microtime(true);
1260 }