aboutsummaryrefslogtreecommitdiffhomepage
path: root/application
diff options
context:
space:
mode:
Diffstat (limited to 'application')
-rw-r--r--application/FeedBuilder.php279
-rw-r--r--application/HttpUtils.php62
-rw-r--r--application/LinkDB.php99
-rw-r--r--application/LinkFilter.php16
-rw-r--r--application/LinkUtils.php22
-rw-r--r--application/NetscapeBookmarkUtils.php54
-rw-r--r--application/PageBuilder.php145
-rw-r--r--application/Router.php40
-rw-r--r--application/TimeZone.php4
-rw-r--r--application/Updater.php2
-rw-r--r--application/Url.php74
-rw-r--r--application/Utils.php32
12 files changed, 776 insertions, 53 deletions
diff --git a/application/FeedBuilder.php b/application/FeedBuilder.php
new file mode 100644
index 00000000..ddefe6ce
--- /dev/null
+++ b/application/FeedBuilder.php
@@ -0,0 +1,279 @@
1<?php
2
3/**
4 * FeedBuilder class.
5 *
6 * Used to build ATOM and RSS feeds data.
7 */
8class FeedBuilder
9{
10 /**
11 * @var string Constant: RSS feed type.
12 */
13 public static $FEED_RSS = 'rss';
14
15 /**
16 * @var string Constant: ATOM feed type.
17 */
18 public static $FEED_ATOM = 'atom';
19
20 /**
21 * @var string Default language if the locale isn't set.
22 */
23 public static $DEFAULT_LANGUAGE = 'en-en';
24
25 /**
26 * @var int Number of links to display in a feed by default.
27 */
28 public static $DEFAULT_NB_LINKS = 50;
29
30 /**
31 * @var LinkDB instance.
32 */
33 protected $linkDB;
34
35 /**
36 * @var string RSS or ATOM feed.
37 */
38 protected $feedType;
39
40 /**
41 * @var array $_SERVER.
42 */
43 protected $serverInfo;
44
45 /**
46 * @var array $_GET.
47 */
48 protected $userInput;
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 links 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 PubSub hub URL.
67 */
68 protected $pubsubhubUrl;
69
70 /**
71 * @var string server locale.
72 */
73 protected $locale;
74
75 /**
76 * @var DateTime Latest item date.
77 */
78 protected $latestDate;
79
80 /**
81 * Feed constructor.
82 *
83 * @param LinkDB $linkDB LinkDB instance.
84 * @param string $feedType Type of feed.
85 * @param array $serverInfo $_SERVER.
86 * @param array $userInput $_GET.
87 * @param boolean $isLoggedIn True if the user is currently logged in, 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 // Optionally filter the results:
106 $linksToDisplay = $this->linkDB->filterSearch($this->userInput);
107
108 $nblinksToDisplay = $this->getNbLinks(count($linksToDisplay));
109
110 // Can't use array_keys() because $link is a LinkDB instance and not a real array.
111 $keys = array();
112 foreach ($linksToDisplay as $key => $value) {
113 $keys[] = $key;
114 }
115
116 $pageaddr = escape(index_url($this->serverInfo));
117 $linkDisplayed = array();
118 for ($i = 0; $i < $nblinksToDisplay && $i < count($keys); $i++) {
119 $linkDisplayed[$keys[$i]] = $this->buildItem($linksToDisplay[$keys[$i]], $pageaddr);
120 }
121
122 $data['language'] = $this->getTypeLanguage();
123 $data['pubsubhub_url'] = $this->pubsubhubUrl;
124 $data['last_update'] = $this->getLatestDateFormatted();
125 $data['show_dates'] = !$this->hideDates || $this->isLoggedIn;
126 // Remove leading slash from REQUEST_URI.
127 $data['self_link'] = $pageaddr . escape(ltrim($this->serverInfo['REQUEST_URI'], '/'));
128 $data['index_url'] = $pageaddr;
129 $data['usepermalinks'] = $this->usePermalinks === true;
130 $data['links'] = $linkDisplayed;
131
132 return $data;
133 }
134
135 /**
136 * Build a feed item (one per shaare).
137 *
138 * @param array $link Single link array extracted from LinkDB.
139 * @param string $pageaddr Index URL.
140 *
141 * @return array Link array with feed attributes.
142 */
143 protected function buildItem($link, $pageaddr)
144 {
145 $link['guid'] = $pageaddr .'?'. smallHash($link['linkdate']);
146 // Check for both signs of a note: starting with ? and 7 chars long.
147 if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
148 $link['url'] = $pageaddr . $link['url'];
149 }
150 if ($this->usePermalinks === true) {
151 $permalink = '<a href="'. $link['url'] .'" title="Direct link">Direct link</a>';
152 } else {
153 $permalink = '<a href="'. $link['guid'] .'" title="Permalink">Permalink</a>';
154 }
155 $link['description'] = format_description($link['description']) . PHP_EOL .'<br>&#8212; '. $permalink;
156
157 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
158
159 if ($this->feedType == self::$FEED_RSS) {
160 $link['iso_date'] = $date->format(DateTime::RSS);
161 } else {
162 $link['iso_date'] = $date->format(DateTime::ATOM);
163 }
164
165 // Save the more recent item.
166 if (empty($this->latestDate) || $this->latestDate < $date) {
167 $this->latestDate = $date;
168 }
169
170 $taglist = array_filter(explode(' ', $link['tags']), 'strlen');
171 uasort($taglist, 'strcasecmp');
172 $link['taglist'] = $taglist;
173
174 return $link;
175 }
176
177 /**
178 * Assign PubSub hub URL.
179 *
180 * @param string $pubsubhubUrl PubSub hub url.
181 */
182 public function setPubsubhubUrl($pubsubhubUrl)
183 {
184 $this->pubsubhubUrl = $pubsubhubUrl;
185 }
186
187 /**
188 * Set this to true to use permalinks instead of direct links.
189 *
190 * @param boolean $usePermalinks true to force permalinks.
191 */
192 public function setUsePermalinks($usePermalinks)
193 {
194 $this->usePermalinks = $usePermalinks;
195 }
196
197 /**
198 * Set this to true to hide timestamps in feeds.
199 *
200 * @param boolean $hideDates true to enable.
201 */
202 public function setHideDates($hideDates)
203 {
204 $this->hideDates = $hideDates;
205 }
206
207 /**
208 * Set the locale. Used to show feed language.
209 *
210 * @param string $locale The locale (eg. 'fr_FR.UTF8').
211 */
212 public function setLocale($locale)
213 {
214 $this->locale = strtolower($locale);
215 }
216
217 /**
218 * Get the language according to the feed type, based on the locale:
219 *
220 * - RSS format: en-us (default: 'en-en').
221 * - ATOM format: fr (default: 'en').
222 *
223 * @return string The language.
224 */
225 public function getTypeLanguage()
226 {
227 // Use the locale do define the language, if available.
228 if (! empty($this->locale) && preg_match('/^\w{2}[_\-]\w{2}/', $this->locale)) {
229 $length = ($this->feedType == self::$FEED_RSS) ? 5 : 2;
230 return str_replace('_', '-', substr($this->locale, 0, $length));
231 }
232 return ($this->feedType == self::$FEED_RSS) ? 'en-en' : 'en';
233 }
234
235 /**
236 * Format the latest item date found according to the feed type.
237 *
238 * Return an empty string if invalid DateTime is passed.
239 *
240 * @return string Formatted date.
241 */
242 protected function getLatestDateFormatted()
243 {
244 if (empty($this->latestDate) || !$this->latestDate instanceof DateTime) {
245 return '';
246 }
247
248 $type = ($this->feedType == self::$FEED_RSS) ? DateTime::RSS : DateTime::ATOM;
249 return $this->latestDate->format($type);
250 }
251
252 /**
253 * Returns the number of link to display according to 'nb' user input parameter.
254 *
255 * If 'nb' not set or invalid, default value: $DEFAULT_NB_LINKS.
256 * If 'nb' is set to 'all', display all filtered links (max parameter).
257 *
258 * @param int $max maximum number of links to display.
259 *
260 * @return int number of links to display.
261 */
262 public function getNbLinks($max)
263 {
264 if (empty($this->userInput['nb'])) {
265 return self::$DEFAULT_NB_LINKS;
266 }
267
268 if ($this->userInput['nb'] == 'all') {
269 return $max;
270 }
271
272 $intNb = intval($this->userInput['nb']);
273 if (! is_int($intNb) || $intNb == 0) {
274 return self::$DEFAULT_NB_LINKS;
275 }
276
277 return $intNb;
278 }
279}
diff --git a/application/HttpUtils.php b/application/HttpUtils.php
index af7cb371..2e0792f9 100644
--- a/application/HttpUtils.php
+++ b/application/HttpUtils.php
@@ -27,7 +27,9 @@
27function get_http_response($url, $timeout = 30, $maxBytes = 4194304) 27function get_http_response($url, $timeout = 30, $maxBytes = 4194304)
28{ 28{
29 $urlObj = new Url($url); 29 $urlObj = new Url($url);
30 if (! filter_var($url, FILTER_VALIDATE_URL) || ! $urlObj->isHttp()) { 30 $cleanUrl = $urlObj->idnToAscii();
31
32 if (! filter_var($cleanUrl, FILTER_VALIDATE_URL) || ! $urlObj->isHttp()) {
31 return array(array(0 => 'Invalid HTTP Url'), false); 33 return array(array(0 => 'Invalid HTTP Url'), false);
32 } 34 }
33 35
@@ -35,22 +37,27 @@ function get_http_response($url, $timeout = 30, $maxBytes = 4194304)
35 'http' => array( 37 'http' => array(
36 'method' => 'GET', 38 'method' => 'GET',
37 'timeout' => $timeout, 39 'timeout' => $timeout,
38 'user_agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0)' 40 'user_agent' => 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:45.0)'
39 .' Gecko/20100101 Firefox/23.0', 41 .' Gecko/20100101 Firefox/45.0',
40 'request_fulluri' => true, 42 'accept_language' => substr(setlocale(LC_COLLATE, 0), 0, 2) . ',en-US;q=0.7,en;q=0.3',
41 ) 43 )
42 ); 44 );
43 45
44 $context = stream_context_create($options);
45 stream_context_set_default($options); 46 stream_context_set_default($options);
47 list($headers, $finalUrl) = get_redirected_headers($cleanUrl);
48 if (! $headers || strpos($headers[0], '200 OK') === false) {
49 $options['http']['request_fulluri'] = true;
50 stream_context_set_default($options);
51 list($headers, $finalUrl) = get_redirected_headers($cleanUrl);
52 }
46 53
47 list($headers, $finalUrl) = get_redirected_headers($urlObj->cleanup());
48 if (! $headers || strpos($headers[0], '200 OK') === false) { 54 if (! $headers || strpos($headers[0], '200 OK') === false) {
49 return array($headers, false); 55 return array($headers, false);
50 } 56 }
51 57
52 try { 58 try {
53 // TODO: catch Exception in calling code (thumbnailer) 59 // TODO: catch Exception in calling code (thumbnailer)
60 $context = stream_context_create($options);
54 $content = file_get_contents($finalUrl, false, $context, -1, $maxBytes); 61 $content = file_get_contents($finalUrl, false, $context, -1, $maxBytes);
55 } catch (Exception $exc) { 62 } catch (Exception $exc) {
56 return array(array(0 => 'HTTP Error'), $exc->getMessage()); 63 return array(array(0 => 'HTTP Error'), $exc->getMessage());
@@ -60,16 +67,19 @@ function get_http_response($url, $timeout = 30, $maxBytes = 4194304)
60} 67}
61 68
62/** 69/**
63 * Retrieve HTTP headers, following n redirections (temporary and permanent). 70 * Retrieve HTTP headers, following n redirections (temporary and permanent ones).
64 * 71 *
65 * @param string $url initial URL to reach. 72 * @param string $url initial URL to reach.
66 * @param int $redirectionLimit max redirection follow.. 73 * @param int $redirectionLimit max redirection follow.
67 * 74 *
68 * @return array 75 * @return array HTTP headers, or false if it failed.
69 */ 76 */
70function get_redirected_headers($url, $redirectionLimit = 3) 77function get_redirected_headers($url, $redirectionLimit = 3)
71{ 78{
72 $headers = get_headers($url, 1); 79 $headers = get_headers($url, 1);
80 if (!empty($headers['location']) && empty($headers['Location'])) {
81 $headers['Location'] = $headers['location'];
82 }
73 83
74 // Headers found, redirection found, and limit not reached. 84 // Headers found, redirection found, and limit not reached.
75 if ($redirectionLimit-- > 0 85 if ($redirectionLimit-- > 0
@@ -79,6 +89,7 @@ function get_redirected_headers($url, $redirectionLimit = 3)
79 89
80 $redirection = is_array($headers['Location']) ? end($headers['Location']) : $headers['Location']; 90 $redirection = is_array($headers['Location']) ? end($headers['Location']) : $headers['Location'];
81 if ($redirection != $url) { 91 if ($redirection != $url) {
92 $redirection = getAbsoluteUrl($url, $redirection);
82 return get_redirected_headers($redirection, $redirectionLimit); 93 return get_redirected_headers($redirection, $redirectionLimit);
83 } 94 }
84 } 95 }
@@ -87,6 +98,35 @@ function get_redirected_headers($url, $redirectionLimit = 3)
87} 98}
88 99
89/** 100/**
101 * Get an absolute URL from a complete one, and another absolute/relative URL.
102 *
103 * @param string $originalUrl The original complete URL.
104 * @param string $newUrl The new one, absolute or relative.
105 *
106 * @return string Final URL:
107 * - $newUrl if it was already an absolute URL.
108 * - if it was relative, absolute URL from $originalUrl path.
109 */
110function getAbsoluteUrl($originalUrl, $newUrl)
111{
112 $newScheme = parse_url($newUrl, PHP_URL_SCHEME);
113 // Already an absolute URL.
114 if (!empty($newScheme)) {
115 return $newUrl;
116 }
117
118 $parts = parse_url($originalUrl);
119 $final = $parts['scheme'] .'://'. $parts['host'];
120 $final .= (!empty($parts['port'])) ? $parts['port'] : '';
121 $final .= '/';
122 if ($newUrl[0] != '/') {
123 $final .= substr(ltrim($parts['path'], '/'), 0, strrpos($parts['path'], '/'));
124 }
125 $final .= ltrim($newUrl, '/');
126 return $final;
127}
128
129/**
90 * Returns the server's base URL: scheme://domain.tld[:port] 130 * Returns the server's base URL: scheme://domain.tld[:port]
91 * 131 *
92 * @param array $server the $_SERVER array 132 * @param array $server the $_SERVER array
@@ -153,7 +193,7 @@ function server_url($server)
153function index_url($server) 193function index_url($server)
154{ 194{
155 $scriptname = $server['SCRIPT_NAME']; 195 $scriptname = $server['SCRIPT_NAME'];
156 if (endswith($scriptname, 'index.php')) { 196 if (endsWith($scriptname, 'index.php')) {
157 $scriptname = substr($scriptname, 0, -9); 197 $scriptname = substr($scriptname, 0, -9);
158 } 198 }
159 return server_url($server) . $scriptname; 199 return server_url($server) . $scriptname;
diff --git a/application/LinkDB.php b/application/LinkDB.php
index 1b505620..1cb70de0 100644
--- a/application/LinkDB.php
+++ b/application/LinkDB.php
@@ -66,21 +66,39 @@ class LinkDB implements Iterator, Countable, ArrayAccess
66 private $_redirector; 66 private $_redirector;
67 67
68 /** 68 /**
69 * Set this to `true` to urlencode link behind redirector link, `false` to leave it untouched.
70 *
71 * Example:
72 * anonym.to needs clean URL while dereferer.org needs urlencoded URL.
73 *
74 * @var boolean $redirectorEncode parameter: true or false
75 */
76 private $redirectorEncode;
77
78 /**
69 * Creates a new LinkDB 79 * Creates a new LinkDB
70 * 80 *
71 * Checks if the datastore exists; else, attempts to create a dummy one. 81 * Checks if the datastore exists; else, attempts to create a dummy one.
72 * 82 *
73 * @param string $datastore datastore file path. 83 * @param string $datastore datastore file path.
74 * @param boolean $isLoggedIn is the user logged in? 84 * @param boolean $isLoggedIn is the user logged in?
75 * @param boolean $hidePublicLinks if true all links are private. 85 * @param boolean $hidePublicLinks if true all links are private.
76 * @param string $redirector link redirector set in user settings. 86 * @param string $redirector link redirector set in user settings.
87 * @param boolean $redirectorEncode Enable urlencode on redirected urls (default: true).
77 */ 88 */
78 function __construct($datastore, $isLoggedIn, $hidePublicLinks, $redirector = '') 89 function __construct(
90 $datastore,
91 $isLoggedIn,
92 $hidePublicLinks,
93 $redirector = '',
94 $redirectorEncode = true
95 )
79 { 96 {
80 $this->_datastore = $datastore; 97 $this->_datastore = $datastore;
81 $this->_loggedIn = $isLoggedIn; 98 $this->_loggedIn = $isLoggedIn;
82 $this->_hidePublicLinks = $hidePublicLinks; 99 $this->_hidePublicLinks = $hidePublicLinks;
83 $this->_redirector = $redirector; 100 $this->_redirector = $redirector;
101 $this->redirectorEncode = $redirectorEncode === true;
84 $this->_checkDB(); 102 $this->_checkDB();
85 $this->_readDB(); 103 $this->_readDB();
86 } 104 }
@@ -278,7 +296,12 @@ You use the community supported version of the original Shaarli project, by Seba
278 296
279 // Do not use the redirector for internal links (Shaarli note URL starting with a '?'). 297 // Do not use the redirector for internal links (Shaarli note URL starting with a '?').
280 if (!empty($this->_redirector) && !startsWith($link['url'], '?')) { 298 if (!empty($this->_redirector) && !startsWith($link['url'], '?')) {
281 $link['real_url'] = $this->_redirector . urlencode($link['url']); 299 $link['real_url'] = $this->_redirector;
300 if ($this->redirectorEncode) {
301 $link['real_url'] .= urlencode(unescape($link['url']));
302 } else {
303 $link['real_url'] .= $link['url'];
304 }
282 } 305 }
283 else { 306 else {
284 $link['real_url'] = $link['url']; 307 $link['real_url'] = $link['url'];
@@ -341,17 +364,71 @@ You use the community supported version of the original Shaarli project, by Seba
341 } 364 }
342 365
343 /** 366 /**
344 * Filter links. 367 * Returns the shaare corresponding to a smallHash.
368 *
369 * @param string $request QUERY_STRING server parameter.
345 * 370 *
346 * @param string $type Type of filter. 371 * @return array $filtered array containing permalink data.
347 * @param mixed $request Search request, string or array. 372 *
373 * @throws LinkNotFoundException if the smallhash is malformed or doesn't match any link.
374 */
375 public function filterHash($request)
376 {
377 $request = substr($request, 0, 6);
378 $linkFilter = new LinkFilter($this->_links);
379 return $linkFilter->filter(LinkFilter::$FILTER_HASH, $request);
380 }
381
382 /**
383 * Returns the list of articles for a given day.
384 *
385 * @param string $request day to filter. Format: YYYYMMDD.
386 *
387 * @return array list of shaare found.
388 */
389 public function filterDay($request) {
390 $linkFilter = new LinkFilter($this->_links);
391 return $linkFilter->filter(LinkFilter::$FILTER_DAY, $request);
392 }
393
394 /**
395 * Filter links according to search parameters.
396 *
397 * @param array $filterRequest Search request content. Supported keys:
398 * - searchtags: list of tags
399 * - searchterm: term search
348 * @param bool $casesensitive Optional: Perform case sensitive filter 400 * @param bool $casesensitive Optional: Perform case sensitive filter
349 * @param bool $privateonly Optional: Returns private links only if true. 401 * @param bool $privateonly Optional: Returns private links only if true.
350 * 402 *
351 * @return array filtered links 403 * @return array filtered links, all links if no suitable filter was provided.
352 */ 404 */
353 public function filter($type = '', $request = '', $casesensitive = false, $privateonly = false) 405 public function filterSearch($filterRequest = array(), $casesensitive = false, $privateonly = false)
354 { 406 {
407 // Filter link database according to parameters.
408 $searchtags = !empty($filterRequest['searchtags']) ? escape($filterRequest['searchtags']) : '';
409 $searchterm = !empty($filterRequest['searchterm']) ? escape($filterRequest['searchterm']) : '';
410
411 // Search tags + fullsearch.
412 if (empty($type) && ! empty($searchtags) && ! empty($searchterm)) {
413 $type = LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT;
414 $request = array($searchtags, $searchterm);
415 }
416 // Search by tags.
417 elseif (! empty($searchtags)) {
418 $type = LinkFilter::$FILTER_TAG;
419 $request = $searchtags;
420 }
421 // Fulltext search.
422 elseif (! empty($searchterm)) {
423 $type = LinkFilter::$FILTER_TEXT;
424 $request = $searchterm;
425 }
426 // Otherwise, display without filtering.
427 else {
428 $type = '';
429 $request = '';
430 }
431
355 $linkFilter = new LinkFilter($this->_links); 432 $linkFilter = new LinkFilter($this->_links);
356 return $linkFilter->filter($type, $request, $casesensitive, $privateonly); 433 return $linkFilter->filter($type, $request, $casesensitive, $privateonly);
357 } 434 }
diff --git a/application/LinkFilter.php b/application/LinkFilter.php
index 3fd803cb..e693b284 100644
--- a/application/LinkFilter.php
+++ b/application/LinkFilter.php
@@ -44,7 +44,7 @@ class LinkFilter
44 * Filter links according to parameters. 44 * Filter links according to parameters.
45 * 45 *
46 * @param string $type Type of filter (eg. tags, permalink, etc.). 46 * @param string $type Type of filter (eg. tags, permalink, etc.).
47 * @param string $request Filter content. 47 * @param mixed $request Filter content.
48 * @param bool $casesensitive Optional: Perform case sensitive filter if true. 48 * @param bool $casesensitive Optional: Perform case sensitive filter if true.
49 * @param bool $privateonly Optional: Only returns private links if true. 49 * @param bool $privateonly Optional: Only returns private links if true.
50 * 50 *
@@ -110,6 +110,8 @@ class LinkFilter
110 * @param string $smallHash permalink hash. 110 * @param string $smallHash permalink hash.
111 * 111 *
112 * @return array $filtered array containing permalink data. 112 * @return array $filtered array containing permalink data.
113 *
114 * @throws LinkNotFoundException if the smallhash doesn't match any link.
113 */ 115 */
114 private function filterSmallHash($smallHash) 116 private function filterSmallHash($smallHash)
115 { 117 {
@@ -121,6 +123,11 @@ class LinkFilter
121 return $filtered; 123 return $filtered;
122 } 124 }
123 } 125 }
126
127 if (empty($filtered)) {
128 throw new LinkNotFoundException();
129 }
130
124 return $filtered; 131 return $filtered;
125 } 132 }
126 133
@@ -315,6 +322,11 @@ class LinkFilter
315 $tagsOut = $casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8'); 322 $tagsOut = $casesensitive ? $tags : mb_convert_case($tags, MB_CASE_LOWER, 'UTF-8');
316 $tagsOut = str_replace(',', ' ', $tagsOut); 323 $tagsOut = str_replace(',', ' ', $tagsOut);
317 324
318 return array_filter(explode(' ', trim($tagsOut)), 'strlen'); 325 return array_values(array_filter(explode(' ', trim($tagsOut)), 'strlen'));
319 } 326 }
320} 327}
328
329class LinkNotFoundException extends Exception
330{
331 protected $message = 'The link you are trying to reach does not exist or has been deleted.';
332}
diff --git a/application/LinkUtils.php b/application/LinkUtils.php
index 26dd6b67..da04ca97 100644
--- a/application/LinkUtils.php
+++ b/application/LinkUtils.php
@@ -9,8 +9,8 @@
9 */ 9 */
10function html_extract_title($html) 10function html_extract_title($html)
11{ 11{
12 if (preg_match('!<title>(.*)</title>!is', $html, $matches)) { 12 if (preg_match('!<title.*?>(.*?)</title>!is', $html, $matches)) {
13 return trim(str_replace("\n", ' ', $matches[1])); 13 return trim(str_replace("\n", '', $matches[1]));
14 } 14 }
15 return false; 15 return false;
16} 16}
@@ -70,10 +70,26 @@ function headers_extract_charset($headers)
70function html_extract_charset($html) 70function html_extract_charset($html)
71{ 71{
72 // Get encoding specified in HTML header. 72 // Get encoding specified in HTML header.
73 preg_match('#<meta .*charset="?([^">/]+)"? */?>#Usi', $html, $enc); 73 preg_match('#<meta .*charset=["\']?([^";\'>/]+)["\']? */?>#Usi', $html, $enc);
74 if (!empty($enc[1])) { 74 if (!empty($enc[1])) {
75 return strtolower($enc[1]); 75 return strtolower($enc[1]);
76 } 76 }
77 77
78 return false; 78 return false;
79} 79}
80
81/**
82 * Count private links in given linklist.
83 *
84 * @param array $links Linklist.
85 *
86 * @return int Number of private links.
87 */
88function count_private($links)
89{
90 $cpt = 0;
91 foreach ($links as $link) {
92 $cpt = $link['private'] == true ? $cpt + 1 : $cpt;
93 }
94 return $cpt;
95}
diff --git a/application/NetscapeBookmarkUtils.php b/application/NetscapeBookmarkUtils.php
new file mode 100644
index 00000000..fdbb0ad7
--- /dev/null
+++ b/application/NetscapeBookmarkUtils.php
@@ -0,0 +1,54 @@
1<?php
2
3/**
4 * Utilities to import and export bookmarks using the Netscape format
5 */
6class NetscapeBookmarkUtils
7{
8
9 /**
10 * Filters links and adds Netscape-formatted fields
11 *
12 * Added fields:
13 * - timestamp link addition date, using the Unix epoch format
14 * - taglist comma-separated tag list
15 *
16 * @param LinkDB $linkDb Link datastore
17 * @param string $selection Which links to export: (all|private|public)
18 * @param bool $prependNoteUrl Prepend note permalinks with the server's URL
19 * @param string $indexUrl Absolute URL of the Shaarli index page
20 *
21 * @throws Exception Invalid export selection
22 *
23 * @return array The links to be exported, with additional fields
24 */
25 public static function filterAndFormat($linkDb, $selection, $prependNoteUrl, $indexUrl)
26 {
27 // see tpl/export.html for possible values
28 if (! in_array($selection, array('all', 'public', 'private'))) {
29 throw new Exception('Invalid export selection: "'.$selection.'"');
30 }
31
32 $bookmarkLinks = array();
33
34 foreach ($linkDb as $link) {
35 if ($link['private'] != 0 && $selection == 'public') {
36 continue;
37 }
38 if ($link['private'] == 0 && $selection == 'private') {
39 continue;
40 }
41 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
42 $link['timestamp'] = $date->getTimestamp();
43 $link['taglist'] = str_replace(' ', ',', $link['tags']);
44
45 if (startsWith($link['url'], '?') && $prependNoteUrl) {
46 $link['url'] = $indexUrl . $link['url'];
47 }
48
49 $bookmarkLinks[] = $link;
50 }
51
52 return $bookmarkLinks;
53 }
54}
diff --git a/application/PageBuilder.php b/application/PageBuilder.php
new file mode 100644
index 00000000..82580787
--- /dev/null
+++ b/application/PageBuilder.php
@@ -0,0 +1,145 @@
1<?php
2
3/**
4 * This class is in charge of building the final page.
5 * (This is basically a wrapper around RainTPL which pre-fills some fields.)
6 * $p = new PageBuilder();
7 * $p->assign('myfield','myvalue');
8 * $p->renderPage('mytemplate');
9 */
10class PageBuilder
11{
12 /**
13 * @var RainTPL RainTPL instance.
14 */
15 private $tpl;
16
17 /**
18 * PageBuilder constructor.
19 * $tpl is initialized at false for lazy loading.
20 */
21 function __construct()
22 {
23 $this->tpl = false;
24 }
25
26 /**
27 * Initialize all default tpl tags.
28 */
29 private function initialize()
30 {
31 $this->tpl = new RainTPL();
32
33 try {
34 $version = ApplicationUtils::checkUpdate(
35 shaarli_version,
36 $GLOBALS['config']['UPDATECHECK_FILENAME'],
37 $GLOBALS['config']['UPDATECHECK_INTERVAL'],
38 $GLOBALS['config']['ENABLE_UPDATECHECK'],
39 isLoggedIn(),
40 $GLOBALS['config']['UPDATECHECK_BRANCH']
41 );
42 $this->tpl->assign('newVersion', escape($version));
43 $this->tpl->assign('versionError', '');
44
45 } catch (Exception $exc) {
46 logm($GLOBALS['config']['LOG_FILE'], $_SERVER['REMOTE_ADDR'], $exc->getMessage());
47 $this->tpl->assign('newVersion', '');
48 $this->tpl->assign('versionError', escape($exc->getMessage()));
49 }
50
51 $this->tpl->assign('feedurl', escape(index_url($_SERVER)));
52 $searchcrits = ''; // Search criteria
53 if (!empty($_GET['searchtags'])) {
54 $searchcrits .= '&searchtags=' . urlencode($_GET['searchtags']);
55 }
56 if (!empty($_GET['searchterm'])) {
57 $searchcrits .= '&searchterm=' . urlencode($_GET['searchterm']);
58 }
59 $this->tpl->assign('searchcrits', $searchcrits);
60 $this->tpl->assign('source', index_url($_SERVER));
61 $this->tpl->assign('version', shaarli_version);
62 $this->tpl->assign('scripturl', index_url($_SERVER));
63 $this->tpl->assign('pagetitle', 'Shaarli');
64 $this->tpl->assign('privateonly', !empty($_SESSION['privateonly'])); // Show only private links?
65 if (!empty($GLOBALS['title'])) {
66 $this->tpl->assign('pagetitle', $GLOBALS['title']);
67 }
68 if (!empty($GLOBALS['titleLink'])) {
69 $this->tpl->assign('titleLink', $GLOBALS['titleLink']);
70 }
71 if (!empty($GLOBALS['pagetitle'])) {
72 $this->tpl->assign('pagetitle', $GLOBALS['pagetitle']);
73 }
74 $this->tpl->assign('shaarlititle', empty($GLOBALS['title']) ? 'Shaarli': $GLOBALS['title']);
75 if (!empty($GLOBALS['plugin_errors'])) {
76 $this->tpl->assign('plugin_errors', $GLOBALS['plugin_errors']);
77 }
78 }
79
80 /**
81 * The following assign() method is basically the same as RainTPL (except lazy loading)
82 *
83 * @param string $placeholder Template placeholder.
84 * @param mixed $value Value to assign.
85 */
86 public function assign($placeholder, $value)
87 {
88 // Lazy initialization
89 if ($this->tpl === false) {
90 $this->initialize();
91 }
92 $this->tpl->assign($placeholder, $value);
93 }
94
95 /**
96 * Assign an array of data to the template builder.
97 *
98 * @param array $data Data to assign.
99 *
100 * @return false if invalid data.
101 */
102 public function assignAll($data)
103 {
104 // Lazy initialization
105 if ($this->tpl === false) {
106 $this->initialize();
107 }
108
109 if (empty($data) || !is_array($data)){
110 return false;
111 }
112
113 foreach ($data as $key => $value) {
114 $this->assign($key, $value);
115 }
116 }
117
118 /**
119 * Render a specific page (using a template file).
120 * e.g. $pb->renderPage('picwall');
121 *
122 * @param string $page Template filename (without extension).
123 */
124 public function renderPage($page)
125 {
126 // Lazy initialization
127 if ($this->tpl===false) {
128 $this->initialize();
129 }
130 $this->tpl->draw($page);
131 }
132
133 /**
134 * Render a 404 page (uses the template : tpl/404.tpl)
135 * usage : $PAGE->render404('The link was deleted')
136 *
137 * @param string $message A messate to display what is not found
138 */
139 public function render404($message = 'The page you are trying to reach does not exist or has been deleted.')
140 {
141 header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
142 $this->tpl->assign('error_message', $message);
143 $this->renderPage('404');
144 }
145}
diff --git a/application/Router.php b/application/Router.php
index 6185f08e..2c3934b0 100644
--- a/application/Router.php
+++ b/application/Router.php
@@ -15,6 +15,10 @@ class Router
15 15
16 public static $PAGE_DAILY = 'daily'; 16 public static $PAGE_DAILY = 'daily';
17 17
18 public static $PAGE_FEED_ATOM = 'atom';
19
20 public static $PAGE_FEED_RSS = 'rss';
21
18 public static $PAGE_TOOLS = 'tools'; 22 public static $PAGE_TOOLS = 'tools';
19 23
20 public static $PAGE_CHANGEPASSWORD = 'changepasswd'; 24 public static $PAGE_CHANGEPASSWORD = 'changepasswd';
@@ -49,7 +53,7 @@ class Router
49 * @param array $get $_SERVER['GET']. 53 * @param array $get $_SERVER['GET'].
50 * @param bool $loggedIn true if authenticated user. 54 * @param bool $loggedIn true if authenticated user.
51 * 55 *
52 * @return self::page found. 56 * @return string page found.
53 */ 57 */
54 public static function findPage($query, $get, $loggedIn) 58 public static function findPage($query, $get, $loggedIn)
55 { 59 {
@@ -59,19 +63,19 @@ class Router
59 return self::$PAGE_LINKLIST; 63 return self::$PAGE_LINKLIST;
60 } 64 }
61 65
62 if (startswith($query, 'do='. self::$PAGE_LOGIN) && $loggedIn === false) { 66 if (startsWith($query, 'do='. self::$PAGE_LOGIN) && $loggedIn === false) {
63 return self::$PAGE_LOGIN; 67 return self::$PAGE_LOGIN;
64 } 68 }
65 69
66 if (startswith($query, 'do='. self::$PAGE_PICWALL)) { 70 if (startsWith($query, 'do='. self::$PAGE_PICWALL)) {
67 return self::$PAGE_PICWALL; 71 return self::$PAGE_PICWALL;
68 } 72 }
69 73
70 if (startswith($query, 'do='. self::$PAGE_TAGCLOUD)) { 74 if (startsWith($query, 'do='. self::$PAGE_TAGCLOUD)) {
71 return self::$PAGE_TAGCLOUD; 75 return self::$PAGE_TAGCLOUD;
72 } 76 }
73 77
74 if (startswith($query, 'do='. self::$PAGE_OPENSEARCH)) { 78 if (startsWith($query, 'do='. self::$PAGE_OPENSEARCH)) {
75 return self::$PAGE_OPENSEARCH; 79 return self::$PAGE_OPENSEARCH;
76 } 80 }
77 81
@@ -79,28 +83,36 @@ class Router
79 return self::$PAGE_DAILY; 83 return self::$PAGE_DAILY;
80 } 84 }
81 85
86 if (startsWith($query, 'do='. self::$PAGE_FEED_ATOM)) {
87 return self::$PAGE_FEED_ATOM;
88 }
89
90 if (startsWith($query, 'do='. self::$PAGE_FEED_RSS)) {
91 return self::$PAGE_FEED_RSS;
92 }
93
82 // At this point, only loggedin pages. 94 // At this point, only loggedin pages.
83 if (!$loggedIn) { 95 if (!$loggedIn) {
84 return self::$PAGE_LINKLIST; 96 return self::$PAGE_LINKLIST;
85 } 97 }
86 98
87 if (startswith($query, 'do='. self::$PAGE_TOOLS)) { 99 if (startsWith($query, 'do='. self::$PAGE_TOOLS)) {
88 return self::$PAGE_TOOLS; 100 return self::$PAGE_TOOLS;
89 } 101 }
90 102
91 if (startswith($query, 'do='. self::$PAGE_CHANGEPASSWORD)) { 103 if (startsWith($query, 'do='. self::$PAGE_CHANGEPASSWORD)) {
92 return self::$PAGE_CHANGEPASSWORD; 104 return self::$PAGE_CHANGEPASSWORD;
93 } 105 }
94 106
95 if (startswith($query, 'do='. self::$PAGE_CONFIGURE)) { 107 if (startsWith($query, 'do='. self::$PAGE_CONFIGURE)) {
96 return self::$PAGE_CONFIGURE; 108 return self::$PAGE_CONFIGURE;
97 } 109 }
98 110
99 if (startswith($query, 'do='. self::$PAGE_CHANGETAG)) { 111 if (startsWith($query, 'do='. self::$PAGE_CHANGETAG)) {
100 return self::$PAGE_CHANGETAG; 112 return self::$PAGE_CHANGETAG;
101 } 113 }
102 114
103 if (startswith($query, 'do='. self::$PAGE_ADDLINK)) { 115 if (startsWith($query, 'do='. self::$PAGE_ADDLINK)) {
104 return self::$PAGE_ADDLINK; 116 return self::$PAGE_ADDLINK;
105 } 117 }
106 118
@@ -108,19 +120,19 @@ class Router
108 return self::$PAGE_EDITLINK; 120 return self::$PAGE_EDITLINK;
109 } 121 }
110 122
111 if (startswith($query, 'do='. self::$PAGE_EXPORT)) { 123 if (startsWith($query, 'do='. self::$PAGE_EXPORT)) {
112 return self::$PAGE_EXPORT; 124 return self::$PAGE_EXPORT;
113 } 125 }
114 126
115 if (startswith($query, 'do='. self::$PAGE_IMPORT)) { 127 if (startsWith($query, 'do='. self::$PAGE_IMPORT)) {
116 return self::$PAGE_IMPORT; 128 return self::$PAGE_IMPORT;
117 } 129 }
118 130
119 if (startswith($query, 'do='. self::$PAGE_PLUGINSADMIN)) { 131 if (startsWith($query, 'do='. self::$PAGE_PLUGINSADMIN)) {
120 return self::$PAGE_PLUGINSADMIN; 132 return self::$PAGE_PLUGINSADMIN;
121 } 133 }
122 134
123 if (startswith($query, 'do='. self::$PAGE_SAVE_PLUGINSADMIN)) { 135 if (startsWith($query, 'do='. self::$PAGE_SAVE_PLUGINSADMIN)) {
124 return self::$PAGE_SAVE_PLUGINSADMIN; 136 return self::$PAGE_SAVE_PLUGINSADMIN;
125 } 137 }
126 138
diff --git a/application/TimeZone.php b/application/TimeZone.php
index e363d90a..26f2232d 100644
--- a/application/TimeZone.php
+++ b/application/TimeZone.php
@@ -101,10 +101,6 @@ function generateTimeZoneForm($preselectedTimezone='')
101 */ 101 */
102function isTimeZoneValid($continent, $city) 102function isTimeZoneValid($continent, $city)
103{ 103{
104 if ($continent == 'UTC' && $city == 'UTC') {
105 return true;
106 }
107
108 return in_array( 104 return in_array(
109 $continent.'/'.$city, 105 $continent.'/'.$city,
110 timezone_identifiers_list() 106 timezone_identifiers_list()
diff --git a/application/Updater.php b/application/Updater.php
index 773a1ffa..58c13c07 100644
--- a/application/Updater.php
+++ b/application/Updater.php
@@ -137,7 +137,7 @@ class Updater
137 */ 137 */
138 public function updateMethodRenameDashTags() 138 public function updateMethodRenameDashTags()
139 { 139 {
140 $linklist = $this->linkDB->filter(); 140 $linklist = $this->linkDB->filterSearch();
141 foreach ($linklist as $link) { 141 foreach ($linklist as $link) {
142 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags']); 142 $link['tags'] = preg_replace('/(^| )\-/', '$1', $link['tags']);
143 $link['tags'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags'], true))); 143 $link['tags'] = implode(' ', array_unique(LinkFilter::tagsStrToArray($link['tags'], true)));
diff --git a/application/Url.php b/application/Url.php
index a4ac2e73..77447c8d 100644
--- a/application/Url.php
+++ b/application/Url.php
@@ -62,7 +62,21 @@ function add_trailing_slash($url)
62{ 62{
63 return $url . (!endsWith($url, '/') ? '/' : ''); 63 return $url . (!endsWith($url, '/') ? '/' : '');
64} 64}
65/**
66 * Converts an URL with an IDN host to a ASCII one.
67 *
68 * @param string $url Input URL.
69 *
70 * @return string converted URL.
71 */
72function url_with_idn_to_ascii($url)
73{
74 $parts = parse_url($url);
75 $parts['host'] = idn_to_ascii($parts['host']);
65 76
77 $httpUrl = new \http\Url($parts);
78 return $httpUrl->toString();
79}
66/** 80/**
67 * URL representation and cleanup utilities 81 * URL representation and cleanup utilities
68 * 82 *
@@ -118,7 +132,8 @@ class Url
118 */ 132 */
119 public function __construct($url) 133 public function __construct($url)
120 { 134 {
121 $this->parts = parse_url(trim($url)); 135 $url = self::cleanupUnparsedUrl(trim($url));
136 $this->parts = parse_url($url);
122 137
123 if (!empty($url) && empty($this->parts['scheme'])) { 138 if (!empty($url) && empty($this->parts['scheme'])) {
124 $this->parts['scheme'] = 'http'; 139 $this->parts['scheme'] = 'http';
@@ -126,6 +141,35 @@ class Url
126 } 141 }
127 142
128 /** 143 /**
144 * Clean up URL before it's parsed.
145 * ie. handle urlencode, url prefixes, etc.
146 *
147 * @param string $url URL to clean.
148 *
149 * @return string cleaned URL.
150 */
151 protected static function cleanupUnparsedUrl($url)
152 {
153 return self::removeFirefoxAboutReader($url);
154 }
155
156 /**
157 * Remove Firefox Reader prefix if it's present.
158 *
159 * @param string $input url
160 *
161 * @return string cleaned url
162 */
163 protected static function removeFirefoxAboutReader($input)
164 {
165 $firefoxPrefix = 'about://reader?url=';
166 if (startsWith($input, $firefoxPrefix)) {
167 return urldecode(ltrim($input, $firefoxPrefix));
168 }
169 return $input;
170 }
171
172 /**
129 * Returns a string representation of this URL 173 * Returns a string representation of this URL
130 */ 174 */
131 public function toString() 175 public function toString()
@@ -191,6 +235,22 @@ class Url
191 } 235 }
192 236
193 /** 237 /**
238 * Converts an URL with an International Domain Name host to a ASCII one.
239 * This requires PHP-intl. If it's not available, just returns this->cleanup().
240 *
241 * @return string converted cleaned up URL.
242 */
243 public function idnToAscii()
244 {
245 $out = $this->cleanup();
246 if (! function_exists('idn_to_ascii') || ! isset($this->parts['host'])) {
247 return $out;
248 }
249 $asciiHost = idn_to_ascii($this->parts['host']);
250 return str_replace($this->parts['host'], $asciiHost, $out);
251 }
252
253 /**
194 * Get URL scheme. 254 * Get URL scheme.
195 * 255 *
196 * @return string the URL scheme or false if none is provided. 256 * @return string the URL scheme or false if none is provided.
@@ -203,6 +263,18 @@ class Url
203 } 263 }
204 264
205 /** 265 /**
266 * Get URL host.
267 *
268 * @return string the URL host or false if none is provided.
269 */
270 public function getHost() {
271 if (empty($this->parts['host'])) {
272 return false;
273 }
274 return $this->parts['host'];
275 }
276
277 /**
206 * Test if the Url is an HTTP one. 278 * Test if the Url is an HTTP one.
207 * 279 *
208 * @return true is HTTP, false otherwise. 280 * @return true is HTTP, false otherwise.
diff --git a/application/Utils.php b/application/Utils.php
index 3d819716..da521cce 100644
--- a/application/Utils.php
+++ b/application/Utils.php
@@ -41,8 +41,14 @@ function smallHash($text)
41 41
42/** 42/**
43 * Tells if a string start with a substring 43 * Tells if a string start with a substring
44 *
45 * @param string $haystack Given string.
46 * @param string $needle String to search at the beginning of $haystack.
47 * @param bool $case Case sensitive.
48 *
49 * @return bool True if $haystack starts with $needle.
44 */ 50 */
45function startsWith($haystack, $needle, $case=true) 51function startsWith($haystack, $needle, $case = true)
46{ 52{
47 if ($case) { 53 if ($case) {
48 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0); 54 return (strcmp(substr($haystack, 0, strlen($needle)), $needle) === 0);
@@ -52,8 +58,14 @@ function startsWith($haystack, $needle, $case=true)
52 58
53/** 59/**
54 * Tells if a string ends with a substring 60 * Tells if a string ends with a substring
61 *
62 * @param string $haystack Given string.
63 * @param string $needle String to search at the end of $haystack.
64 * @param bool $case Case sensitive.
65 *
66 * @return bool True if $haystack ends with $needle.
55 */ 67 */
56function endsWith($haystack, $needle, $case=true) 68function endsWith($haystack, $needle, $case = true)
57{ 69{
58 if ($case) { 70 if ($case) {
59 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0); 71 return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)), $needle) === 0);
@@ -63,14 +75,22 @@ function endsWith($haystack, $needle, $case=true)
63 75
64/** 76/**
65 * Htmlspecialchars wrapper 77 * Htmlspecialchars wrapper
78 * Support multidimensional array of strings.
66 * 79 *
67 * @param string $str the string to escape. 80 * @param mixed $input Data to escape: a single string or an array of strings.
68 * 81 *
69 * @return string escaped. 82 * @return string escaped.
70 */ 83 */
71function escape($str) 84function escape($input)
72{ 85{
73 return htmlspecialchars($str, ENT_COMPAT, 'UTF-8', false); 86 if (is_array($input)) {
87 $out = array();
88 foreach($input as $key => $value) {
89 $out[$key] = escape($value);
90 }
91 return $out;
92 }
93 return htmlspecialchars($input, ENT_COMPAT, 'UTF-8', false);
74} 94}
75 95
76/** 96/**
@@ -226,7 +246,7 @@ function space2nbsp($text)
226 * 246 *
227 * @return string formatted description. 247 * @return string formatted description.
228 */ 248 */
229function format_description($description, $redirector) { 249function format_description($description, $redirector = false) {
230 return nl2br(space2nbsp(text2clickable($description, $redirector))); 250 return nl2br(space2nbsp(text2clickable($description, $redirector)));
231} 251}
232 252