]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - application/feed/FeedBuilder.php
Apply PHP Code Beautifier on source code for linter automatic fixes
[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 // Optionally filter the results:
106 $linksToDisplay = $this->linkDB->search($userInput ?? [], null, false, false, true);
107
108 $nblinksToDisplay = $this->getNbLinks(count($linksToDisplay), $userInput);
109
110 // Can't use array_keys() because $link is a LinkDB instance and not a real array.
111 $keys = [];
112 foreach ($linksToDisplay as $key => $value) {
113 $keys[] = $key;
114 }
115
116 $pageaddr = escape(index_url($this->serverInfo));
117 $this->formatter->addContextData('index_url', $pageaddr);
118 $linkDisplayed = [];
119 for ($i = 0; $i < $nblinksToDisplay && $i < count($keys); $i++) {
120 $linkDisplayed[$keys[$i]] = $this->buildItem($feedType, $linksToDisplay[$keys[$i]], $pageaddr);
121 }
122
123 $data['language'] = $this->getTypeLanguage($feedType);
124 $data['last_update'] = $this->getLatestDateFormatted($feedType);
125 $data['show_dates'] = !$this->hideDates || $this->isLoggedIn;
126 // Remove leading path from REQUEST_URI (already contained in $pageaddr).
127 $requestUri = preg_replace('#(.*?/)(feed.*)#', '$2', escape($this->serverInfo['REQUEST_URI']));
128 $data['self_link'] = $pageaddr . $requestUri;
129 $data['index_url'] = $pageaddr;
130 $data['usepermalinks'] = $this->usePermalinks === true;
131 $data['links'] = $linkDisplayed;
132
133 return $data;
134 }
135
136 /**
137 * Set this to true to use permalinks instead of direct bookmarks.
138 *
139 * @param boolean $usePermalinks true to force permalinks.
140 */
141 public function setUsePermalinks($usePermalinks)
142 {
143 $this->usePermalinks = $usePermalinks;
144 }
145
146 /**
147 * Set this to true to hide timestamps in feeds.
148 *
149 * @param boolean $hideDates true to enable.
150 */
151 public function setHideDates($hideDates)
152 {
153 $this->hideDates = $hideDates;
154 }
155
156 /**
157 * Set the locale. Used to show feed language.
158 *
159 * @param string $locale The locale (eg. 'fr_FR.UTF8').
160 */
161 public function setLocale($locale)
162 {
163 $this->locale = strtolower($locale);
164 }
165
166 /**
167 * Build a feed item (one per shaare).
168 *
169 * @param string $feedType Type of feed (RSS/ATOM).
170 * @param Bookmark $link Single link array extracted from LinkDB.
171 * @param string $pageaddr Index URL.
172 *
173 * @return array Link array with feed attributes.
174 */
175 protected function buildItem(string $feedType, $link, $pageaddr)
176 {
177 $data = $this->formatter->format($link);
178 $data['guid'] = rtrim($pageaddr, '/') . '/shaare/' . $data['shorturl'];
179 if ($this->usePermalinks === true) {
180 $permalink = '<a href="' . $data['url'] . '" title="' . t('Direct link') . '">' . t('Direct link') . '</a>';
181 } else {
182 $permalink = '<a href="' . $data['guid'] . '" title="' . t('Permalink') . '">' . t('Permalink') . '</a>';
183 }
184 $data['description'] .= PHP_EOL . PHP_EOL . '<br>&#8212; ' . $permalink;
185
186 $data['pub_iso_date'] = $this->getIsoDate($feedType, $data['created']);
187
188 // atom:entry elements MUST contain exactly one atom:updated element.
189 if (!empty($link->getUpdated())) {
190 $data['up_iso_date'] = $this->getIsoDate($feedType, $data['updated'], DateTime::ATOM);
191 } else {
192 $data['up_iso_date'] = $this->getIsoDate($feedType, $data['created'], DateTime::ATOM);
193 }
194
195 // Save the more recent item.
196 if (empty($this->latestDate) || $this->latestDate < $data['created']) {
197 $this->latestDate = $data['created'];
198 }
199 if (!empty($data['updated']) && $this->latestDate < $data['updated']) {
200 $this->latestDate = $data['updated'];
201 }
202
203 return $data;
204 }
205
206 /**
207 * Get the language according to the feed type, based on the locale:
208 *
209 * - RSS format: en-us (default: 'en-en').
210 * - ATOM format: fr (default: 'en').
211 *
212 * @param string $feedType Type of feed (RSS/ATOM).
213 *
214 * @return string The language.
215 */
216 protected function getTypeLanguage(string $feedType)
217 {
218 // Use the locale do define the language, if available.
219 if (!empty($this->locale) && preg_match('/^\w{2}[_\-]\w{2}/', $this->locale)) {
220 $length = ($feedType === self::$FEED_RSS) ? 5 : 2;
221 return str_replace('_', '-', substr($this->locale, 0, $length));
222 }
223 return ($feedType === self::$FEED_RSS) ? 'en-en' : 'en';
224 }
225
226 /**
227 * Format the latest item date found according to the feed type.
228 *
229 * Return an empty string if invalid DateTime is passed.
230 *
231 * @param string $feedType Type of feed (RSS/ATOM).
232 *
233 * @return string Formatted date.
234 */
235 protected function getLatestDateFormatted(string $feedType)
236 {
237 if (empty($this->latestDate) || !$this->latestDate instanceof DateTime) {
238 return '';
239 }
240
241 $type = ($feedType == self::$FEED_RSS) ? DateTime::RSS : DateTime::ATOM;
242 return $this->latestDate->format($type);
243 }
244
245 /**
246 * Get ISO date from DateTime according to feed type.
247 *
248 * @param string $feedType Type of feed (RSS/ATOM).
249 * @param DateTime $date Date to format.
250 * @param string|bool $format Force format.
251 *
252 * @return string Formatted date.
253 */
254 protected function getIsoDate(string $feedType, DateTime $date, $format = false)
255 {
256 if ($format !== false) {
257 return $date->format($format);
258 }
259 if ($feedType == self::$FEED_RSS) {
260 return $date->format(DateTime::RSS);
261 }
262 return $date->format(DateTime::ATOM);
263 }
264
265 /**
266 * Returns the number of link to display according to 'nb' user input parameter.
267 *
268 * If 'nb' not set or invalid, default value: $DEFAULT_NB_LINKS.
269 * If 'nb' is set to 'all', display all filtered bookmarks (max parameter).
270 *
271 * @param int $max maximum number of bookmarks to display.
272 * @param array $userInput $_GET.
273 *
274 * @return int number of bookmarks to display.
275 */
276 protected function getNbLinks($max, ?array $userInput)
277 {
278 if (empty($userInput['nb'])) {
279 return self::$DEFAULT_NB_LINKS;
280 }
281
282 if ($userInput['nb'] == 'all') {
283 return $max;
284 }
285
286 $intNb = intval($userInput['nb']);
287 if (!is_int($intNb) || $intNb == 0) {
288 return self::$DEFAULT_NB_LINKS;
289 }
290
291 return $intNb;
292 }
293 }