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