aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--application/FeedBuilder.php295
-rw-r--r--application/Router.php2
-rw-r--r--index.php279
3 files changed, 337 insertions, 239 deletions
diff --git a/application/FeedBuilder.php b/application/FeedBuilder.php
new file mode 100644
index 00000000..50e09831
--- /dev/null
+++ b/application/FeedBuilder.php
@@ -0,0 +1,295 @@
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 $searchtags = !empty($this->userInput['searchtags']) ? escape($this->userInput['searchtags']) : '';
107 $searchterm = !empty($this->userInput['searchterm']) ? escape($this->userInput['searchterm']) : '';
108 if (! empty($searchtags) && ! empty($searchterm)) {
109 $linksToDisplay = $this->linkDB->filter(
110 LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT,
111 array($searchtags, $searchterm)
112 );
113 }
114 elseif ($searchtags) {
115 $linksToDisplay = $this->linkDB->filter(LinkFilter::$FILTER_TAG, $searchtags);
116 }
117 elseif ($searchterm) {
118 $linksToDisplay = $this->linkDB->filter(LinkFilter::$FILTER_TEXT, $searchterm);
119 }
120 else {
121 $linksToDisplay = $this->linkDB;
122 }
123
124 $nblinksToDisplay = $this->getNbLinks(count($linksToDisplay));
125
126 // Can't use array_keys() because $link is a LinkDB instance and not a real array.
127 $keys = array();
128 foreach ($linksToDisplay as $key => $value) {
129 $keys[] = $key;
130 }
131
132 $pageaddr = escape(index_url($this->serverInfo));
133 $linkDisplayed = array();
134 for ($i = 0; $i < $nblinksToDisplay && $i < count($keys); $i++) {
135 $linkDisplayed[$keys[$i]] = $this->buildItem($linksToDisplay[$keys[$i]], $pageaddr);
136 }
137
138 $data['language'] = $this->getTypeLanguage();
139 $data['pubsubhub_url'] = $this->pubsubhubUrl;
140 $data['last_update'] = $this->getLatestDateFormatted();
141 $data['show_dates'] = !$this->hideDates || $this->isLoggedIn;
142 // Remove leading slash from REQUEST_URI.
143 $data['self_link'] = $pageaddr . escape(ltrim($this->serverInfo['REQUEST_URI'], '/'));
144 $data['index_url'] = $pageaddr;
145 $data['usepermalinks'] = $this->usePermalinks === true;
146 $data['links'] = $linkDisplayed;
147
148 return $data;
149 }
150
151 /**
152 * Build a feed item (one per shaare).
153 *
154 * @param array $link Single link array extracted from LinkDB.
155 * @param string $pageaddr Index URL.
156 *
157 * @return array Link array with feed attributes.
158 */
159 protected function buildItem($link, $pageaddr)
160 {
161 $link['guid'] = $pageaddr .'?'. smallHash($link['linkdate']);
162 // Check for both signs of a note: starting with ? and 7 chars long.
163 if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
164 $link['url'] = $pageaddr . $link['url'];
165 }
166 if ($this->usePermalinks === true) {
167 $permalink = '<a href="'. $link['url'] .'" title="Direct link">Direct link</a>';
168 } else {
169 $permalink = '<a href="'. $link['guid'] .'" title="Permalink">Permalink</a>';
170 }
171 $link['description'] = format_description($link['description']) . PHP_EOL .'<br>&#8212; '. $permalink;
172
173 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
174
175 if ($this->feedType == self::$FEED_RSS) {
176 $link['iso_date'] = $date->format(DateTime::RSS);
177 } else {
178 $link['iso_date'] = $date->format(DateTime::ATOM);
179 }
180
181 // Save the more recent item.
182 if (empty($this->latestDate) || $this->latestDate < $date) {
183 $this->latestDate = $date;
184 }
185
186 $taglist = array_filter(explode(' ', $link['tags']), 'strlen');
187 uasort($taglist, 'strcasecmp');
188 $link['taglist'] = $taglist;
189
190 return $link;
191 }
192
193 /**
194 * Assign PubSub hub URL.
195 *
196 * @param string $pubsubhubUrl PubSub hub url.
197 */
198 public function setPubsubhubUrl($pubsubhubUrl)
199 {
200 $this->pubsubhubUrl = $pubsubhubUrl;
201 }
202
203 /**
204 * Set this to true to use permalinks instead of direct links.
205 *
206 * @param boolean $usePermalinks true to force permalinks.
207 */
208 public function setUsePermalinks($usePermalinks)
209 {
210 $this->usePermalinks = $usePermalinks;
211 }
212
213 /**
214 * Set this to true to hide timestamps in feeds.
215 *
216 * @param boolean $hideDates true to enable.
217 */
218 public function setHideDates($hideDates)
219 {
220 $this->hideDates = $hideDates;
221 }
222
223 /**
224 * Set the locale. Used to show feed language.
225 *
226 * @param string $locale The locale (eg. 'fr_FR.UTF8').
227 */
228 public function setLocale($locale)
229 {
230 $this->locale = strtolower($locale);
231 }
232
233 /**
234 * Get the language according to the feed type, based on the locale:
235 *
236 * - RSS format: en-us (default: 'en-en').
237 * - ATOM format: fr (default: 'en').
238 *
239 * @return string The language.
240 */
241 public function getTypeLanguage()
242 {
243 // Use the locale do define the language, if available.
244 if (! empty($this->locale) && preg_match('/^\w{2}[_\-]\w{2}/', $this->locale)) {
245 $length = ($this->feedType == self::$FEED_RSS) ? 5 : 2;
246 return str_replace('_', '-', substr($this->locale, 0, $length));
247 }
248 return ($this->feedType == self::$FEED_RSS) ? 'en-en' : 'en';
249 }
250
251 /**
252 * Format the latest item date found according to the feed type.
253 *
254 * Return an empty string if invalid DateTime is passed.
255 *
256 * @return string Formatted date.
257 */
258 protected function getLatestDateFormatted()
259 {
260 if (empty($this->latestDate) || !$this->latestDate instanceof DateTime) {
261 return '';
262 }
263
264 $type = ($this->feedType == self::$FEED_RSS) ? DateTime::RSS : DateTime::ATOM;
265 return $this->latestDate->format($type);
266 }
267
268 /**
269 * Returns the number of link to display according to 'nb' user input parameter.
270 *
271 * If 'nb' not set or invalid, default value: $DEFAULT_NB_LINKS.
272 * If 'nb' is set to 'all', display all filtered links (max parameter).
273 *
274 * @param int $max maximum number of links to display.
275 *
276 * @return int number of links to display.
277 */
278 public function getNbLinks($max)
279 {
280 if (empty($this->userInput['nb'])) {
281 return self::$DEFAULT_NB_LINKS;
282 }
283
284 if ($this->userInput['nb'] == 'all') {
285 return $max;
286 }
287
288 $intNb = intval($this->userInput['nb']);
289 if (! is_int($intNb) || $intNb == 0) {
290 return self::$DEFAULT_NB_LINKS;
291 }
292
293 return $intNb;
294 }
295}
diff --git a/application/Router.php b/application/Router.php
index d98312b5..a1e594a0 100644
--- a/application/Router.php
+++ b/application/Router.php
@@ -53,7 +53,7 @@ class Router
53 * @param array $get $_SERVER['GET']. 53 * @param array $get $_SERVER['GET'].
54 * @param bool $loggedIn true if authenticated user. 54 * @param bool $loggedIn true if authenticated user.
55 * 55 *
56 * @return self::page found. 56 * @return string page found.
57 */ 57 */
58 public static function findPage($query, $get, $loggedIn) 58 public static function findPage($query, $get, $loggedIn)
59 { 59 {
diff --git a/index.php b/index.php
index 73b83533..6e14ff3f 100644
--- a/index.php
+++ b/index.php
@@ -154,6 +154,7 @@ if (is_file($GLOBALS['config']['CONFIG_FILE'])) {
154require_once 'application/ApplicationUtils.php'; 154require_once 'application/ApplicationUtils.php';
155require_once 'application/Cache.php'; 155require_once 'application/Cache.php';
156require_once 'application/CachedPage.php'; 156require_once 'application/CachedPage.php';
157require_once 'application/FeedBuilder.php';
157require_once 'application/FileUtils.php'; 158require_once 'application/FileUtils.php';
158require_once 'application/HttpUtils.php'; 159require_once 'application/HttpUtils.php';
159require_once 'application/LinkDB.php'; 160require_once 'application/LinkDB.php';
@@ -682,237 +683,6 @@ class pageBuilder
682} 683}
683 684
684// ------------------------------------------------------------------------------------------ 685// ------------------------------------------------------------------------------------------
685// Output the last N links in RSS 2.0 format.
686function showRSS($pageBuilder, $linkDB)
687{
688 header('Content-Type: application/rss+xml; charset=utf-8');
689
690 // $usepermalink : If true, use permalink instead of final link.
691 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=rss&permalinks
692 // Also enabled through a config option
693 $usepermalinks = isset($_GET['permalinks']) || !$GLOBALS['config']['ENABLE_RSS_PERMALINKS'];
694
695 // Cache system
696 $query = $_SERVER['QUERY_STRING'];
697 $cache = new CachedPage(
698 $GLOBALS['config']['PAGECACHE'],
699 page_url($_SERVER),
700 startsWith($query, 'do=rss') && !isLoggedIn()
701 );
702 $cached = $cache->cachedVersion();
703 if (! empty($cached)) {
704 echo $cached;
705 exit;
706 }
707
708 // Optionally filter the results:
709 $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : '';
710 $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : '';
711 if (! empty($searchtags) && ! empty($searchterm)) {
712 $linksToDisplay = $linkDB->filter(
713 LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT,
714 array($searchtags, $searchterm)
715 );
716 }
717 elseif ($searchtags) {
718 $linksToDisplay = $linkDB->filter(LinkFilter::$FILTER_TAG, $searchtags);
719 }
720 elseif ($searchterm) {
721 $linksToDisplay = $linkDB->filter(LinkFilter::$FILTER_TEXT, $searchterm);
722 }
723 else {
724 $linksToDisplay = $linkDB;
725 }
726
727 $nblinksToDisplay = 50; // Number of links to display.
728 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
729 if (!empty($_GET['nb'])) {
730 $nblinksToDisplay = $_GET['nb'] == 'all' ? count($linksToDisplay) : max(intval($_GET['nb']), 1);
731 }
732
733 $keys = array();
734 foreach ($linksToDisplay as $key=>$value) {
735 $keys[] = $key; // No, I can't use array_keys().
736 }
737
738 $pageaddr = escape(index_url($_SERVER));
739 $latestDate = '';
740 $i = 0;
741 $linkDisp = array();
742 while ($i < $nblinksToDisplay && $i < count($keys))
743 {
744 $link = $linksToDisplay[$keys[$i]];
745 $link['guid'] = $pageaddr. '?' .smallHash($link['linkdate']);
746 // Check for both signs of a note: starting with ? and 7 chars long.
747 if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
748 $link['url'] = $pageaddr . $link['url'];
749 }
750 if ($usepermalinks) {
751 $permalink = '<a href="'. $link['url'] .'" title="Direct link">Direct link</a>';
752 } else {
753 $permalink = '<a href="'. $link['guid'] .'" title="Permalink">Permalink</a>';
754 }
755 $link['description'] = format_description($link['description']) . PHP_EOL .'<br>&#8212; '. $permalink;
756
757 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
758 $link['iso_date'] = $date->format(DateTime::RSS);
759 $latestDate = max($latestDate, $link['iso_date']);
760 $taglist = array_filter(explode(' ', $link['tags']), 'strlen');
761 uasort($taglist, 'strcasecmp');
762 $link['taglist'] = $taglist;
763
764 $linkDisp[$keys[$i]] = $link;
765 $i++;
766 }
767
768 $data = array();
769 if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) {
770 $data['pubsubhub_url'] = escape($GLOBALS['config']['PUBSUBHUB_URL']);
771 }
772
773 // Use the locale do define the language, if available.
774 $locale = strtolower(setlocale(LC_COLLATE, 0));
775 if (! empty($locale) && preg_match('/^\w{2}[_\-]\w{2}/', $locale)) {
776 $data['language'] = str_replace('_', '-', substr($locale, 0, 5));
777 } else {
778 $data['language'] = 'en-en';
779 }
780 $data['last_update'] = escape($latestDate);
781 $data['show_dates'] = !$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn();
782 // Remove starting slash from REQUEST_URI.
783 $data['self_link'] = escape($pageaddr . substr($_SERVER['REQUEST_URI'], 1));
784 $data['index_url'] = escape($pageaddr);
785 $data['usepermalinks'] = $usepermalinks;
786 $data['links'] = $linkDisp;
787
788 $pluginManager = PluginManager::getInstance();
789 $pluginManager->executeHooks('render_feed', $data, array(
790 'loggedin' => isLoggedIn(),
791 'target' => Router::$PAGE_RSS,
792 ));
793
794 $pageBuilder->assignAll($data);
795 $pageBuilder->renderPage('feed.rss', false);
796 $cache->cache(ob_get_contents());
797 ob_end_flush();
798 exit;
799}
800
801// ------------------------------------------------------------------------------------------
802// Output the last N links in ATOM format.
803function showATOM($pageBuilder, $linkDB)
804{
805 header('Content-Type: application/atom+xml; charset=utf-8');
806
807 // Cache system
808 $query = $_SERVER["QUERY_STRING"];
809 $cache = new CachedPage(
810 $GLOBALS['config']['PAGECACHE'],
811 page_url($_SERVER),
812 startsWith($query,'do=atom') && !isLoggedIn()
813 );
814 $cached = $cache->cachedVersion();
815 if (!empty($cached)) {
816 echo $cached;
817 exit;
818 }
819
820 // $usepermalink : If true, use permalink instead of final link.
821 // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=atom&permalinks
822 $usepermalinks = isset($_GET['permalinks']) || !$GLOBALS['config']['ENABLE_RSS_PERMALINKS'];
823
824 // Optionally filter the results:
825 $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : '';
826 $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : '';
827 if (! empty($searchtags) && ! empty($searchterm)) {
828 $linksToDisplay = $linkDB->filter(
829 LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT,
830 array($searchtags, $searchterm)
831 );
832 }
833 elseif ($searchtags) {
834 $linksToDisplay = $linkDB->filter(LinkFilter::$FILTER_TAG, $searchtags);
835 }
836 elseif ($searchterm) {
837 $linksToDisplay = $linkDB->filter(LinkFilter::$FILTER_TEXT, $searchterm);
838 }
839 else {
840 $linksToDisplay = $linkDB;
841 }
842
843 $nblinksToDisplay = 50; // Number of links to display.
844 // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
845 if (!empty($_GET['nb'])) {
846 $nblinksToDisplay = $_GET['nb'] == 'all' ? count($linksToDisplay) : max(intval($_GET['nb']), 1);
847 }
848
849 $keys = array();
850 foreach ($linksToDisplay as $key=>$value) {
851 $keys[] = $key; // No, I can't use array_keys().
852 }
853
854 $pageaddr = escape(index_url($_SERVER));
855 $latestDate = '';
856 $i = 0;
857 $linkDisp = array();
858 while ($i < $nblinksToDisplay && $i < count($keys))
859 {
860 $link = $linksToDisplay[$keys[$i]];
861 $link['guid'] = $pageaddr. '?' .smallHash($link['linkdate']);
862 // Check for both signs of a note: starting with ? and 7 chars long.
863 if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
864 $link['url'] = $pageaddr . $link['url'];
865 }
866 if ($usepermalinks) {
867 $permalink = '<a href="'. $link['url'] .'" title="Direct link">Direct link</a>';
868 } else {
869 $permalink = '<a href="'. $link['guid'] .'" title="Permalink">Permalink</a>';
870 }
871 $link['description'] = format_description($link['description']) . PHP_EOL .'<br>&#8212; '. $permalink;
872
873 $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
874 $link['iso_date'] = $date->format(DateTime::ATOM);
875 $latestDate = max($latestDate, $link['iso_date']);
876 $taglist = array_filter(explode(' ', $link['tags']), 'strlen');
877 uasort($taglist, 'strcasecmp');
878 $link['taglist'] = $taglist;
879
880 $linkDisp[$keys[$i]] = $link;
881 $i++;
882 }
883
884 $data = array();
885 if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) {
886 $data['pubsubhub_url'] = escape($GLOBALS['config']['PUBSUBHUB_URL']);
887 }
888 // Use the locale do define the language, if available.
889 $locale = strtolower(setlocale(LC_COLLATE, 0));
890 if (! empty($locale) && preg_match('/^\w{2}[_\-]\w{2}/', $locale)) {
891 $data['language'] = substr($locale, 0, 2);
892 } else {
893 $data['language'] = 'en';
894 }
895 $data['last_update'] = escape($latestDate);
896 $data['show_dates'] = !$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn();
897 $data['self_link'] = escape($pageaddr . $_SERVER['REQUEST_URI']);
898 $data['index_url'] = escape($pageaddr);
899 $data['usepermalinks'] = $usepermalinks;
900 $data['links'] = $linkDisp;
901
902 $pluginManager = PluginManager::getInstance();
903 $pluginManager->executeHooks('render_feed', $data, array(
904 'loggedin' => isLoggedIn(),
905 'target' => Router::$PAGE_ATOM,
906 ));
907
908 $pageBuilder->assignAll($data);
909 $pageBuilder->renderPage('feed.atom', false);
910 $cache->cache(ob_get_contents());
911 ob_end_flush();
912 exit;
913}
914
915// ------------------------------------------------------------------------------------------
916// Daily RSS feed: 1 RSS entry per day giving all the links on that day. 686// Daily RSS feed: 1 RSS entry per day giving all the links on that day.
917// Gives the last 7 days (which have links). 687// Gives the last 7 days (which have links).
918// This RSS feed cannot be filtered. 688// This RSS feed cannot be filtered.
@@ -1288,14 +1058,47 @@ function renderPage()
1288 showDaily($PAGE); 1058 showDaily($PAGE);
1289 } 1059 }
1290 1060
1291 // ATOM feed. 1061 // ATOM and RSS feed.
1292 if ($targetPage == Router::$PAGE_ATOM) { 1062 if ($targetPage == Router::$PAGE_FEED_ATOM || $targetPage == Router::$PAGE_FEED_RSS) {
1293 showATOM($PAGE, $LINKSDB); 1063 $feedType = $targetPage == Router::$PAGE_FEED_RSS ? FeedBuilder::$FEED_RSS : FeedBuilder::$FEED_ATOM;
1294 } 1064 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
1295 1065
1296 // RSS feed. 1066 // Cache system
1297 if ($targetPage == Router::$PAGE_RSS) { 1067 $query = $_SERVER['QUERY_STRING'];
1298 showRSS($PAGE, $LINKSDB); 1068 $cache = new CachedPage(
1069 $GLOBALS['config']['PAGECACHE'],
1070 page_url($_SERVER),
1071 startsWith($query,'do='. $targetPage) && !isLoggedIn()
1072 );
1073 $cached = $cache->cachedVersion();
1074 if (!empty($cached)) {
1075 echo $cached;
1076 exit;
1077 }
1078
1079 // Generate data.
1080 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, isLoggedIn());
1081 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0)));
1082 $feedGenerator->setHideDates($GLOBALS['config']['HIDE_TIMESTAMPS'] && !isLoggedIn());
1083 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$GLOBALS['config']['ENABLE_RSS_PERMALINKS']);
1084 if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) {
1085 $feedGenerator->setPubsubhubUrl($GLOBALS['config']['PUBSUBHUB_URL']);
1086 }
1087 $data = $feedGenerator->buildData();
1088
1089 // Process plugin hook.
1090 $pluginManager = PluginManager::getInstance();
1091 $pluginManager->executeHooks('render_feed', $data, array(
1092 'loggedin' => isLoggedIn(),
1093 'target' => $targetPage,
1094 ));
1095
1096 // Render the template.
1097 $PAGE->assignAll($data);
1098 $PAGE->renderPage('feed.'. $feedType);
1099 $cache->cache(ob_get_contents());
1100 ob_end_flush();
1101 exit;
1299 } 1102 }
1300 1103
1301 // Display openseach plugin (XML) 1104 // Display openseach plugin (XML)