]> git.immae.eu Git - github/shaarli/Shaarli.git/blobdiff - application/feed/FeedBuilder.php
Handle pagination through BookmarkService
[github/shaarli/Shaarli.git] / application / feed / FeedBuilder.php
index b66f2f918edd494f1d11090892fbcfda7d073e59..d5d74fd143adb105ede408865b7914681bad6ece 100644 (file)
@@ -1,7 +1,11 @@
 <?php
+
 namespace Shaarli\Feed;
 
 use DateTime;
+use Shaarli\Bookmark\Bookmark;
+use Shaarli\Bookmark\BookmarkServiceInterface;
+use Shaarli\Formatter\BookmarkFormatter;
 
 /**
  * FeedBuilder class.
@@ -26,37 +30,30 @@ class FeedBuilder
     public static $DEFAULT_LANGUAGE = 'en-en';
 
     /**
-     * @var int Number of links to display in a feed by default.
+     * @var int Number of bookmarks to display in a feed by default.
      */
     public static $DEFAULT_NB_LINKS = 50;
 
     /**
-     * @var \Shaarli\Bookmark\LinkDB instance.
+     * @var BookmarkServiceInterface instance.
      */
     protected $linkDB;
 
     /**
-     * @var string RSS or ATOM feed.
+     * @var BookmarkFormatter instance.
      */
-    protected $feedType;
+    protected $formatter;
 
-    /**
-     * @var array $_SERVER
-     */
+    /** @var mixed[] $_SERVER */
     protected $serverInfo;
 
-    /**
-     * @var array $_GET
-     */
-    protected $userInput;
-
     /**
      * @var boolean True if the user is currently logged in, false otherwise.
      */
     protected $isLoggedIn;
 
     /**
-     * @var boolean Use permalinks instead of direct links if true.
+     * @var boolean Use permalinks instead of direct bookmarks if true.
      */
     protected $usePermalinks;
 
@@ -69,7 +66,6 @@ class FeedBuilder
      * @var string server locale.
      */
     protected $locale;
-
     /**
      * @var DateTime Latest item date.
      */
@@ -78,115 +74,61 @@ class FeedBuilder
     /**
      * Feed constructor.
      *
-     * @param \Shaarli\Bookmark\LinkDB $linkDB     LinkDB instance.
-     * @param string                   $feedType   Type of feed.
+     * @param BookmarkServiceInterface $linkDB     LinkDB instance.
+     * @param BookmarkFormatter        $formatter  instance.
      * @param array                    $serverInfo $_SERVER.
-     * @param array                    $userInput  $_GET.
-     * @param boolean                  $isLoggedIn True if the user is currently logged in,
-     *                                             false otherwise.
+     * @param boolean                  $isLoggedIn True if the user is currently logged in, false otherwise.
      */
-    public function __construct($linkDB, $feedType, $serverInfo, $userInput, $isLoggedIn)
+    public function __construct($linkDB, $formatter, $serverInfo, $isLoggedIn)
     {
         $this->linkDB = $linkDB;
-        $this->feedType = $feedType;
+        $this->formatter = $formatter;
         $this->serverInfo = $serverInfo;
-        $this->userInput = $userInput;
         $this->isLoggedIn = $isLoggedIn;
     }
 
     /**
      * Build data for feed templates.
      *
+     * @param string $feedType   Type of feed (RSS/ATOM).
+     * @param array  $userInput  $_GET.
+     *
      * @return array Formatted data for feeds templates.
      */
-    public function buildData()
+    public function buildData(string $feedType, ?array $userInput)
     {
-        // Search for untagged links
-        if (isset($this->userInput['searchtags']) && empty($this->userInput['searchtags'])) {
-            $this->userInput['searchtags'] = false;
+        // Search for untagged bookmarks
+        if (isset($this->userInput['searchtags']) && empty($userInput['searchtags'])) {
+            $userInput['searchtags'] = false;
         }
 
-        // Optionally filter the results:
-        $linksToDisplay = $this->linkDB->filterSearch($this->userInput);
-
-        $nblinksToDisplay = $this->getNbLinks(count($linksToDisplay));
+        $limit = $this->getLimit($userInput);
 
-        // Can't use array_keys() because $link is a LinkDB instance and not a real array.
-        $keys = array();
-        foreach ($linksToDisplay as $key => $value) {
-            $keys[] = $key;
-        }
+        // Optionally filter the results:
+        $searchResult = $this->linkDB->search($userInput ?? [], null, false, false, true, ['limit' => $limit]);
 
         $pageaddr = escape(index_url($this->serverInfo));
-        $linkDisplayed = array();
-        for ($i = 0; $i < $nblinksToDisplay && $i < count($keys); $i++) {
-            $linkDisplayed[$keys[$i]] = $this->buildItem($linksToDisplay[$keys[$i]], $pageaddr);
+        $this->formatter->addContextData('index_url', $pageaddr);
+        $links = [];
+        foreach ($searchResult->getBookmarks() as $key => $bookmark) {
+            $links[$key] = $this->buildItem($feedType, $bookmark, $pageaddr);
         }
 
-        $data['language'] = $this->getTypeLanguage();
-        $data['last_update'] = $this->getLatestDateFormatted();
+        $data['language'] = $this->getTypeLanguage($feedType);
+        $data['last_update'] = $this->getLatestDateFormatted($feedType);
         $data['show_dates'] = !$this->hideDates || $this->isLoggedIn;
-        // Remove leading slash from REQUEST_URI.
-        $data['self_link'] = escape(server_url($this->serverInfo))
-            . escape($this->serverInfo['REQUEST_URI']);
+        // Remove leading path from REQUEST_URI (already contained in $pageaddr).
+        $requestUri = preg_replace('#(.*?/)(feed.*)#', '$2', escape($this->serverInfo['REQUEST_URI']));
+        $data['self_link'] = $pageaddr . $requestUri;
         $data['index_url'] = $pageaddr;
         $data['usepermalinks'] = $this->usePermalinks === true;
-        $data['links'] = $linkDisplayed;
+        $data['links'] = $links;
 
         return $data;
     }
 
     /**
-     * Build a feed item (one per shaare).
-     *
-     * @param array  $link     Single link array extracted from LinkDB.
-     * @param string $pageaddr Index URL.
-     *
-     * @return array Link array with feed attributes.
-     */
-    protected function buildItem($link, $pageaddr)
-    {
-        $link['guid'] = $pageaddr . '?' . $link['shorturl'];
-        // Check for both signs of a note: starting with ? and 7 chars long.
-        if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
-            $link['url'] = $pageaddr . $link['url'];
-        }
-        if ($this->usePermalinks === true) {
-            $permalink = '<a href="' . $link['url'] . '" title="' . t('Direct link') . '">' . t('Direct link') . '</a>';
-        } else {
-            $permalink = '<a href="' . $link['guid'] . '" title="' . t('Permalink') . '">' . t('Permalink') . '</a>';
-        }
-        $link['description'] = format_description($link['description'], '', false, $pageaddr);
-        $link['description'] .= PHP_EOL . '<br>&#8212; ' . $permalink;
-
-        $pubDate = $link['created'];
-        $link['pub_iso_date'] = $this->getIsoDate($pubDate);
-
-        // atom:entry elements MUST contain exactly one atom:updated element.
-        if (!empty($link['updated'])) {
-            $upDate = $link['updated'];
-            $link['up_iso_date'] = $this->getIsoDate($upDate, DateTime::ATOM);
-        } else {
-            $link['up_iso_date'] = $this->getIsoDate($pubDate, DateTime::ATOM);
-        }
-
-        // Save the more recent item.
-        if (empty($this->latestDate) || $this->latestDate < $pubDate) {
-            $this->latestDate = $pubDate;
-        }
-        if (!empty($upDate) && $this->latestDate < $upDate) {
-            $this->latestDate = $upDate;
-        }
-
-        $taglist = array_filter(explode(' ', $link['tags']), 'strlen');
-        uasort($taglist, 'strcasecmp');
-        $link['taglist'] = $taglist;
-
-        return $link;
-    }
-
-    /**
-     * Set this to true to use permalinks instead of direct links.
+     * Set this to true to use permalinks instead of direct bookmarks.
      *
      * @param boolean $usePermalinks true to force permalinks.
      */
@@ -215,22 +157,64 @@ class FeedBuilder
         $this->locale = strtolower($locale);
     }
 
+    /**
+     * Build a feed item (one per shaare).
+     *
+     * @param string $feedType Type of feed (RSS/ATOM).
+     * @param Bookmark $link     Single link array extracted from LinkDB.
+     * @param string   $pageaddr Index URL.
+     *
+     * @return array Link array with feed attributes.
+     */
+    protected function buildItem(string $feedType, $link, $pageaddr)
+    {
+        $data = $this->formatter->format($link);
+        $data['guid'] = rtrim($pageaddr, '/') . '/shaare/' . $data['shorturl'];
+        if ($this->usePermalinks === true) {
+            $permalink = '<a href="' . $data['url'] . '" title="' . t('Direct link') . '">' . t('Direct link') . '</a>';
+        } else {
+            $permalink = '<a href="' . $data['guid'] . '" title="' . t('Permalink') . '">' . t('Permalink') . '</a>';
+        }
+        $data['description'] .= PHP_EOL . PHP_EOL . '<br>&#8212; ' . $permalink;
+
+        $data['pub_iso_date'] = $this->getIsoDate($feedType, $data['created']);
+
+        // atom:entry elements MUST contain exactly one atom:updated element.
+        if (!empty($link->getUpdated())) {
+            $data['up_iso_date'] = $this->getIsoDate($feedType, $data['updated'], DateTime::ATOM);
+        } else {
+            $data['up_iso_date'] = $this->getIsoDate($feedType, $data['created'], DateTime::ATOM);
+        }
+
+        // Save the more recent item.
+        if (empty($this->latestDate) || $this->latestDate < $data['created']) {
+            $this->latestDate = $data['created'];
+        }
+        if (!empty($data['updated']) && $this->latestDate < $data['updated']) {
+            $this->latestDate = $data['updated'];
+        }
+
+        return $data;
+    }
+
     /**
      * Get the language according to the feed type, based on the locale:
      *
      *   - RSS format: en-us (default: 'en-en').
      *   - ATOM format: fr (default: 'en').
      *
+     * @param string $feedType Type of feed (RSS/ATOM).
+     *
      * @return string The language.
      */
-    public function getTypeLanguage()
+    protected function getTypeLanguage(string $feedType)
     {
         // Use the locale do define the language, if available.
         if (!empty($this->locale) && preg_match('/^\w{2}[_\-]\w{2}/', $this->locale)) {
-            $length = ($this->feedType === self::$FEED_RSS) ? 5 : 2;
+            $length = ($feedType === self::$FEED_RSS) ? 5 : 2;
             return str_replace('_', '-', substr($this->locale, 0, $length));
         }
-        return ($this->feedType === self::$FEED_RSS) ? 'en-en' : 'en';
+        return ($feedType === self::$FEED_RSS) ? 'en-en' : 'en';
     }
 
     /**
@@ -238,32 +222,35 @@ class FeedBuilder
      *
      * Return an empty string if invalid DateTime is passed.
      *
+     * @param string $feedType Type of feed (RSS/ATOM).
+     *
      * @return string Formatted date.
      */
-    protected function getLatestDateFormatted()
+    protected function getLatestDateFormatted(string $feedType)
     {
         if (empty($this->latestDate) || !$this->latestDate instanceof DateTime) {
             return '';
         }
 
-        $type = ($this->feedType == self::$FEED_RSS) ? DateTime::RSS : DateTime::ATOM;
+        $type = ($feedType == self::$FEED_RSS) ? DateTime::RSS : DateTime::ATOM;
         return $this->latestDate->format($type);
     }
 
     /**
      * Get ISO date from DateTime according to feed type.
      *
+     * @param string      $feedType Type of feed (RSS/ATOM).
      * @param DateTime    $date   Date to format.
      * @param string|bool $format Force format.
      *
      * @return string Formatted date.
      */
-    protected function getIsoDate(DateTime $date, $format = false)
+    protected function getIsoDate(string $feedType, DateTime $date, $format = false)
     {
         if ($format !== false) {
             return $date->format($format);
         }
-        if ($this->feedType == self::$FEED_RSS) {
+        if ($feedType == self::$FEED_RSS) {
             return $date->format(DateTime::RSS);
         }
         return $date->format(DateTime::ATOM);
@@ -273,23 +260,23 @@ class FeedBuilder
      * Returns the number of link to display according to 'nb' user input parameter.
      *
      * If 'nb' not set or invalid, default value: $DEFAULT_NB_LINKS.
-     * If 'nb' is set to 'all', display all filtered links (max parameter).
+     * If 'nb' is set to 'all', display all filtered bookmarks (max parameter).
      *
-     * @param int $max maximum number of links to display.
+     * @param array $userInput $_GET.
      *
-     * @return int number of links to display.
+     * @return int number of bookmarks to display.
      */
-    public function getNbLinks($max)
+    protected function getLimit(?array $userInput)
     {
-        if (empty($this->userInput['nb'])) {
+        if (empty($userInput['nb'])) {
             return self::$DEFAULT_NB_LINKS;
         }
 
-        if ($this->userInput['nb'] == 'all') {
-            return $max;
+        if ($userInput['nb'] == 'all') {
+            return null;
         }
 
-        $intNb = intval($this->userInput['nb']);
+        $intNb = intval($userInput['nb']);
         if (!is_int($intNb) || $intNb == 0) {
             return self::$DEFAULT_NB_LINKS;
         }