-// ------------------------------------------------------------------------------------------
-/* This class is in charge of building the final page.
- (This is basically a wrapper around RainTPL which pre-fills some fields.)
- p = new pageBuilder;
- p.assign('myfield','myvalue');
- p.renderPage('mytemplate');
-
-*/
-class pageBuilder
-{
- private $tpl; // RainTPL template
-
- function __construct()
- {
- $this->tpl = false;
- }
-
- /**
- * Initialize all default tpl tags.
- */
- private function initialize()
- {
- $this->tpl = new RainTPL;
-
- try {
- $version = ApplicationUtils::checkUpdate(
- shaarli_version,
- $GLOBALS['config']['UPDATECHECK_FILENAME'],
- $GLOBALS['config']['UPDATECHECK_INTERVAL'],
- $GLOBALS['config']['ENABLE_UPDATECHECK'],
- isLoggedIn(),
- $GLOBALS['config']['UPDATECHECK_BRANCH']
- );
- $this->tpl->assign('newVersion', escape($version));
- $this->tpl->assign('versionError', '');
-
- } catch (Exception $exc) {
- logm($GLOBALS['config']['LOG_FILE'], $_SERVER['REMOTE_ADDR'], $exc->getMessage());
- $this->tpl->assign('newVersion', '');
- $this->tpl->assign('versionError', escape($exc->getMessage()));
- }
-
- $this->tpl->assign('feedurl', escape(index_url($_SERVER)));
- $searchcrits = ''; // Search criteria
- if (!empty($_GET['searchtags'])) {
- $searchcrits .= '&searchtags=' . urlencode($_GET['searchtags']);
- }
- if (!empty($_GET['searchterm'])) {
- $searchcrits .= '&searchterm=' . urlencode($_GET['searchterm']);
- }
- $this->tpl->assign('searchcrits', $searchcrits);
- $this->tpl->assign('source', index_url($_SERVER));
- $this->tpl->assign('version', shaarli_version);
- $this->tpl->assign('scripturl', index_url($_SERVER));
- $this->tpl->assign('pagetitle', 'Shaarli');
- $this->tpl->assign('privateonly', !empty($_SESSION['privateonly'])); // Show only private links?
- if (!empty($GLOBALS['title'])) {
- $this->tpl->assign('pagetitle', $GLOBALS['title']);
- }
- if (!empty($GLOBALS['titleLink'])) {
- $this->tpl->assign('titleLink', $GLOBALS['titleLink']);
- }
- if (!empty($GLOBALS['pagetitle'])) {
- $this->tpl->assign('pagetitle', $GLOBALS['pagetitle']);
- }
- $this->tpl->assign('shaarlititle', empty($GLOBALS['title']) ? 'Shaarli': $GLOBALS['title']);
- if (!empty($GLOBALS['plugin_errors'])) {
- $this->tpl->assign('plugin_errors', $GLOBALS['plugin_errors']);
- }
- }
-
- // The following assign() method is basically the same as RainTPL (except that it's lazy)
- public function assign($what,$where)
- {
- if ($this->tpl===false) $this->initialize(); // Lazy initialization
- $this->tpl->assign($what,$where);
- }
-
- /**
- * Assign an array of data to the template builder.
- *
- * @param array $data Data to assign.
- *
- * @return false if invalid data.
- */
- public function assignAll($data)
- {
- // Lazy initialization
- if ($this->tpl === false) {
- $this->initialize();
- }
-
- if (empty($data) || !is_array($data)){
- return false;
- }
-
- foreach ($data as $key => $value) {
- $this->assign($key, $value);
- }
- }
-
- // Render a specific page (using a template).
- // e.g. pb.renderPage('picwall')
- public function renderPage($page)
- {
- if ($this->tpl===false) $this->initialize(); // Lazy initialization
- $this->tpl->draw($page);
- }
-
- /**
- * Render a 404 page (uses the template : tpl/404.tpl)
- *
- * usage : $PAGE->render404('The link was deleted')
- * @param string $message A messate to display what is not found
- */
- public function render404($message='The page you are trying to reach does not exist or has been deleted.') {
- header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
- $this->tpl->assign('error_message', $message);
- $this->renderPage('404');
- }
-}
-
-// ------------------------------------------------------------------------------------------
-// Output the last N links in RSS 2.0 format.
-function showRSS()
-{
- header('Content-Type: application/rss+xml; charset=utf-8');
-
- // $usepermalink : If true, use permalink instead of final link.
- // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=rss&permalinks
- // Also enabled through a config option
- $usepermalinks = isset($_GET['permalinks']) || !$GLOBALS['config']['ENABLE_RSS_PERMALINKS'];
-
- // Cache system
- $query = $_SERVER["QUERY_STRING"];
- $cache = new CachedPage(
- $GLOBALS['config']['PAGECACHE'],
- page_url($_SERVER),
- startsWith($query,'do=rss') && !isLoggedIn()
- );
- $cached = $cache->cachedVersion();
- if (! empty($cached)) {
- echo $cached;
- exit;
- }
-
- // If cached was not found (or not usable), then read the database and build the response:
- $LINKSDB = new LinkDB(
- $GLOBALS['config']['DATASTORE'],
- isLoggedIn(),
- $GLOBALS['config']['HIDE_PUBLIC_LINKS'],
- $GLOBALS['redirector']
- );
- // Read links from database (and filter private links if user it not logged in).
-
- // Optionally filter the results:
- $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : '';
- $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : '';
- if (! empty($searchtags) && ! empty($searchterm)) {
- $linksToDisplay = $LINKSDB->filter(
- LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT,
- array($searchtags, $searchterm)
- );
- }
- elseif ($searchtags) {
- $linksToDisplay = $LINKSDB->filter(LinkFilter::$FILTER_TAG, $searchtags);
- }
- elseif ($searchterm) {
- $linksToDisplay = $LINKSDB->filter(LinkFilter::$FILTER_TEXT, $searchterm);
- }
- else {
- $linksToDisplay = $LINKSDB;
- }
-
- $nblinksToDisplay = 50; // Number of links to display.
- // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
- if (!empty($_GET['nb'])) {
- $nblinksToDisplay = $_GET['nb'] == 'all' ? count($linksToDisplay) : max(intval($_GET['nb']), 1);
- }
-
- $pageaddr = escape(index_url($_SERVER));
- echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">';
- echo '<channel><title>'.$GLOBALS['title'].'</title><link>'.$pageaddr.'</link>';
- echo '<description>Shared links</description><language>en-en</language><copyright>'.$pageaddr.'</copyright>'."\n\n";
- if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
- {
- echo '<!-- PubSubHubbub Discovery -->';
- echo '<link rel="hub" href="'.escape($GLOBALS['config']['PUBSUBHUB_URL']).'" xmlns="http://www.w3.org/2005/Atom" />';
- echo '<link rel="self" href="'.$pageaddr.'?do=rss" xmlns="http://www.w3.org/2005/Atom" />';
- echo '<!-- End Of PubSubHubbub Discovery -->';
- }
- $i=0;
- $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys().
- while ($i<$nblinksToDisplay && $i<count($keys))
- {
- $link = $linksToDisplay[$keys[$i]];
- $guid = $pageaddr.'?'.smallHash($link['linkdate']);
- $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
- $absurl = $link['url'];
- if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute
- if ($usepermalinks===true)
- echo '<item><title>'.$link['title'].'</title><guid isPermaLink="true">'.$guid.'</guid><link>'.$guid.'</link>';
- else
- echo '<item><title>'.$link['title'].'</title><guid isPermaLink="false">'.$guid.'</guid><link>'.$absurl.'</link>';
- if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) {
- echo '<pubDate>'.escape($date->format(DateTime::RSS))."</pubDate>\n";
- }
- if ($link['tags']!='') // Adding tags to each RSS entry (as mentioned in RSS specification)
- {
- foreach(explode(' ',$link['tags']) as $tag) { echo '<category domain="'.$pageaddr.'">'.$tag.'</category>'."\n"; }
- }
-
- // Add permalink in description
- $descriptionlink = '(<a href="'.$guid.'">Permalink</a>)';
- // If user wants permalinks first, put the final link in description
- if ($usepermalinks===true) $descriptionlink = '(<a href="'.$absurl.'">Link</a>)';
- if (strlen($link['description'])>0) $descriptionlink = '<br>'.$descriptionlink;
- echo '<description><![CDATA['.
- format_description($link['description'], $GLOBALS['redirector']) .
- $descriptionlink . ']]></description>' . "\n</item>\n";
- $i++;
- }
- echo '</channel></rss><!-- Cached version of '.escape(page_url($_SERVER)).' -->';
-
- $cache->cache(ob_get_contents());
- ob_end_flush();
- exit;
-}
-
-// ------------------------------------------------------------------------------------------
-// Output the last N links in ATOM format.
-function showATOM($pageBuilder, $linkDB)
-{
- header('Content-Type: application/atom+xml; charset=utf-8');
-
- // Cache system
- $query = $_SERVER["QUERY_STRING"];
- $cache = new CachedPage(
- $GLOBALS['config']['PAGECACHE'],
- page_url($_SERVER),
- startsWith($query,'do=atom') && !isLoggedIn()
- );
- $cached = $cache->cachedVersion();
- if (!empty($cached)) {
- echo $cached;
- exit;
- }
-
- // $usepermalink : If true, use permalink instead of final link.
- // User just has to add 'permalink' in URL parameters. e.g. http://mysite.com/shaarli/?do=atom&permalinks
- $usepermalinks = isset($_GET['permalinks']) || !$GLOBALS['config']['ENABLE_RSS_PERMALINKS'];
-
- // Optionally filter the results:
- $searchtags = !empty($_GET['searchtags']) ? escape($_GET['searchtags']) : '';
- $searchterm = !empty($_GET['searchterm']) ? escape($_GET['searchterm']) : '';
- if (! empty($searchtags) && ! empty($searchterm)) {
- $linksToDisplay = $linkDB->filter(
- LinkFilter::$FILTER_TAG | LinkFilter::$FILTER_TEXT,
- array($searchtags, $searchterm)
- );
- }
- elseif ($searchtags) {
- $linksToDisplay = $linkDB->filter(LinkFilter::$FILTER_TAG, $searchtags);
- }
- elseif ($searchterm) {
- $linksToDisplay = $linkDB->filter(LinkFilter::$FILTER_TEXT, $searchterm);
- }
- else {
- $linksToDisplay = $linkDB;
- }
-
- $nblinksToDisplay = 50; // Number of links to display.
- // In URL, you can specificy the number of links. Example: nb=200 or nb=all for all links.
- if (!empty($_GET['nb'])) {
- $nblinksToDisplay = $_GET['nb'] == 'all' ? count($linksToDisplay) : max(intval($_GET['nb']), 1);
- }
-
- $keys = array();
- foreach ($linksToDisplay as $key=>$value) {
- $keys[] = $key; // No, I can't use array_keys().
- }
-
- $pageaddr = escape(index_url($_SERVER));
- $latestDate = '';
- $i = 0;
- $linkDisp = array();
- while ($i < $nblinksToDisplay && $i < count($keys))
- {
- $link = $linksToDisplay[$keys[$i]];
- $link['guid'] = $pageaddr. '?' .smallHash($link['linkdate']);
- // Check for both signs of a note: starting with ? and 7 chars long.
- if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
- $link['url'] = $pageaddr . $link['url'];
- }
- if ($usepermalinks) {
- $permalink = '<a href="'. $link['url'] .'" title="Direct link">Direct link</a>';
- } else {
- $permalink = '<a href="'. $link['guid'] .'" title="Permalink">Permalink</a>';
- }
- $link['description'] = format_description($link['description']) . PHP_EOL .'<br>— '. $permalink;
-
- $date = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $link['linkdate']);
- $link['iso_date'] = $date->format(DateTime::ATOM);
- $latestDate = max($latestDate, $link['iso_date']);
- $taglist = array_filter(explode(' ', $link['tags']), 'strlen');
- uasort($taglist, 'strcasecmp');
- $link['taglist'] = $taglist;
-
- $linkDisp[$keys[$i]] = $link;
- $i++;
- }
-
- $data = array();
- if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) {
- $data['pubsubhub_url'] = escape($GLOBALS['config']['PUBSUBHUB_URL']);
- }
- // Use the locale do define the language, if available.
- $locale = strtolower(setlocale(LC_COLLATE, 0));
- if (! empty($locale) && preg_match('/^\w{2}[_\-]\w{2}/', $locale)) {
- $data['language'] = substr($locale, 0, 2);
- } else {
- $data['language'] = 'en';
- }
- $data['last_update'] = escape($latestDate);
- $data['show_dates'] = !$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn();
- $data['self_link'] = escape($pageaddr . $_SERVER['REQUEST_URI']);
- $data['index_url'] = escape($pageaddr);
- $data['usepermalinks'] = $usepermalinks;
- $data['links'] = $linkDisp;
-
- $pageBuilder->assignAll($data);
- $pageBuilder->renderPage('feed.atom', false);
- $cache->cache(ob_get_contents());
- ob_end_flush();
- exit;
-}
-
-// ------------------------------------------------------------------------------------------
-// Daily RSS feed: 1 RSS entry per day giving all the links on that day.
-// Gives the last 7 days (which have links).
-// This RSS feed cannot be filtered.
-function showDailyRSS() {