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