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