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