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