Merge pull request #6783 from nupplaphil/feature/replace_q_calls
authorHypolite Petovan <hypolite@mrpetovan.com>
Fri, 1 Mar 2019 21:49:52 +0000 (16:49 -0500)
committerGitHub <noreply@github.com>
Fri, 1 Mar 2019 21:49:52 +0000 (16:49 -0500)
Replace "q" calls in NotificationManager, UserImport & ForumManager

include/api.php
src/Content/ForumManager.php
src/Core/NotificationsManager.php
src/Core/UserImport.php
src/Database/DBStructure.php

index e6fd2f2..7df71d2 100644 (file)
@@ -5951,7 +5951,7 @@ function api_friendica_notification($type)
        }
        $nm = new NotificationsManager();
 
-       $notes = $nm->getAll([], "+seen -date", 50);
+       $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50);
 
        if ($type == "xml") {
                $xmlnotes = [];
index 0ef18df..e9dab41 100644 (file)
@@ -196,7 +196,7 @@ class ForumManager
         */
        public static function countUnseenItems()
        {
-               $r = q(
+               $stmtContacts = DBA::p(
                        "SELECT `contact`.`id`, `contact`.`name`, COUNT(*) AS `count` FROM `item`
                                INNER JOIN `contact` ON `item`.`contact-id` = `contact`.`id`
                                WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`deleted` AND `item`.`unseen`
@@ -208,6 +208,6 @@ class ForumManager
                        intval(local_user())
                );
 
-               return $r;
+               return DBA::toArray($stmtContacts);
        }
 }
index d582f21..4c6b932 100644 (file)
@@ -36,7 +36,7 @@ class NotificationsManager extends BaseObject
         *  - msg_plain: message as plain text string
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       private function _set_extra($notes)
+       private function _set_extra(array $notes)
        {
                $rets = [];
                foreach ($notes as $n) {
@@ -55,50 +55,28 @@ class NotificationsManager extends BaseObject
         * @brief Get all notifications for local_user()
         *
         * @param array  $filter optional Array "column name"=>value: filter query by columns values
-        * @param string $order  optional Space separated list of column to sort by.
-        *                       Prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
+        * @param array  $order  optional Array to order by
         * @param string $limit  optional Query limits
         *
-        * @return array of results or false on errors
+        * @return array|bool of results or false on errors
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       public function getAll($filter = [], $order = "-date", $limit = "")
+       public function getAll($filter = [], $order = ['date' => 'DESC'], $limit = "")
        {
-               $filter_str = [];
-               $filter_sql = "";
-               foreach ($filter as $column => $value) {
-                       $filter_str[] = sprintf("`%s` = '%s'", $column, DBA::escape($value));
-               }
-               if (count($filter_str) > 0) {
-                       $filter_sql = "AND " . implode(" AND ", $filter_str);
-               }
+               $params = [];
 
-               $aOrder = explode(" ", $order);
-               $asOrder = [];
-               foreach ($aOrder as $o) {
-                       $dir = "asc";
-                       if ($o[0] === "-") {
-                               $dir = "desc";
-                               $o = substr($o, 1);
-                       }
-                       if ($o[0] === "+") {
-                               $dir = "asc";
-                               $o = substr($o, 1);
-                       }
-                       $asOrder[] = "$o $dir";
-               }
-               $order_sql = implode(", ", $asOrder);
+               $params['order'] = $order;
 
-               if ($limit != "") {
-                       $limit = " LIMIT " . $limit;
+               if (!empty($limit)) {
+                       $params['limit'] = $limit;
                }
-               $r = q(
-                       "SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
-                       intval(local_user())
-               );
 
-               if (DBA::isResult($r)) {
-                       return $this->_set_extra($r);
+               $dbFilter = array_merge($filter, ['uid' => local_user()]);
+
+               $stmtNotifies = DBA::select('notify', [], $dbFilter, $order, $params);
+
+               if (DBA::isResult($stmtNotifies)) {
+                       return $this->_set_extra(DBA::toArray($stmtNotifies));
                }
 
                return false;
@@ -113,13 +91,9 @@ class NotificationsManager extends BaseObject
         */
        public function getByID($id)
        {
-               $r = q(
-                       "SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
-                       intval($id),
-                       intval(local_user())
-               );
-               if (DBA::isResult($r)) {
-                       return $this->_set_extra($r)[0];
+               $stmtNotify = DBA::selectFirst('notify', ['id' => $id, 'uid' => local_user()]);
+               if (DBA::isResult($stmtNotify)) {
+                       return $this->_set_extra([$stmtNotify])[0];
                }
                return null;
        }
@@ -134,14 +108,7 @@ class NotificationsManager extends BaseObject
         */
        public function setSeen($note, $seen = true)
        {
-               return q(
-                       "UPDATE `notify` SET `seen` = %d WHERE (`link` = '%s' OR (`parent` != 0 AND `parent` = %d AND `otype` = '%s')) AND `uid` = %d",
-                       intval($seen),
-                       DBA::escape($note['link']),
-                       intval($note['parent']),
-                       DBA::escape($note['otype']),
-                       intval(local_user())
-               );
+               return DBA::update('notify', ['seen' => $seen], ['link' => $note['link'], 'parent' => $note['parent'], 'otype' => $note['otype'], 'uid' => local_user()]);
        }
 
        /**
@@ -153,11 +120,7 @@ class NotificationsManager extends BaseObject
         */
        public function setAllSeen($seen = true)
        {
-               return q(
-                       "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
-                       intval($seen),
-                       intval(local_user())
-               );
+               return DBA::update('notify', ['seen' => $seen], ['uid' => local_user()]);
        }
 
        /**
@@ -460,20 +423,21 @@ class NotificationsManager extends BaseObject
                $notifs = [];
                $sql_seen = "";
 
+               $filter = ['uid' => local_user()];
                if ($seen === 0) {
-                       $sql_seen = " AND NOT `seen` ";
+                       $filter['seen'] = false;
                }
 
-               $r = q(
-                       "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen`, `verb` FROM `notify`
-                               WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
-                       intval(local_user()),
-                       intval($start),
-                       intval($limit)
-               );
+               $params = [];
+               $params['limit'] = [$start, $limit];
+
+               $stmtNotifies = DBA::select('notify',
+                       ['id', 'url', 'photo', 'msg', 'date', 'seen', 'verb'],
+                       $filter,
+                       $params);
 
-               if (DBA::isResult($r)) {
-                       $notifs = $this->formatNotifs($r, $ident);
+               if (DBA::isResult($stmtNotifies)) {
+                       $notifs = $this->formatNotifs(DBA::toArray($stmtNotifies), $ident);
                }
 
                $arr = [
@@ -596,7 +560,7 @@ class NotificationsManager extends BaseObject
                }
 
                /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
-               $r = q(
+               $stmtNotifies = DBA::p(
                        "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
                                `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
                                `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
@@ -613,8 +577,8 @@ class NotificationsManager extends BaseObject
                        intval($start),
                        intval($limit)
                );
-               if (DBA::isResult($r)) {
-                       $notifs = $this->formatIntros($r);
+               if (DBA::isResult($stmtNotifies)) {
+                       $notifs = $this->formatIntros(DBA::toArray($stmtNotifies));
                }
 
                $arr = [
index 1e103c1..0a4223f 100644 (file)
@@ -6,6 +6,7 @@ namespace Friendica\Core;
 
 use Friendica\App;
 use Friendica\Database\DBA;
+use Friendica\Database\DBStructure;
 use Friendica\Model\Photo;
 use Friendica\Object\Image;
 use Friendica\Util\Strings;
@@ -35,12 +36,11 @@ class UserImport
         */
        private static function checkCols($table, &$arr)
        {
-               $query = sprintf("SHOW COLUMNS IN `%s`", DBA::escape($table));
-               Logger::log("uimport: $query", Logger::DEBUG);
-               $r = q($query);
+               $tableColumns = DBStructure::getColumns($table);
+
                $tcols = [];
                // get a plain array of column names
-               foreach ($r as $tcol) {
+               foreach ($tableColumns as $tcol) {
                        $tcols[] = $tcol['Field'];
                }
                // remove inexistent columns
@@ -66,16 +66,12 @@ class UserImport
                }
 
                self::checkCols($table, $arr);
-               $cols = implode("`,`", array_map(['Friendica\Database\DBA', 'escape'], array_keys($arr)));
-               $vals = implode("','", array_map(['Friendica\Database\DBA', 'escape'], array_values($arr)));
-               $query = "INSERT INTO `$table` (`$cols`) VALUES ('$vals')";
-               Logger::log("uimport: $query", Logger::TRACE);
 
                if (self::IMPORT_DEBUG) {
                        return true;
                }
 
-               return q($query);
+               return DBA::insert($table, $arr);
        }
 
        /**
index 75a5c86..abbac4e 100644 (file)
@@ -844,4 +844,18 @@ class DBStructure
 
                return $retval;
        }
+
+       /**
+        * Returns the columns of a table
+        *
+        * @param string $table Table name
+        *
+        * @return array An array of the table columns
+        * @throws Exception
+        */
+       public static function getColumns($table)
+       {
+               $stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
+               return DBA::toArray($stmtColumns);
+       }
 }