]> git.mxchange.org Git - friendica.git/blobdiff - include/dba.php
Replace dba::select(limit => 1) by dba::selectOne
[friendica.git] / include / dba.php
index 74e9d7c061dd3b62c8641e1a87257efcb1e58b75..3a72d596491741a6b3928ffbfb1c7fe74d488780 100644 (file)
@@ -1,7 +1,8 @@
 <?php
-use \Friendica\Core\System;
+use Friendica\Core\System;
+use Friendica\Database\DBM;
+use Friendica\Database\DBStructure;
 
-require_once("dbm.php");
 require_once('include/datetime.php');
 
 /**
@@ -93,23 +94,11 @@ class dba {
                        }
                }
 
-               if (!self::$connected && function_exists('mysql_connect')) {
-                       self::$driver = 'mysql';
-                       self::$db = mysql_connect($serveraddr, $user, $pass);
-                       if (self::$db && mysql_select_db($db, self::$db)) {
-                               self::$connected = true;
-
-                               if (isset($a->config["system"]["db_charset"])) {
-                                       mysql_set_charset($a->config["system"]["db_charset"], self::$db);
-                               }
-                       }
-               }
-
                // No suitable SQL driver was found.
                if (!self::$connected) {
                        self::$db = null;
                        if (!$install) {
-                               system_unavailable();
+                               System::unavailable();
                        }
                }
                $a->save_timestamp($stamp1, "network");
@@ -134,9 +123,6 @@ class dba {
                                case 'mysqli':
                                        self::$_server_info = self::$db->server_info;
                                        break;
-                               case 'mysql':
-                                       self::$_server_info = mysql_get_server_info(self::$db);
-                                       break;
                        }
                }
                return self::$_server_info;
@@ -176,7 +162,7 @@ class dba {
                }
 
                $r = self::p("EXPLAIN ".$query);
-               if (!dbm::is_result($r)) {
+               if (!DBM::is_result($r)) {
                        return;
                }
 
@@ -216,8 +202,6 @@ class dba {
                                return substr(@self::$db->quote($str, PDO::PARAM_STR), 1, -1);
                        case 'mysqli':
                                return @self::$db->real_escape_string($str);
-                       case 'mysql':
-                               return @mysql_real_escape_string($str,self::$db);
                }
        }
 
@@ -227,7 +211,7 @@ class dba {
                switch (self::$driver) {
                        case 'pdo':
                                $r = dba::p("SELECT 1");
-                               if (dbm::is_result($r)) {
+                               if (DBM::is_result($r)) {
                                        $row = dba::inArray($r);
                                        $connected = ($row[0]['1'] == '1');
                                }
@@ -235,9 +219,6 @@ class dba {
                        case 'mysqli':
                                $connected = self::$db->ping();
                                break;
-                       case 'mysql':
-                               $connected = mysql_ping(self::$db);
-                               break;
                }
                return $connected;
        }
@@ -485,22 +466,6 @@ class dba {
                                        self::$affected_rows = $retval->affected_rows;
                                }
                                break;
-                       case 'mysql':
-                               // For the old "mysql" functions we cannot use prepared statements
-                               $retval = mysql_query(self::replace_parameters($sql, $args), self::$db);
-                               if (mysql_errno(self::$db)) {
-                                       self::$error = mysql_error(self::$db);
-                                       self::$errorno = mysql_errno(self::$db);
-                               } else {
-                                       self::$affected_rows = mysql_affected_rows($retval);
-
-                                       // Due to missing mysql_* support this here wasn't tested at all
-                                       // See here: http://php.net/manual/en/function.mysql-num-rows.php
-                                       if (self::$affected_rows <= 0) {
-                                               self::$affected_rows = mysql_num_rows($retval);
-                                       }
-                               }
-                               break;
                }
 
                // We are having an own error logging in the function "e"
@@ -607,7 +572,7 @@ class dba {
                        $fields = array($array_key);
                }
 
-               $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true));
+               $stmt = self::select($table, $fields, $condition, ['limit' => 1]);
 
                if (is_bool($stmt)) {
                        $retval = $stmt;
@@ -668,8 +633,6 @@ class dba {
                                return $stmt->columnCount();
                        case 'mysqli':
                                return $stmt->field_count;
-                       case 'mysql':
-                               return mysql_affected_rows($stmt);
                }
                return 0;
        }
@@ -688,8 +651,6 @@ class dba {
                                return $stmt->rowCount();
                        case 'mysqli':
                                return $stmt->num_rows;
-                       case 'mysql':
-                               return mysql_num_rows($stmt);
                }
                return 0;
        }
@@ -740,8 +701,6 @@ class dba {
                                        $columns[$fields[$param]->name] = $col;
                                }
                                return $columns;
-                       case 'mysql':
-                               return mysql_fetch_array($stmt, MYSQL_ASSOC);
                }
        }
 
@@ -755,6 +714,12 @@ class dba {
         * @return boolean was the insert successfull?
         */
        public static function insert($table, $param, $on_duplicate_update = false) {
+
+               if (empty($table) || empty($param)) {
+                       logger('Table and fields have to be set');
+                       return false;
+               }
+
                $sql = "INSERT INTO `".self::escape($table)."` (`".implode("`, `", array_keys($param))."`) VALUES (".
                        substr(str_repeat("?, ", count($param)), 0, -2).")";
 
@@ -781,9 +746,6 @@ class dba {
                        case 'mysqli':
                                $id = self::$db->insert_id;
                                break;
-                       case 'mysql':
-                               $id = mysql_insert_id(self::$db);
-                               break;
                }
                return $id;
        }
@@ -868,12 +830,12 @@ class dba {
        /**
         * @brief Build the array with the table relations
         *
-        * The array is build from the database definitions in dbstructure.php
+        * The array is build from the database definitions in DBStructure.php
         *
         * This process must only be started once, since the value is cached.
         */
        private static function build_relation_data() {
-               $definition = db_definition();
+               $definition = DBStructure::definition();
 
                foreach ($definition AS $table => $structure) {
                        foreach ($structure['fields'] AS $field => $field_struct) {
@@ -897,6 +859,12 @@ class dba {
         * @return boolean|array was the delete successfull? 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');
+                       return false;
+               }
+
                $commands = array();
 
                // Create a key for the loop prevention
@@ -1059,24 +1027,26 @@ class dba {
         * @return boolean was the update successfull?
         */
        public static function update($table, $fields, $condition, $old_fields = array()) {
+
+               if (empty($table) || empty($fields) || empty($condition)) {
+                       logger('Table, fields and condition have to be set');
+                       return false;
+               }
+
                $table = self::escape($table);
 
-               if (count($condition) > 0) {
-                       $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))."` = ?";
-                       }
+               $array_element = each($condition);
+               $array_key = $array_element['key'];
+               if (is_int($array_key)) {
+                       $condition_string = " WHERE ".array_shift($condition);
                } else {
-                       $condition_string = "";
+                       $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
                }
 
                if (is_bool($old_fields)) {
                        $do_insert = $old_fields;
 
-                       $old_fields = self::select($table, array(), $condition, array('limit' => 1));
+                       $old_fields = self::selectOne($table, [], $condition);
 
                        if (is_bool($old_fields)) {
                                if ($do_insert) {
@@ -1113,6 +1083,31 @@ class dba {
                return self::e($sql, $params);
        }
 
+       /**
+        * 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
+        * @param array  $condition
+        * @param array  $params
+        * @return bool|array
+        * @see dba::select
+        */
+       public static function selectOne($table, array $fields = [], array $condition = [], $params = [])
+       {
+               $params['limit'] = 1;
+               $result = self::select($table, $fields, $condition, $params);
+
+               if (is_bool($result)) {
+                       return $result;
+               } else {
+                       $row = self::fetch($result);
+                       self::close($result);
+                       return $row;
+               }
+       }
+
        /**
         * @brief Select rows from a table
         *
@@ -1135,66 +1130,112 @@ class dba {
         *
         * $data = dba::select($table, $fields, $condition, $params);
         */
-       public static function select($table, $fields = array(), $condition = array(), $params = array()) {
+       public static function select($table, array $fields = [], array $condition = [], array $params = [])
+       {
                if ($table == '') {
                        return false;
                }
 
                if (count($fields) > 0) {
-                       $select_fields = "`".implode("`, `", array_values($fields))."`";
+                       $select_fields = "`" . implode("`, `", array_values($fields)) . "`";
                } else {
                        $select_fields = "*";
                }
 
-               if (count($condition) > 0) {
-                       $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))."` = ?";
-                       }
-               } else {
-                       $condition_string = "";
-               }
-
-               $param_string = '';
-               $single_row = false;
+               $condition_string = self::buildCondition($condition);
 
                if (isset($params['order'])) {
-                       $param_string .= " ORDER BY ";
+                       $order_string = " ORDER BY ";
                        foreach ($params['order'] AS $fields => $order) {
                                if (!is_int($fields)) {
-                                       $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", ";
+                                       $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", ";
                                } else {
-                                       $param_string .= "`".$order."`, ";
+                                       $order_string .= "`" . $order . "`, ";
                                }
                        }
-                       $param_string = substr($param_string, 0, -2);
+                       $order_string = substr($order_string, 0, -2);
                }
 
                if (isset($params['limit']) && is_int($params['limit'])) {
-                       $param_string .= " LIMIT ".$params['limit'];
-                       $single_row = ($params['limit'] == 1);
+                       $limit_string = " LIMIT " . $params['limit'];
                }
 
-               if (isset($params['only_query']) && $params['only_query']) {
-                       $single_row = !$params['only_query'];
+               if (isset($params['limit']) && is_array($params['limit'])) {
+                       $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]);
                }
 
-               $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string;
+               $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string;
 
                $result = self::p($sql, $condition);
 
-               if (is_bool($result) || !$single_row) {
-                       return $result;
-               } else {
-                       $row = self::fetch($result);
-                       self::close($result);
-                       return $row;
+               return $result;
+       }
+
+       /**
+        * @brief Counts the rows from a table satisfying the provided condition
+        *
+        * @param string $table Table name
+        * @param array $condition array of fields for condition
+        *
+        * @return int
+        *
+        * Example:
+        * $table = "item";
+        *
+        * $condition = ["uid" => 1, "network" => 'dspr'];
+        * or:
+        * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
+        *
+        * $count = dba::count($table, $condition);
+        */
+       public static function count($table, array $condition = [])
+       {
+               if ($table == '') {
+                       return false;
                }
+
+               $condition_string = self::buildCondition($condition);
+
+               $sql = "SELECT COUNT(*) AS `count` FROM `".$table."`".$condition_string;
+
+               $row = self::fetch_first($sql, $condition);
+
+               return $row['count'];
        }
 
+       /**
+        * @brief Returns the SQL condition string built from the provided condition array
+        *
+        * This function operates with two modes.
+        * - Supplied with a filed/value associative array, it builds simple strict
+        *   equality conditions linked by AND.
+        * - Supplied with a flat list, the first element is the condition string and
+        *   the following arguments are the values to be interpolated
+        *
+        * $condition = ["uid" => 1, "network" => 'dspr'];
+        * or:
+        * $condition = ["`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'];
+        *
+        * In either case, the provided array is left with the parameters only
+        *
+        * @param array $condition
+        * @return string
+        */
+       private 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);
+                       } else {
+                               $condition_string = " WHERE `".implode("` = ? AND `", array_keys($condition))."` = ?";
+                       }
+               }
+
+               return $condition_string;
+       }
 
        /**
         * @brief Fills an array with data from a query
@@ -1250,10 +1291,8 @@ class dba {
                        case 'pdo':
                                return $stmt->closeCursor();
                        case 'mysqli':
-                               return $stmt->free_result();
+                               $stmt->free_result();
                                return $stmt->close();
-                       case 'mysql':
-                               return mysql_free_result($stmt);
                }
        }
 }
@@ -1274,7 +1313,7 @@ function dbesc($str) {
  * dba::delete, dba::update, dba::p, dba::e
  *
  * @param $args Query parameters (1 to N parameters of different types)
- * @return array Query array
+ * @return array|bool Query array
  */
 function q($sql) {
        $args = func_get_args();