]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/feed/FeedBuilder.php
Handle pagination through BookmarkService
[github/shaarli/Shaarli.git] / application / feed / FeedBuilder.php
1 <?php
2
3 namespace Shaarli\Feed;
4
5 use DateTime;
6 use Shaarli\Bookmark\Bookmark;
7 use Shaarli\Bookmark\BookmarkServiceInterface;
8 use Shaarli\Formatter\BookmarkFormatter;
9
10 /**
11 * FeedBuilder class.
12 *
13 * Used to build ATOM and RSS feeds data.
14 */
15 class FeedBuilder
16 {
17 /**
18 * @var string Constant: RSS feed type.
19 */
20 public static $FEED_RSS = 'rss';
21
22 /**
23 * @var string Constant: ATOM feed type.
24 */
25 public static $FEED_ATOM = 'atom';
26
27 /**
28 * @var string Default language if the locale isn't set.
29 */
30 public static $DEFAULT_LANGUAGE = 'en-en';
31
32 /**
33 * @var int Number of bookmarks to display in a feed by default.
34 */
35 public static $DEFAULT_NB_LINKS = 50;
36
37 /**
38 * @var BookmarkServiceInterface instance.
39 */
40 protected $linkDB;
41
42 /**
43 * @var BookmarkFormatter instance.
44 */
45 protected $formatter;
46
47 /** @var mixed[] $_SERVER */
48 protected $serverInfo;
49
50 /**
51 * @var boolean True if the user is currently logged in, false otherwise.
52 */
53 protected $isLoggedIn;
54
55 /**
56 * @var boolean Use permalinks instead of direct bookmarks if true.
57 */
58 protected $usePermalinks;
59
60 /**
61 * @var boolean true to hide dates in feeds.
62 */
63 protected $hideDates;
64
65 /**
66 * @var string server locale.
67 */
68 protected $locale;
69 /**
70 * @var DateTime Latest item date.
71 */
72 protected $latestDate;
73
74 /**
75 * Feed constructor.
76 *
77 * @param BookmarkServiceInterface $linkDB LinkDB instance.
78 * @param BookmarkFormatter $formatter instance.
79 * @param array $serverInfo $_SERVER.
80 * @param boolean $isLoggedIn True if the user is currently logged in, false otherwise.
81 */
82 public function __construct($linkDB, $formatter, $serverInfo, $isLoggedIn)
83 {
84 $this->linkDB = $linkDB;
85 $this->formatter = $formatter;
86 $this->serverInfo = $serverInfo;
87 $this->isLoggedIn = $isLoggedIn;
88 }
89
90 /**
91 * Build data for feed templates.
92 *
93 * @param string $feedType Type of feed (RSS/ATOM).
94 * @param array $userInput $_GET.
95 *
96 * @return array Formatted data for feeds templates.
97 */
98 public function buildData(string $feedType, ?array $userInput)
99 {
100 // Search for untagged bookmarks
101 if (isset($this->userInput['searchtags']) && empty($userInput['searchtags'])) {
102 $userInput['searchtags'] = false;
103 }
104
105 $limit = $this->getLimit($userInput);
106
107 // Optionally filter the results:
108 $searchResult = $this->linkDB->search($userInput ?? [], null, false, false, true, ['limit' => $limit]);
109
110 $pageaddr = escape(index_url($this->serverInfo));
111 $this->formatter->addContextData('index_url', $pageaddr);
112 $links = [];
113 foreach ($searchResult->getBookmarks() as $key => $bookmark) {
114 $links[$key] = $this->buildItem($feedType, $bookmark, $pageaddr);
115 }
116
117 $data['language'] = $this->getTypeLanguage($feedType);
118 $data['last_update'] = $this->getLatestDateFormatted($feedType);
119 $data['show_dates'] = !$this->hideDates || $this->isLoggedIn;
120 // Remove leading path from REQUEST_URI (already contained in $pageaddr).
121 $requestUri = preg_replace('#(.*?/)(feed.*)#', '$2', escape($this->serverInfo['REQUEST_URI']));
122 $data['self_link'] = $pageaddr . $requestUri;
123 $data['index_url'] = $pageaddr;
124 $data['usepermalinks'] = $this->usePermalinks === true;
125 $data['links'] = $links;
126
127 return $data;
128 }
129
130 /**
131 * Set this to true to use permalinks instead of direct bookmarks.
132 *
133 * @param boolean $usePermalinks true to force permalinks.
134 */
135 public function setUsePermalinks($usePermalinks)
136 {
137 $this->usePermalinks = $usePermalinks;
138 }
139
140 /**
141 * Set this to true to hide timestamps in feeds.
142 *
143 * @param boolean $hideDates true to enable.
144 */
145 public function setHideDates($hideDates)
146 {
147 $this->hideDates = $hideDates;
148 }
149
150 /**
151 * Set the locale. Used to show feed language.
152 *
153 * @param string $locale The locale (eg. 'fr_FR.UTF8').
154 */
155 public function setLocale($locale)
156 {
157 $this->locale = strtolower($locale);
158 }
159
160 /**
161 * Build a feed item (one per shaare).
162 *
163 * @param string $feedType Type of feed (RSS/ATOM).
164 * @param Bookmark $link Single link array extracted from LinkDB.
165 * @param string $pageaddr Index URL.
166 *
167 * @return array Link array with feed attributes.
168 */
169 protected function buildItem(string $feedType, $link, $pageaddr)
170 {
171 $data = $this->formatter->format($link);
172 $data['guid'] = rtrim($pageaddr, '/') . '/shaare/' . $data['shorturl'];
173 if ($this->usePermalinks === true) {
174 $permalink = '<a href="' . $data['url'] . '" title="' . t('Direct link') . '">' . t('Direct link') . '</a>';
175 } else {
176 $permalink = '<a href="' . $data['guid'] . '" title="' . t('Permalink') . '">' . t('Permalink') . '</a>';
177 }
178 $data['description'] .= PHP_EOL . PHP_EOL . '<br>&#8212; ' . $permalink;
179
180 $data['pub_iso_date'] = $this->getIsoDate($feedType, $data['created']);
181
182 // atom:entry elements MUST contain exactly one atom:updated element.
183 if (!empty($link->getUpdated())) {
184 $data['up_iso_date'] = $this->getIsoDate($feedType, $data['updated'], DateTime::ATOM);
185 } else {
186 $data['up_iso_date'] = $this->getIsoDate($feedType, $data['created'], DateTime::ATOM);
187 }
188
189 // Save the more recent item.
190 if (empty($this->latestDate) || $this->latestDate < $data['created']) {
191 $this->latestDate = $data['created'];
192 }
193 if (!empty($data['updated']) && $this->latestDate < $data['updated']) {
194 $this->latestDate = $data['updated'];
195 }
196
197 return $data;
198 }
199
200 /**
201 * Get the language according to the feed type, based on the locale:
202 *
203 * - RSS format: en-us (default: 'en-en').
204 * - ATOM format: fr (default: 'en').
205 *
206 * @param string $feedType Type of feed (RSS/ATOM).
207 *
208 * @return string The language.
209 */
210 protected function getTypeLanguage(string $feedType)
211 {
212 // Use the locale do define the language, if available.
213 if (!empty($this->locale) && preg_match('/^\w{2}[_\-]\w{2}/', $this->locale)) {
214 $length = ($feedType === self::$FEED_RSS) ? 5 : 2;
215 return str_replace('_', '-', substr($this->locale, 0, $length));
216 }
217 return ($feedType === self::$FEED_RSS) ? 'en-en' : 'en';
218 }
219
220 /**
221 * Format the latest item date found according to the feed type.
222 *
223 * Return an empty string if invalid DateTime is passed.
224 *
225 * @param string $feedType Type of feed (RSS/ATOM).
226 *
227 * @return string Formatted date.
228 */
229 protected function getLatestDateFormatted(string $feedType)
230 {
231 if (empty($this->latestDate) || !$this->latestDate instanceof DateTime) {
232 return '';
233 }
234
235 $type = ($feedType == self::$FEED_RSS) ? DateTime::RSS : DateTime::ATOM;
236 return $this->latestDate->format($type);
237 }
238
239 /**
240 * Get ISO date from DateTime according to feed type.
241 *
242 * @param string $feedType Type of feed (RSS/ATOM).
243 * @param DateTime $date Date to format.
244 * @param string|bool $format Force format.
245 *
246 * @return string Formatted date.
247 */
248 protected function getIsoDate(string $feedType, DateTime $date, $format = false)
249 {
250 if ($format !== false) {
251 return $date->format($format);
252 }
253 if ($feedType == self::$FEED_RSS) {
254 return $date->format(DateTime::RSS);
255 }
256 return $date->format(DateTime::ATOM);
257 }
258
259 /**
260 * Returns the number of link to display according to 'nb' user input parameter.
261 *
262 * If 'nb' not set or invalid, default value: $DEFAULT_NB_LINKS.
263 * If 'nb' is set to 'all', display all filtered bookmarks (max parameter).
264 *
265 * @param array $userInput $_GET.
266 *
267 * @return int number of bookmarks to display.
268 */
269 protected function getLimit(?array $userInput)
270 {
271 if (empty($userInput['nb'])) {
272 return self::$DEFAULT_NB_LINKS;
273 }
274
275 if ($userInput['nb'] == 'all') {
276 return null;
277 }
278
279 $intNb = intval($userInput['nb']);
280 if (!is_int($intNb) || $intNb == 0) {
281 return self::$DEFAULT_NB_LINKS;
282 }
283
284 return $intNb;
285 }
286 }