]> git.mxchange.org Git - friendica.git/blobdiff - include/dba.php
Fix Config use in api_statusnet_config()
[friendica.git] / include / dba.php
index 293bfdc00233f7005ec43b1c850c31ecaeceae44..9d828f8b440e40ac8147662eefc32acd328bd4ff 100644 (file)
@@ -1,9 +1,11 @@
 <?php
+
+use Friendica\App;
+use Friendica\Core\L10n;
 use Friendica\Core\System;
 use Friendica\Database\DBM;
 use Friendica\Database\DBStructure;
-
-require_once('include/datetime.php');
+use Friendica\Util\DateTimeFormat;
 
 /**
  * @class MySQL database class
@@ -12,7 +14,7 @@ require_once('include/datetime.php');
  */
 
 class dba {
-       public static $connected = true;
+       public static $connected = false;
 
        private static $_server_info = '';
        private static $db;
@@ -21,10 +23,15 @@ class dba {
        private static $errorno = 0;
        private static $affected_rows = 0;
        private static $in_transaction = false;
-       private static $relation = array();
-
-       public static function connect($serveraddr, $user, $pass, $db, $install = false) {
-               if (!is_null(self::$db)) {
+       private static $in_retrial = false;
+       private static $relation = [];
+       private static $db_serveraddr = '';
+       private static $db_user = '';
+       private static $db_pass = '';
+       private static $db_name = '';
+
+       public static function connect($serveraddr, $user, $pass, $db) {
+               if (!is_null(self::$db) && self::connected()) {
                        return true;
                }
 
@@ -32,6 +39,12 @@ class dba {
 
                $stamp1 = microtime(true);
 
+               // We are storing these values for being able to perform a reconnect
+               self::$db_serveraddr = $serveraddr;
+               self::$db_user = $user;
+               self::$db_pass = $pass;
+               self::$db_name = $db;
+
                $serveraddr = trim($serveraddr);
 
                $serverdata = explode(':', $serveraddr);
@@ -47,22 +60,9 @@ class dba {
                $db = trim($db);
 
                if (!(strlen($server) && strlen($user))) {
-                       self::$connected = false;
-                       self::$db = null;
                        return false;
                }
 
-               if ($install) {
-                       if (strlen($server) && ($server !== 'localhost') && ($server !== '127.0.0.1')) {
-                               if (! dns_get_record($server, DNS_A + DNS_CNAME + DNS_PTR)) {
-                                       self::$error = sprintf(t('Cannot locate DNS info for database server \'%s\''), $server);
-                                       self::$connected = false;
-                                       self::$db = null;
-                                       return false;
-                               }
-                       }
-               }
-
                if (class_exists('\PDO') && in_array('mysql', PDO::getAvailableDrivers())) {
                        self::$driver = 'pdo';
                        $connect = "mysql:host=".$server.";dbname=".$db;
@@ -76,9 +76,9 @@ class dba {
                        }
                        try {
                                self::$db = @new PDO($connect, $user, $pass);
+                               self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
                                self::$connected = true;
                        } catch (PDOException $e) {
-                               self::$connected = false;
                        }
                }
 
@@ -96,14 +96,51 @@ class dba {
 
                // No suitable SQL driver was found.
                if (!self::$connected) {
+                       self::$driver = null;
                        self::$db = null;
-                       if (!$install) {
-                               System::unavailable();
-                       }
                }
                $a->save_timestamp($stamp1, "network");
 
-               return true;
+               return self::$connected;
+       }
+
+       /**
+        * Disconnects the current database connection
+        */
+       public static function disconnect()
+       {
+               if (is_null(self::$db)) {
+                       return;
+               }
+
+               switch (self::$driver) {
+                       case 'pdo':
+                               self::$db = null;
+                               break;
+                       case 'mysqli':
+                               self::$db->close();
+                               self::$db = null;
+                               break;
+               }
+       }
+
+       /**
+        * Perform a reconnect of an existing database connection
+        */
+       public static function reconnect() {
+               self::disconnect();
+
+               $ret = self::connect(self::$db_serveraddr, self::$db_user, self::$db_pass, self::$db_name);
+               return $ret;
+       }
+
+       /**
+        * Return the database object.
+        * @return PDO|mysqli
+        */
+       public static function get_db()
+       {
+               return self::$db;
        }
 
        /**
@@ -135,7 +172,7 @@ class dba {
         */
        public static function database_name() {
                $ret = self::p("SELECT DATABASE() AS `db`");
-                $data = self::inArray($ret);
+               $data = self::inArray($ret);
                return $data[0]['db'];
        }
 
@@ -144,7 +181,7 @@ class dba {
         *
         * @param string $query The database query that will be analyzed
         */
-       private static function log_index($query) {
+       private static function logIndex($query) {
                $a = get_app();
 
                if (empty($a->config["system"]["db_log_index"])) {
@@ -157,7 +194,7 @@ class dba {
                }
 
                // Only do the explain on "select", "update" and "delete"
-               if (!in_array(strtolower(substr($query, 0, 6)), array("select", "update", "delete"))) {
+               if (!in_array(strtolower(substr($query, 0, 6)), ["select", "update", "delete"])) {
                        return;
                }
 
@@ -187,7 +224,7 @@ class dba {
 
                        if ($log) {
                                $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
-                               @file_put_contents($a->config["system"]["db_log_index"], datetime_convert()."\t".
+                               @file_put_contents($a->config["system"]["db_log_index"], DateTimeFormat::utcNow()."\t".
                                                $row['key']."\t".$row['rows']."\t".$row['Extra']."\t".
                                                basename($backtrace[1]["file"])."\t".
                                                $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
@@ -253,8 +290,8 @@ class dba {
         * @return string The input SQL string modified if necessary.
         */
        public static function clean_query($sql) {
-               $search = array("\t", "\n", "\r", "  ");
-               $replace = array(' ', ' ', ' ', ' ');
+               $search = ["\t", "\n", "\r", "  "];
+               $replace = [' ', ' ', ' ', ' '];
                do {
                        $oldsql = $sql;
                        $sql = str_replace($search, $replace, $sql);
@@ -271,7 +308,7 @@ class dba {
         * @param array $args The parameters that are to replace the ? placeholders
         * @return string The replaced SQL query
         */
-       private static function replace_parameters($sql, $args) {
+       private static function replaceParameters($sql, $args) {
                $offset = 0;
                foreach ($args AS $param => $value) {
                        if (is_int($args[$param]) || is_float($args[$param])) {
@@ -313,7 +350,7 @@ class dba {
         * For all regular queries please use dba::select or dba::exists
         *
         * @param string $sql SQL statement
-        * @return bool|object statement object
+        * @return bool|object statement object or result object
         */
        public static function p($sql) {
                $a = get_app();
@@ -324,7 +361,7 @@ class dba {
 
                // Renumber the array keys to be sure that they fit
                $i = 0;
-               $args = array();
+               $args = [];
                foreach ($params AS $param) {
                        // Avoid problems with some MySQL servers and boolean values. See issue #3645
                        if (is_bool($param)) {
@@ -391,7 +428,12 @@ class dba {
                                }
 
                                foreach ($args AS $param => $value) {
-                                       $stmt->bindParam($param, $args[$param]);
+                                       if (is_int($args[$param])) {
+                                               $data_type = PDO::PARAM_INT;
+                                       } else {
+                                               $data_type = PDO::PARAM_STR;
+                                       }
+                                       $stmt->bindParam($param, $args[$param], $data_type);
                                }
 
                                if (!$stmt->execute()) {
@@ -408,11 +450,11 @@ class dba {
                                // There are SQL statements that cannot be executed with a prepared statement
                                $parts = explode(' ', $orig_sql);
                                $command = strtolower($parts[0]);
-                               $can_be_prepared = in_array($command, array('select', 'update', 'insert', 'delete'));
+                               $can_be_prepared = in_array($command, ['select', 'update', 'insert', 'delete']);
 
                                // The fallback routine is called as well when there are no arguments
                                if (!$can_be_prepared || (count($args) == 0)) {
-                                       $retval = self::$db->query(self::replace_parameters($sql, $args));
+                                       $retval = self::$db->query(self::replaceParameters($sql, $args));
                                        if (self::$db->errno) {
                                                self::$error = self::$db->error;
                                                self::$errorno = self::$db->errno;
@@ -436,24 +478,24 @@ class dba {
                                        break;
                                }
 
-                               $params = '';
-                               $values = array();
+                               $param_types = '';
+                               $values = [];
                                foreach ($args AS $param => $value) {
                                        if (is_int($args[$param])) {
-                                               $params .= 'i';
+                                               $param_types .= 'i';
                                        } elseif (is_float($args[$param])) {
-                                               $params .= 'd';
+                                               $param_types .= 'd';
                                        } elseif (is_string($args[$param])) {
-                                               $params .= 's';
+                                               $param_types .= 's';
                                        } else {
-                                               $params .= 'b';
+                                               $param_types .= 'b';
                                        }
                                        $values[] = &$args[$param];
                                }
 
                                if (count($values) > 0) {
-                                       array_unshift($values, $params);
-                                       call_user_func_array(array($stmt, 'bind_param'), $values);
+                                       array_unshift($values, $param_types);
+                                       call_user_func_array([$stmt, 'bind_param'], $values);
                                }
 
                                if (!$stmt->execute()) {
@@ -475,7 +517,27 @@ class dba {
                        $errorno = self::$errorno;
 
                        logger('DB Error '.self::$errorno.': '.self::$error."\n".
-                               System::callstack(8)."\n".self::replace_parameters($sql, $params));
+                               System::callstack(8)."\n".self::replaceParameters($sql, $args));
+
+                       // On a lost connection we try to reconnect - but only once.
+                       if ($errorno == 2006) {
+                               if (self::$in_retrial || !self::reconnect()) {
+                                       // It doesn't make sense to continue when the database connection was lost
+                                       if (self::$in_retrial) {
+                                               logger('Giving up retrial because of database error '.$errorno.': '.$error);
+                                       } else {
+                                               logger("Couldn't reconnect after database error ".$errorno.': '.$error);
+                                       }
+                                       exit(1);
+                               } else {
+                                       // We try it again
+                                       logger('Reconnected after database error '.$errorno.': '.$error);
+                                       self::$in_retrial = true;
+                                       $ret = self::p($sql, $args);
+                                       self::$in_retrial = false;
+                                       return $ret;
+                               }
+                       }
 
                        self::$error = $error;
                        self::$errorno = $errorno;
@@ -492,10 +554,10 @@ class dba {
                                $duration = round($duration, 3);
                                $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
 
-                               @file_put_contents($a->config["system"]["db_log"], datetime_convert()."\t".$duration."\t".
+                               @file_put_contents($a->config["system"]["db_log"], DateTimeFormat::utcNow()."\t".$duration."\t".
                                                basename($backtrace[1]["file"])."\t".
                                                $backtrace[1]["line"]."\t".$backtrace[2]["function"]."\t".
-                                               substr(self::replace_parameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
+                                               substr(self::replaceParameters($sql, $args), 0, 2000)."\n", FILE_APPEND);
                        }
                }
                return $retval;
@@ -540,7 +602,14 @@ class dba {
                        $errorno = self::$errorno;
 
                        logger('DB Error '.self::$errorno.': '.self::$error."\n".
-                               System::callstack(8)."\n".self::replace_parameters($sql, $params));
+                               System::callstack(8)."\n".self::replaceParameters($sql, $params));
+
+                       // On a lost connection we simply quit.
+                       // A reconnect like in self::p could be dangerous with modifications
+                       if ($errorno == 2006) {
+                               logger('Giving up because of database error '.$errorno.': '.$error);
+                               exit(1);
+                       }
 
                        self::$error = $error;
                        self::$errorno = $errorno;
@@ -564,12 +633,12 @@ class dba {
                        return false;
                }
 
-               $fields = array();
+               $fields = [];
 
-               $array_element = each($condition);
-               $array_key = $array_element['key'];
-               if (!is_int($array_key)) {
-                       $fields = array($array_key);
+               reset($condition);
+               $first_key = key($condition);
+               if (!is_int($first_key)) {
+                       $fields = [$first_key];
                }
 
                $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
@@ -587,8 +656,8 @@ class dba {
 
        /**
         * Fetches the first row
-        * 
-        * Please use dba::selectOne or dba::exists whenever this is possible.
+        *
+        * Please use dba::selectFirst or dba::exists whenever this is possible.
         *
         * @brief Fetches the first row
         * @param string $sql SQL statement
@@ -659,33 +728,41 @@ class dba {
        /**
         * @brief Fetch a single row
         *
-        * @param PDOStatement|mysqli_result|mysqli_stmt $stmt statement object
+        * @param mixed $stmt statement object
         * @return array current row
         */
        public static function fetch($stmt) {
+               $a = get_app();
+
+               $stamp1 = microtime(true);
+
+               $columns = [];
+
                if (!is_object($stmt)) {
                        return false;
                }
 
                switch (self::$driver) {
                        case 'pdo':
-                               return $stmt->fetch(PDO::FETCH_ASSOC);
+                               $columns = $stmt->fetch(PDO::FETCH_ASSOC);
+                               break;
                        case 'mysqli':
                                if (get_class($stmt) == 'mysqli_result') {
-                                       return $stmt->fetch_assoc();
+                                       $columns = $stmt->fetch_assoc();
+                                       break;
                                }
 
                                // This code works, but is slow
 
                                // Bind the result to a result array
-                               $cols = array();
+                               $cols = [];
 
-                               $cols_num = array();
+                               $cols_num = [];
                                for ($x = 0; $x < $stmt->field_count; $x++) {
                                        $cols[] = &$cols_num[$x];
                                }
 
-                               call_user_func_array(array($stmt, 'bind_result'), $cols);
+                               call_user_func_array([$stmt, 'bind_result'], $cols);
 
                                if (!$stmt->fetch()) {
                                        return false;
@@ -697,12 +774,14 @@ class dba {
                                $result = $stmt->result_metadata();
                                $fields = $result->fetch_fields();
 
-                               $columns = array();
                                foreach ($cols_num AS $param => $col) {
                                        $columns[$fields[$param]->name] = $col;
                                }
-                               return $columns;
                }
+
+               $a->save_timestamp($stamp1, 'database');
+
+               return $columns;
        }
 
        /**
@@ -762,10 +841,25 @@ class dba {
         */
        public static function lock($table) {
                // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
-               self::e("SET autocommit=0");
+               if (self::$driver == 'pdo') {
+                       self::e("SET autocommit=0");
+                       self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
+               } else {
+                       self::$db->autocommit(false);
+               }
+
                $success = self::e("LOCK TABLES `".self::escape($table)."` WRITE");
+
+               if (self::$driver == 'pdo') {
+                       self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
+               }
+
                if (!$success) {
-                       self::e("SET autocommit=1");
+                       if (self::$driver == 'pdo') {
+                               self::e("SET autocommit=1");
+                       } else {
+                               self::$db->autocommit(true);
+                       }
                } else {
                        self::$in_transaction = true;
                }
@@ -779,9 +873,21 @@ class dba {
         */
        public static function unlock() {
                // See here: https://dev.mysql.com/doc/refman/5.7/en/lock-tables-and-transactions.html
-               self::e("COMMIT");
+               self::performCommit();
+
+               if (self::$driver == 'pdo') {
+                       self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
+               }
+
                $success = self::e("UNLOCK TABLES");
-               self::e("SET autocommit=1");
+
+               if (self::$driver == 'pdo') {
+                       self::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
+                       self::e("SET autocommit=1");
+               } else {
+                       self::$db->autocommit(true);
+               }
+
                self::$in_transaction = false;
                return $success;
        }
@@ -792,23 +898,51 @@ class dba {
         * @return boolean Was the command executed successfully?
         */
        public static function transaction() {
-               if (!self::e('COMMIT')) {
+               if (!self::performCommit()) {
                        return false;
                }
-               if (!self::e('START TRANSACTION')) {
-                       return false;
+
+               switch (self::$driver) {
+                       case 'pdo':
+                               if (self::$db->inTransaction()) {
+                                       break;
+                               }
+                               if (!self::$db->beginTransaction()) {
+                                       return false;
+                               }
+                               break;
+                       case 'mysqli':
+                               if (!self::$db->begin_transaction()) {
+                                       return false;
+                               }
+                               break;
                }
+
                self::$in_transaction = true;
                return true;
        }
 
+       private static function performCommit()
+       {
+               switch (self::$driver) {
+                       case 'pdo':
+                               if (!self::$db->inTransaction()) {
+                                       return true;
+                               }
+                               return self::$db->commit();
+                       case 'mysqli':
+                               return self::$db->commit();
+               }
+               return true;
+       }
+
        /**
         * @brief Does a commit
         *
         * @return boolean Was the command executed successfully?
         */
        public static function commit() {
-               if (!self::e('COMMIT')) {
+               if (!self::performCommit()) {
                        return false;
                }
                self::$in_transaction = false;
@@ -821,11 +955,20 @@ class dba {
         * @return boolean Was the command executed successfully?
         */
        public static function rollback() {
-               if (!self::e('ROLLBACK')) {
-                       return false;
+               switch (self::$driver) {
+                       case 'pdo':
+                               if (!self::$db->inTransaction()) {
+                                       $ret = true;
+                                       break;
+                               }
+                               $ret = self::$db->rollBack();
+                               break;
+                       case 'mysqli':
+                               $ret = self::$db->rollback();
+                               break;
                }
                self::$in_transaction = false;
-               return true;
+               return $ret;
        }
 
        /**
@@ -835,7 +978,7 @@ class dba {
         *
         * This process must only be started once, since the value is cached.
         */
-       private static function build_relation_data() {
+       private static function buildRelationData() {
                $definition = DBStructure::definition();
 
                foreach ($definition AS $table => $structure) {
@@ -852,24 +995,27 @@ class dba {
        /**
         * @brief Delete a row from a table
         *
-        * @param string $table Table name
-        * @param array $param parameter array
-        * @param boolean $in_process Internal use: Only do a commit after the last delete
-        * @param array $callstack Internal use: prevent endless loops
+        * @param string  $table       Table name
+        * @param array   $conditions  Field condition(s)
+        * @param array   $options
+        *                - cascade: If true we delete records in other tables that depend on the one we're deleting through
+        *                           relations (default: true)
+        * @param boolean $in_process  Internal use: Only do a commit after the last delete
+        * @param array   $callstack   Internal use: prevent endless loops
         *
-        * @return boolean|array was the delete successfull? When $in_process is set: deletion data
+        * @return boolean|array was the delete successful? When $in_process is set: deletion data
         */
-       public static function delete($table, $param, $in_process = false, &$callstack = array()) {
-
-               if (empty($table) || empty($param)) {
-                       logger('Table and condition have to be set');
+       public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
+       {
+               if (empty($table) || empty($conditions)) {
+                       logger('Table and conditions have to be set');
                        return false;
                }
 
-               $commands = array();
+               $commands = [];
 
                // Create a key for the loop prevention
-               $key = $table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
+               $key = $table . ':' . json_encode($conditions);
 
                // We quit when this key already exists in the callstack.
                if (isset($callstack[$key])) {
@@ -880,42 +1026,44 @@ class dba {
 
                $table = self::escape($table);
 
-               $commands[$key] = array('table' => $table, 'param' => $param);
+               $commands[$key] = ['table' => $table, 'conditions' => $conditions];
+
+               $cascade = defaults($options, 'cascade', true);
 
                // To speed up the whole process we cache the table relations
-               if (count(self::$relation) == 0) {
-                       self::build_relation_data();
+               if ($cascade && count(self::$relation) == 0) {
+                       self::buildRelationData();
                }
 
                // Is there a relation entry for the table?
-               if (isset(self::$relation[$table])) {
+               if ($cascade && isset(self::$relation[$table])) {
                        // We only allow a simple "one field" relation.
                        $field = array_keys(self::$relation[$table])[0];
                        $rel_def = array_values(self::$relation[$table])[0];
 
                        // Create a key for preventing double queries
-                       $qkey = $field.'-'.$table.':'.implode(':', array_keys($param)).':'.implode(':', $param);
+                       $qkey = $field . '-' . $table . ':' . json_encode($conditions);
 
                        // When the search field is the relation field, we don't need to fetch the rows
                        // This is useful when the leading record is already deleted in the frontend but the rest is done in the backend
-                       if ((count($param) == 1) && ($field == array_keys($param)[0])) {
+                       if ((count($conditions) == 1) && ($field == array_keys($conditions)[0])) {
                                foreach ($rel_def AS $rel_table => $rel_fields) {
                                        foreach ($rel_fields AS $rel_field) {
-                                               $retval = self::delete($rel_table, array($rel_field => array_values($param)[0]), true, $callstack);
+                                               $retval = self::delete($rel_table, [$rel_field => array_values($conditions)[0]], $options, true, $callstack);
                                                $commands = array_merge($commands, $retval);
                                        }
                                }
-                       // We quit when this key already exists in the callstack.
+                               // We quit when this key already exists in the callstack.
                        } elseif (!isset($callstack[$qkey])) {
 
                                $callstack[$qkey] = true;
 
                                // Fetch all rows that are to be deleted
-                               $data = self::select($table, array($field), $param);
+                               $data = self::select($table, [$field], $conditions);
 
                                while ($row = self::fetch($data)) {
                                        // Now we accumulate the delete commands
-                                       $retval = self::delete($table, array($field => $row[$field]), true, $callstack);
+                                       $retval = self::delete($table, [$field => $row[$field]], $options, true, $callstack);
                                        $commands = array_merge($commands, $retval);
                                }
 
@@ -934,24 +1082,21 @@ class dba {
                                self::transaction();
                        }
 
-                       $compacted = array();
-                       $counter = array();
+                       $compacted = [];
+                       $counter = [];
 
                        foreach ($commands AS $command) {
-                               $condition = $command['param'];
-                               $array_element = each($condition);
-                               $array_key = $array_element['key'];
-                               if (is_int($array_key)) {
-                                       $condition_string = " WHERE ".array_shift($condition);
-                               } else {
-                                       $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
-                               }
+                               $conditions = $command['conditions'];
+                               reset($conditions);
+                               $first_key = key($conditions);
 
-                               if ((count($command['param']) > 1) || is_int($array_key)) {
-                                       $sql = "DELETE FROM `".$command['table']."`".$condition_string;
-                                       logger(self::replace_parameters($sql, $condition), LOGGER_DATA);
+                               $condition_string = self::buildCondition($conditions);
 
-                                       if (!self::e($sql, $condition)) {
+                               if ((count($command['conditions']) > 1) || is_int($first_key)) {
+                                       $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
+                                       logger(self::replaceParameters($sql, $conditions), LOGGER_DATA);
+
+                                       if (!self::e($sql, $conditions)) {
                                                if ($do_transaction) {
                                                        self::rollback();
                                                }
@@ -959,27 +1104,27 @@ class dba {
                                        }
                                } else {
                                        $key_table = $command['table'];
-                                       $key_param = array_keys($command['param'])[0];
-                                       $value = array_values($command['param'])[0];
+                                       $key_condition = array_keys($command['conditions'])[0];
+                                       $value = array_values($command['conditions'])[0];
 
                                        // Split the SQL queries in chunks of 100 values
                                        // We do the $i stuff here to make the code better readable
-                                       $i = $counter[$key_table][$key_param];
-                                       if (count($compacted[$key_table][$key_param][$i]) > 100) {
+                                       $i = $counter[$key_table][$key_condition];
+                                       if (isset($compacted[$key_table][$key_condition][$i]) && count($compacted[$key_table][$key_condition][$i]) > 100) {
                                                ++$i;
                                        }
 
-                                       $compacted[$key_table][$key_param][$i][$value] = $value;
-                                       $counter[$key_table][$key_param] = $i;
+                                       $compacted[$key_table][$key_condition][$i][$value] = $value;
+                                       $counter[$key_table][$key_condition] = $i;
                                }
                        }
                        foreach ($compacted AS $table => $values) {
                                foreach ($values AS $field => $field_value_list) {
                                        foreach ($field_value_list AS $field_values) {
-                                               $sql = "DELETE FROM `".$table."` WHERE `".$field."` IN (".
-                                                       substr(str_repeat("?, ", count($field_values)), 0, -2).");";
+                                               $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
+                                                       substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
 
-                                               logger(self::replace_parameters($sql, $field_values), LOGGER_DATA);
+                                               logger(self::replaceParameters($sql, $field_values), LOGGER_DATA);
 
                                                if (!self::e($sql, $field_values)) {
                                                        if ($do_transaction) {
@@ -1027,7 +1172,7 @@ class dba {
         *
         * @return boolean was the update successfull?
         */
-       public static function update($table, $fields, $condition, $old_fields = array()) {
+       public static function update($table, $fields, $condition, $old_fields = []) {
 
                if (empty($table) || empty($fields) || empty($condition)) {
                        logger('Table, fields and condition have to be set');
@@ -1036,13 +1181,7 @@ class dba {
 
                $table = self::escape($table);
 
-               $array_element = each($condition);
-               $array_key = $array_element['key'];
-               if (is_int($array_key)) {
-                       $condition_string = " WHERE ".array_shift($condition);
-               } else {
-                       $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
-               }
+               $condition_string = self::buildCondition($condition);
 
                if (is_bool($old_fields)) {
                        $do_insert = $old_fields;
@@ -1054,7 +1193,7 @@ class dba {
                                        $values = array_merge($condition, $fields);
                                        return self::insert($table, $values, $do_insert);
                                }
-                               $old_fields = array();
+                               $old_fields = [];
                        }
                }
 
@@ -1086,7 +1225,7 @@ class dba {
 
        /**
         * Retrieve a single record from a table and returns it in an associative array
-        * 
+        *
         * @brief Retrieve a single record from a table
         * @param string $table
         * @param array  $fields
@@ -1137,6 +1276,8 @@ class dba {
                        return false;
                }
 
+               $table = self::escape($table);
+
                if (count($fields) > 0) {
                        $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
                } else {
@@ -1145,27 +1286,9 @@ class dba {
 
                $condition_string = self::buildCondition($condition);
 
-               if (isset($params['order'])) {
-                       $order_string = " ORDER BY ";
-                       foreach ($params['order'] AS $fields => $order) {
-                               if (!is_int($fields)) {
-                                       $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
-                               } else {
-                                       $order_string .= "`" . $order . "`, ";
-                               }
-                       }
-                       $order_string = substr($order_string, 0, -2);
-               }
-
-               if (isset($params['limit']) && is_int($params['limit'])) {
-                       $limit_string = " LIMIT " . $params['limit'];
-               }
-
-               if (isset($params['limit']) && is_array($params['limit'])) {
-                       $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
-               }
+               $param_string = self::buildParameter($params);
 
-               $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
+               $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $param_string;
 
                $result = self::p($sql, $condition);
 
@@ -1222,22 +1345,95 @@ class dba {
         * @param array $condition
         * @return string
         */
-       private static function buildCondition(array &$condition = [])
+       public static function buildCondition(array &$condition = [])
        {
                $condition_string = '';
                if (count($condition) > 0) {
-                       $array_element = each($condition);
-                       $array_key = $array_element['key'];
-                       if (is_int($array_key)) {
-                               $condition_string = " WHERE ".array_shift($condition);
+                       reset($condition);
+                       $first_key = key($condition);
+                       if (is_int($first_key)) {
+                               $condition_string = " WHERE (" . array_shift($condition) . ")";
                        } else {
-                               $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
+                               $new_values = [];
+                               $condition_string = "";
+                               foreach ($condition as $field => $value) {
+                                       if ($condition_string != "") {
+                                               $condition_string .= " AND ";
+                                       }
+                                       if (is_array($value)) {
+                                               /* Workaround for MySQL Bug #64791.
+                                                * Never mix data types inside any IN() condition.
+                                                * In case of mixed types, cast all as string.
+                                                * Logic needs to be consistent with dba::p() data types.
+                                                */
+                                               $is_int = false;
+                                               $is_alpha = false;
+                                               foreach ($value as $single_value) {
+                                                       if (is_int($single_value)) {
+                                                               $is_int = true;
+                                                       } else {
+                                                               $is_alpha = true;
+                                                       }
+                                               }
+                                               
+                                               if ($is_int && $is_alpha) {
+                                                       foreach ($value as &$ref) {
+                                                               if (is_int($ref)) {
+                                                                       $ref = (string)$ref;
+                                                               }
+                                                       }
+                                                       unset($ref); //Prevent accidental re-use.
+                                               }
+
+                                               $new_values = array_merge($new_values, array_values($value));
+                                               $placeholders = substr(str_repeat("?, ", count($value)), 0, -2);
+                                               $condition_string .= "`" . $field . "` IN (" . $placeholders . ")";
+                                       } else {
+                                               $new_values[$field] = $value;
+                                               $condition_string .= "`" . $field . "` = ?";
+                                       }
+                               }
+                               $condition_string = " WHERE (" . $condition_string . ")";
+                               $condition = $new_values;
                        }
                }
 
                return $condition_string;
        }
 
+       /**
+        * @brief Returns the SQL parameter string built from the provided parameter array
+        *
+        * @param array $params
+        * @return string
+        */
+       public static function buildParameter(array $params = [])
+       {
+               $order_string = '';
+               if (isset($params['order'])) {
+                       $order_string = " ORDER BY ";
+                       foreach ($params['order'] AS $fields => $order) {
+                               if (!is_int($fields)) {
+                                       $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
+                               } else {
+                                       $order_string .= "`" . $order . "`, ";
+                               }
+                       }
+                       $order_string = substr($order_string, 0, -2);
+               }
+
+               $limit_string = '';
+               if (isset($params['limit']) && is_int($params['limit'])) {
+                       $limit_string = " LIMIT " . $params['limit'];
+               }
+
+               if (isset($params['limit']) && is_array($params['limit'])) {
+                       $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
+               }
+
+               return $order_string.$limit_string;
+       }
+
        /**
         * @brief Fills an array with data from a query
         *
@@ -1249,7 +1445,7 @@ class dba {
                        return $stmt;
                }
 
-               $data = array();
+               $data = [];
                while ($row = self::fetch($stmt)) {
                        $data[] = $row;
                }
@@ -1284,17 +1480,37 @@ class dba {
         * @return boolean was the close successful?
         */
        public static function close($stmt) {
+               $a = get_app();
+
+               $stamp1 = microtime(true);
+
                if (!is_object($stmt)) {
                        return false;
                }
 
                switch (self::$driver) {
                        case 'pdo':
-                               return $stmt->closeCursor();
+                               $ret = $stmt->closeCursor();
+                               break;
                        case 'mysqli':
-                               $stmt->free_result();
-                               return $stmt->close();
+                               // MySQLi offers both a mysqli_stmt and a mysqli_result class.
+                               // We should be careful not to assume the object type of $stmt
+                               // because dba::p() has been able to return both types.
+                               if ($stmt instanceof mysqli_stmt) {
+                                       $stmt->free_result();
+                                       $ret = $stmt->close();
+                               } elseif ($stmt instanceof mysqli_result) {
+                                       $stmt->free();
+                                       $ret = true;
+                               } else {
+                                       $ret = false;
+                               }
+                               break;
                }
+
+               $a->save_timestamp($stamp1, 'database');
+
+               return $ret;
        }
 }