4 * Shaarli v0.8.7 - Shaare your links...
6 * The personal, minimalist, super-fast, database free, bookmarking service.
8 * Shaarli - The personal, minimalist, super-fast, database free, bookmarking service.
11 * Friendly fork by the Shaarli community:
12 * - https://github.com/shaarli/Shaarli
14 * Original project by sebsauvage.net:
15 * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
16 * - https://github.com/sebsauvage/Shaarli
18 * Licence: http://www.opensource.org/licenses/zlib-license.php
23 // Set 'UTC' as the default timezone if it is not defined in php.ini
24 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
25 if (date_default_timezone_get() == '') {
26 date_default_timezone_set('UTC');
33 // http://server.com/x/shaarli --> /shaarli/
34 define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+
strrpos($_SERVER['REQUEST_URI'], '/', 0)));
36 // High execution time in case of problematic imports/exports.
37 ini_set('max_input_time', '60');
39 // Try to set max upload file size and read
40 ini_set('memory_limit', '128M');
41 ini_set('post_max_size', '16M');
42 ini_set('upload_max_filesize', '16M');
44 // See all error except warnings
45 error_reporting(E_ALL^E_WARNING
);
46 // See all errors (for debugging only)
47 //error_reporting(-1);
50 // 3rd-party libraries
51 if (! file_exists(__DIR__
. '/vendor/autoload.php')) {
52 header('Content-Type: text/plain; charset=utf-8');
53 echo "Error: missing Composer configuration\n\n"
54 ."If you installed Shaarli through Git or using the development branch,\n"
55 ."please refer to the installation documentation to install PHP"
56 ." dependencies using Composer:\n"
57 ."- https://shaarli.readthedocs.io/en/master/Server-configuration/\n"
58 ."- https://shaarli.readthedocs.io/en/master/Download-and-Installation/";
61 require_once 'inc/rain.tpl.class.php';
62 require_once __DIR__
. '/vendor/autoload.php';
65 require_once 'application/bookmark/LinkUtils.php';
66 require_once 'application/config/ConfigPlugin.php';
67 require_once 'application/feed/Cache.php';
68 require_once 'application/http/HttpUtils.php';
69 require_once 'application/http/UrlUtils.php';
70 require_once 'application/updater/UpdaterUtils.php';
71 require_once 'application/FileUtils.php';
72 require_once 'application/TimeZone.php';
73 require_once 'application/Utils.php';
75 use \Shaarli\ApplicationUtils
;
76 use \Shaarli\Bookmark\Exception\LinkNotFoundException
;
77 use \Shaarli\Bookmark\LinkDB
;
78 use \Shaarli\Config\ConfigManager
;
79 use \Shaarli\Feed\CachedPage
;
80 use \Shaarli\Feed\FeedBuilder
;
82 use \Shaarli\Languages
;
83 use \Shaarli\Netscape\NetscapeBookmarkUtils
;
84 use \Shaarli\Plugin\PluginManager
;
85 use \Shaarli\Render\PageBuilder
;
86 use \Shaarli\Render\ThemeUtils
;
88 use \Shaarli\Security\LoginManager
;
89 use \Shaarli\Security\SessionManager
;
90 use \Shaarli\Thumbnailer
;
91 use \Shaarli\Updater\Updater
;
93 // Ensure the PHP version is supported
95 ApplicationUtils
::checkPHPVersion('5.5', PHP_VERSION
);
96 } catch (Exception
$exc) {
97 header('Content-Type: text/plain; charset=utf-8');
98 echo $exc->getMessage();
102 define('SHAARLI_VERSION', ApplicationUtils
::getVersion(__DIR__
.'/'. ApplicationUtils
::$VERSION_FILE));
104 // Force cookie path (but do not change lifetime)
105 $cookie = session_get_cookie_params();
107 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
108 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
110 // Set default cookie expiration and path.
111 session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
112 // Set session parameters on server side.
113 // Use cookies to store session.
114 ini_set('session.use_cookies', 1);
115 // Force cookies for session (phpsessionID forbidden in URL).
116 ini_set('session.use_only_cookies', 1);
117 // Prevent PHP form using sessionID in URL if cookies are disabled.
118 ini_set('session.use_trans_sid', false);
120 session_name('shaarli');
121 // Start session if needed (Some server auto-start sessions).
122 if (session_status() == PHP_SESSION_NONE
) {
126 // Regenerate session ID if invalid or not defined in cookie.
127 if (isset($_COOKIE['shaarli']) && !SessionManager
::checkId($_COOKIE['shaarli'])) {
128 session_regenerate_id(true);
129 $_COOKIE['shaarli'] = session_id();
132 $conf = new ConfigManager();
133 $sessionManager = new SessionManager($_SESSION, $conf);
134 $loginManager = new LoginManager($conf, $sessionManager);
135 $loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
136 $clientIpId = client_ip_id($_SERVER);
138 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
139 if (! defined('LC_MESSAGES')) {
140 define('LC_MESSAGES', LC_COLLATE
);
143 // Sniff browser language and set date format accordingly.
144 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
145 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
148 new Languages(setlocale(LC_MESSAGES
, 0), $conf);
150 $conf->setEmpty('general.timezone', date_default_timezone_get());
151 $conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
152 RainTPL
::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
153 RainTPL
::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
155 $pluginManager = new PluginManager($conf);
156 $pluginManager->load($conf->get('general.enabled_plugins'));
158 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
160 ob_start(); // Output buffering for the page cache.
162 // Prevent caching on client side or proxy: (yes, it's ugly)
163 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
164 header("Cache-Control: no-store, no-cache, must-revalidate");
165 header("Cache-Control: post-check=0, pre-check=0", false);
166 header("Pragma: no-cache");
168 if (! is_file($conf->getConfigFileExt())) {
169 // Ensure Shaarli has proper access to its resources
170 $errors = ApplicationUtils
::checkResourcePermissions($conf);
172 if ($errors != array()) {
173 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
175 foreach ($errors as $error) {
176 $message .= '<li>'.$error.'</li>';
180 header('Content-Type: text/html; charset=utf-8');
185 // Display the installation form if no existing config is found
186 install($conf, $sessionManager, $loginManager);
189 $loginManager->checkLoginState($_COOKIE, $clientIpId);
192 * Adapter function to ensure compatibility with third-party templates
194 * @see https://github.com/shaarli/Shaarli/pull/1086
196 * @return bool true when the user is logged in, false otherwise
198 function isLoggedIn()
200 global $loginManager;
201 return $loginManager->isLoggedIn();
205 // ------------------------------------------------------------------------------------------
206 // Process login form: Check if login/password is correct.
207 if (isset($_POST['login'])) {
208 if (! $loginManager->canLogin($_SERVER)) {
209 die(t('I said: NO. You are banned for the moment. Go away.'));
211 if (isset($_POST['password'])
212 && $sessionManager->checkToken($_POST['token'])
213 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
215 $loginManager->handleSuccessfulLogin($_SERVER);
218 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
219 // Note: Never forget the trailing slash on the cookie path!
220 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
223 if (!empty($_POST['longlastingsession'])) {
224 // Keep the session cookie even after the browser closes
225 $sessionManager->setStaySignedIn(true);
226 $expirationTime = $sessionManager->extendSession();
229 $loginManager::$STAY_SIGNED_IN_COOKIE,
230 $loginManager->getStaySignedInToken(),
235 // Standard session expiration (=when browser closes)
239 // Send cookie with the new expiration date to the browser
240 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
241 session_regenerate_id(true);
243 // Optional redirect after login:
244 if (isset($_GET['post'])) {
245 $uri = '?post='. urlencode($_GET['post']);
246 foreach (array('description', 'source', 'title', 'tags') as $param) {
247 if (!empty($_GET[$param])) {
248 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
251 header('Location: '. $uri);
255 if (isset($_GET['edit_link'])) {
256 header('Location: ?edit_link='. escape($_GET['edit_link']));
260 if (isset($_POST['returnurl'])) {
261 // Prevent loops over login screen.
262 if (strpos($_POST['returnurl'], 'do=login') === false) {
263 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
267 header('Location: ?');
270 $loginManager->handleFailedLogin($_SERVER);
271 $redir = '&username='. urlencode($_POST['login']);
272 if (isset($_GET['post'])) {
273 $redir .= '&post=' . urlencode($_GET['post']);
274 foreach (array('description', 'source', 'title', 'tags') as $param) {
275 if (!empty($_GET[$param])) {
276 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
280 // Redirect to login screen.
281 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
286 // ------------------------------------------------------------------------------------------
287 // Token management for XSRF protection
288 // Token should be used in any form which acts on data (create,update,delete,import...).
289 if (!isset($_SESSION['tokens'])) {
290 $_SESSION['tokens']=array(); // Token are attached to the session.
294 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
295 * Gives the last 7 days (which have links).
296 * This RSS feed cannot be filtered.
298 * @param ConfigManager $conf Configuration Manager instance
299 * @param LoginManager $loginManager LoginManager instance
301 function showDailyRSS($conf, $loginManager)
304 $query = $_SERVER['QUERY_STRING'];
305 $cache = new CachedPage(
306 $conf->get('config.PAGE_CACHE'),
308 startsWith($query, 'do=dailyrss') && !$loginManager->isLoggedIn()
310 $cached = $cache->cachedVersion();
311 if (!empty($cached)) {
316 // If cached was not found (or not usable), then read the database and build the response:
317 // Read links from database (and filter private links if used it not logged in).
318 $LINKSDB = new LinkDB(
319 $conf->get('resource.datastore'),
320 $loginManager->isLoggedIn(),
321 $conf->get('privacy.hide_public_links')
324 /* Some Shaarlies may have very few links, so we need to look
325 back in time until we have enough days ($nb_of_days).
327 $nb_of_days = 7; // We take 7 days.
328 $today = date('Ymd');
331 foreach ($LINKSDB as $link) {
332 $day = $link['created']->format('Ymd'); // Extract day (without time)
333 if (strcmp($day, $today) < 0) {
334 if (empty($days[$day])) {
335 $days[$day] = array();
337 $days[$day][] = $link;
340 if (count($days) > $nb_of_days) {
341 break; // Have we collected enough days?
345 // Build the RSS feed.
346 header('Content-Type: application/rss+xml; charset=utf-8');
347 $pageaddr = escape(index_url($_SERVER));
348 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
350 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
351 echo '<link>'. $pageaddr .'</link>';
352 echo '<description>Daily shared links</description>';
353 echo '<language>en-en</language>';
354 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL
;
357 foreach ($days as $day => $links) {
358 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
359 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
361 // We pre-format some fields for proper output.
362 foreach ($links as &$link) {
363 $link['formatedDescription'] = format_description($link['description']);
364 $link['timestamp'] = $link['created']->getTimestamp();
365 if (is_note($link['url'])) {
366 $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
370 // Then build the HTML for this day:
372 $tpl->assign('title', $conf->get('general.title'));
373 $tpl->assign('daydate', $dayDate->getTimestamp());
374 $tpl->assign('absurl', $absurl);
375 $tpl->assign('links', $links);
376 $tpl->assign('rssdate', escape($dayDate->format(DateTime
::RSS
)));
377 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
378 $tpl->assign('index_url', $pageaddr);
379 $html = $tpl->draw('dailyrss', true);
381 echo $html . PHP_EOL
;
383 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
385 $cache->cache(ob_get_contents());
391 * Show the 'Daily' page.
393 * @param PageBuilder $pageBuilder Template engine wrapper.
394 * @param LinkDB $LINKSDB LinkDB instance.
395 * @param ConfigManager $conf Configuration Manager instance.
396 * @param PluginManager $pluginManager Plugin Manager instance.
397 * @param LoginManager $loginManager Login Manager instance
399 function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
401 if (isset($_GET['day'])) {
403 if ($day === date('Ymd', strtotime('now'))) {
404 $pageBuilder->assign('dayDesc', t('Today'));
405 } elseif ($day === date('Ymd', strtotime('-1 days'))) {
406 $pageBuilder->assign('dayDesc', t('Yesterday'));
409 $day = date('Ymd', strtotime('now')); // Today, in format YYYYMMDD.
410 $pageBuilder->assign('dayDesc', t('Today'));
413 $days = $LINKSDB->days();
414 $i = array_search($day, $days);
415 if ($i === false && count($days)) {
416 // no links for day, but at least one day with links
417 $i = count($days) - 1;
425 $previousday=$days[$i - 1];
427 if ($i < count($days) - 1) {
428 $nextday = $days[$i +
1];
432 $linksToDisplay = $LINKSDB->filterDay($day);
433 } catch (Exception
$exc) {
435 $linksToDisplay = array();
438 // We pre-format some fields for proper output.
439 foreach ($linksToDisplay as $key => $link) {
440 $taglist = explode(' ', $link['tags']);
441 uasort($taglist, 'strcasecmp');
442 $linksToDisplay[$key]['taglist']=$taglist;
443 $linksToDisplay[$key]['formatedDescription'] = format_description($link['description']);
444 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
447 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
449 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
450 'linksToDisplay' => $linksToDisplay,
451 'day' => $dayDate->getTimestamp(),
452 'dayDate' => $dayDate,
453 'previousday' => $previousday,
454 'nextday' => $nextday,
457 /* Hook is called before column construction so that plugins don't have
458 to deal with columns. */
459 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
461 /* We need to spread the articles on 3 columns.
462 I did not want to use a JavaScript lib like http://masonry.desandro.com/
463 so I manually spread entries with a simple method: I roughly evaluate the
464 height of a div according to title and description length.
466 $columns = array(array(), array(), array()); // Entries to display, for each column.
467 $fill = array(0, 0, 0); // Rough estimate of columns fill.
468 foreach ($data['linksToDisplay'] as $key => $link) {
469 // Roughly estimate length of entry (by counting characters)
470 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
471 // Description: 836 characters gives roughly 342 pixel height.
472 // This is not perfect, but it's usually OK.
473 $length = strlen($link['title']) +
(342 * strlen($link['description'])) / 836;
474 if ($link['thumbnail']) {
475 $length +
= 100; // 1 thumbnails roughly takes 100 pixels height.
477 // Then put in column which is the less filled:
478 $smallest = min($fill); // find smallest value in array.
479 $index = array_search($smallest, $fill); // find index of this smallest value.
480 array_push($columns[$index], $link); // Put entry in this column.
481 $fill[$index] +
= $length;
484 $data['cols'] = $columns;
486 foreach ($data as $key => $value) {
487 $pageBuilder->assign($key, $value);
490 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
491 $pageBuilder->renderPage('daily');
496 * Renders the linklist
498 * @param pageBuilder $PAGE pageBuilder instance.
499 * @param LinkDB $LINKSDB LinkDB instance.
500 * @param ConfigManager $conf Configuration Manager instance.
501 * @param PluginManager $pluginManager Plugin Manager instance.
503 function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
505 buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
506 $PAGE->renderPage('linklist');
510 * Render HTML page (according to URL parameters and user rights)
512 * @param ConfigManager $conf Configuration Manager instance.
513 * @param PluginManager $pluginManager Plugin Manager instance,
514 * @param LinkDB $LINKSDB
515 * @param History $history instance
516 * @param SessionManager $sessionManager SessionManager instance
517 * @param LoginManager $loginManager LoginManager instance
519 function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
521 $updater = new Updater(
522 read_updates_file($conf->get('resource.updates')),
525 $loginManager->isLoggedIn(),
529 $newUpdates = $updater->update();
530 if (! empty($newUpdates)) {
532 $conf->get('resource.updates'),
533 $updater->getDoneUpdates()
536 } catch (Exception
$e) {
537 die($e->getMessage());
540 $PAGE = new PageBuilder($conf, $_SESSION, $LINKSDB, $sessionManager->generateToken(), $loginManager->isLoggedIn());
541 $PAGE->assign('linkcount', count($LINKSDB));
542 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
543 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
545 // Determine which page will be rendered.
546 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
547 $targetPage = Router
::findPage($query, $_GET, $loginManager->isLoggedIn());
549 if (// if the user isn't logged in
550 !$loginManager->isLoggedIn() &&
551 // and Shaarli doesn't have public content...
552 $conf->get('privacy.hide_public_links') &&
553 // and is configured to enforce the login
554 $conf->get('privacy.force_login') &&
555 // and the current page isn't already the login page
556 $targetPage !== Router
::$PAGE_LOGIN &&
557 // and the user is not requesting a feed (which would lead to a different content-type as expected)
558 $targetPage !== Router
::$PAGE_FEED_ATOM &&
559 $targetPage !== Router
::$PAGE_FEED_RSS
561 // force current page to be the login page
562 $targetPage = Router
::$PAGE_LOGIN;
565 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
566 // Then assign generated data to RainTPL.
567 $common_hooks = array(
573 foreach ($common_hooks as $name) {
574 $plugin_data = array();
575 $pluginManager->executeHooks(
579 'target' => $targetPage,
580 'loggedin' => $loginManager->isLoggedIn()
583 $PAGE->assign('plugins_' . $name, $plugin_data);
586 // -------- Display login form.
587 if ($targetPage == Router
::$PAGE_LOGIN) {
588 if ($conf->get('security.open_shaarli')) {
589 header('Location: ?');
591 } // No need to login for open Shaarli
592 if (isset($_GET['username'])) {
593 $PAGE->assign('username', escape($_GET['username']));
595 $PAGE->assign('returnurl', (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
596 // add default state of the 'remember me' checkbox
597 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
598 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
599 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
600 $PAGE->renderPage('loginform');
603 // -------- User wants to logout.
604 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) {
605 invalidateCaches($conf->get('resource.page_cache'));
606 $sessionManager->logout();
607 setcookie(LoginManager
::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH
);
608 header('Location: ?');
612 // -------- Picture wall
613 if ($targetPage == Router
::$PAGE_PICWALL) {
614 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
615 if (! $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
) === Thumbnailer
::MODE_NONE
) {
616 $PAGE->assign('linksToDisplay', []);
617 $PAGE->renderPage('picwall');
621 // Optionally filter the results:
622 $links = $LINKSDB->filterSearch($_GET);
623 $linksToDisplay = array();
625 // Get only links which have a thumbnail.
626 // Note: we do not retrieve thumbnails here, the request is too heavy.
627 foreach ($links as $key => $link) {
628 if (isset($link['thumbnail']) && $link['thumbnail'] !== false) {
629 $linksToDisplay[] = $link; // Add to array.
634 'linksToDisplay' => $linksToDisplay,
636 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => $loginManager->isLoggedIn()));
638 foreach ($data as $key => $value) {
639 $PAGE->assign($key, $value);
643 $PAGE->renderPage('picwall');
647 // -------- Tag cloud
648 if ($targetPage == Router
::$PAGE_TAGCLOUD) {
649 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
650 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
651 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
653 // We sort tags alphabetically, then choose a font size according to count.
654 // First, find max value.
656 foreach ($tags as $value) {
657 $maxcount = max($maxcount, $value);
660 alphabetical_sort($tags, false, true);
663 foreach ($tags as $key => $value) {
664 if (in_array($key, $filteringTags)) {
667 // Tag font size scaling:
668 // default 15 and 30 logarithm bases affect scaling,
669 // 22 and 6 are arbitrary font sizes for max and min sizes.
670 $size = log($value, 15) / log($maxcount, 30) * 2.2 +
0.8;
671 $tagList[$key] = array(
673 'size' => number_format($size, 2, '.', ''),
677 $searchTags = implode(' ', escape($filteringTags));
679 'search_tags' => $searchTags,
682 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
684 foreach ($data as $key => $value) {
685 $PAGE->assign($key, $value);
688 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
689 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
690 $PAGE->renderPage('tag.cloud');
695 if ($targetPage == Router
::$PAGE_TAGLIST) {
696 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
697 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
698 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
699 foreach ($filteringTags as $tag) {
700 if (array_key_exists($tag, $tags)) {
705 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
706 alphabetical_sort($tags, false, true);
709 $searchTags = implode(' ', escape($filteringTags));
711 'search_tags' => $searchTags,
714 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
716 foreach ($data as $key => $value) {
717 $PAGE->assign($key, $value);
720 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
721 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
722 $PAGE->renderPage('tag.list');
727 if ($targetPage == Router
::$PAGE_DAILY) {
728 showDaily($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
731 // ATOM and RSS feed.
732 if ($targetPage == Router
::$PAGE_FEED_ATOM || $targetPage == Router
::$PAGE_FEED_RSS) {
733 $feedType = $targetPage == Router
::$PAGE_FEED_RSS ? FeedBuilder
::$FEED_RSS : FeedBuilder
::$FEED_ATOM;
734 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
737 $query = $_SERVER['QUERY_STRING'];
738 $cache = new CachedPage(
739 $conf->get('resource.page_cache'),
741 startsWith($query, 'do='. $targetPage) && !$loginManager->isLoggedIn()
743 $cached = $cache->cachedVersion();
744 if (!empty($cached)) {
750 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, $loginManager->isLoggedIn());
751 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE
, 0)));
752 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
753 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
754 $data = $feedGenerator->buildData();
756 // Process plugin hook.
757 $pluginManager->executeHooks('render_feed', $data, array(
758 'loggedin' => $loginManager->isLoggedIn(),
759 'target' => $targetPage,
762 // Render the template.
763 $PAGE->assignAll($data);
764 $PAGE->renderPage('feed.'. $feedType);
765 $cache->cache(ob_get_contents());
770 // Display opensearch plugin (XML)
771 if ($targetPage == Router
::$PAGE_OPENSEARCH) {
772 header('Content-Type: application/xml; charset=utf-8');
773 $PAGE->assign('serverurl', index_url($_SERVER));
774 $PAGE->renderPage('opensearch');
778 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
779 if (isset($_GET['addtag'])) {
780 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
781 if (empty($_SERVER['HTTP_REFERER'])) {
782 // In case browser does not send HTTP_REFERER
783 header('Location: ?searchtags='.urlencode($_GET['addtag']));
786 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
788 // Prevent redirection loop
789 if (isset($params['addtag'])) {
790 unset($params['addtag']);
793 // Check if this tag is already in the search query and ignore it if it is.
794 // Each tag is always separated by a space
795 if (isset($params['searchtags'])) {
796 $current_tags = explode(' ', $params['searchtags']);
798 $current_tags = array();
801 foreach ($current_tags as $value) {
802 if ($value === $_GET['addtag']) {
807 // Append the tag if necessary
808 if (empty($params['searchtags'])) {
809 $params['searchtags'] = trim($_GET['addtag']);
811 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
814 // We also remove page (keeping the same page has no sense, since the
815 // results are different)
816 unset($params['page']);
818 header('Location: ?'.http_build_query($params));
822 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
823 if (isset($_GET['removetag'])) {
824 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
825 if (empty($_SERVER['HTTP_REFERER'])) {
826 header('Location: ?');
830 // In case browser does not send HTTP_REFERER
831 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
833 // Prevent redirection loop
834 if (isset($params['removetag'])) {
835 unset($params['removetag']);
838 if (isset($params['searchtags'])) {
839 $tags = explode(' ', $params['searchtags']);
840 // Remove value from array $tags.
841 $tags = array_diff($tags, array($_GET['removetag']));
842 $params['searchtags'] = implode(' ', $tags);
844 if (empty($params['searchtags'])) {
845 unset($params['searchtags']);
848 // We also remove page (keeping the same page has no sense, since
849 // the results are different)
850 unset($params['page']);
852 header('Location: ?'.http_build_query($params));
856 // -------- User wants to change the number of links per page (linksperpage=...)
857 if (isset($_GET['linksperpage'])) {
858 if (is_numeric($_GET['linksperpage'])) {
859 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
862 if (! empty($_SERVER['HTTP_REFERER'])) {
863 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
867 header('Location: '. $location);
871 // -------- User wants to see only private links (toggle)
872 if (isset($_GET['visibility'])) {
873 if ($_GET['visibility'] === 'private') {
874 // Visibility not set or not already private, set private, otherwise reset it
875 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
876 // See only private links
877 $_SESSION['visibility'] = 'private';
879 unset($_SESSION['visibility']);
881 } elseif ($_GET['visibility'] === 'public') {
882 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
883 // See only public links
884 $_SESSION['visibility'] = 'public';
886 unset($_SESSION['visibility']);
890 if (! empty($_SERVER['HTTP_REFERER'])) {
891 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
895 header('Location: '. $location);
899 // -------- User wants to see only untagged links (toggle)
900 if (isset($_GET['untaggedonly'])) {
901 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
903 if (! empty($_SERVER['HTTP_REFERER'])) {
904 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
908 header('Location: '. $location);
912 // -------- Handle other actions allowed for non-logged in users:
913 if (!$loginManager->isLoggedIn()) {
914 // User tries to post new link but is not logged in:
915 // Show login screen, then redirect to ?post=...
916 if (isset($_GET['post'])) {
917 header( // Redirect to login page, then back to post link.
918 'Location: ?do=login&post='.urlencode($_GET['post']).
919 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
920 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
921 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
922 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
927 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
928 if (isset($_GET['edit_link'])) {
929 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
933 exit; // Never remove this one! All operations below are reserved for logged in user.
936 // -------- All other functions are reserved for the registered user:
938 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
939 if ($targetPage == Router
::$PAGE_TOOLS) {
941 'pageabsaddr' => index_url($_SERVER),
942 'sslenabled' => is_https($_SERVER),
944 $pluginManager->executeHooks('render_tools', $data);
946 foreach ($data as $key => $value) {
947 $PAGE->assign($key, $value);
950 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
951 $PAGE->renderPage('tools');
955 // -------- User wants to change his/her password.
956 if ($targetPage == Router
::$PAGE_CHANGEPASSWORD) {
957 if ($conf->get('security.open_shaarli')) {
958 die(t('You are not supposed to change a password on an Open Shaarli.'));
961 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) {
962 if (!$sessionManager->checkToken($_POST['token'])) {
963 die(t('Wrong token.')); // Go away!
966 // Make sure old password is correct.
968 $_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt')
970 if ($oldhash != $conf->get('credentials.hash')) {
971 echo '<script>alert("'
972 . t('The old password is not correct.')
973 .'");document.location=\'?do=changepasswd\';</script>';
977 // Salt renders rainbow-tables attacks useless.
978 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
982 $_POST['setpassword']
983 . $conf->get('credentials.login')
984 . $conf->get('credentials.salt')
988 $conf->write($loginManager->isLoggedIn());
989 } catch (Exception
$e) {
991 'ERROR while writing config file after changing password.' . PHP_EOL
.
995 // TODO: do not handle exceptions/errors in JS.
996 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
999 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
1002 // show the change password form.
1003 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
1004 $PAGE->renderPage('changepassword');
1009 // -------- User wants to change configuration
1010 if ($targetPage == Router
::$PAGE_CONFIGURE) {
1011 if (!empty($_POST['title'])) {
1012 if (!$sessionManager->checkToken($_POST['token'])) {
1013 die(t('Wrong token.')); // Go away!
1016 if (!empty($_POST['continent']) && !empty($_POST['city'])
1017 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1019 $tz = $_POST['continent'] . '/' . $_POST['city'];
1021 $conf->set('general.timezone', $tz);
1022 $conf->set('general.title', escape($_POST['title']));
1023 $conf->set('general.header_link', escape($_POST['titleLink']));
1024 $conf->set('general.retrieve_description', !empty($_POST['retrieveDescription']));
1025 $conf->set('resource.theme', escape($_POST['theme']));
1026 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
1027 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
1028 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1029 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1030 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
1031 $conf->set('api.enabled', !empty($_POST['enableApi']));
1032 $conf->set('api.secret', escape($_POST['apiSecret']));
1033 $conf->set('translation.language', escape($_POST['language']));
1035 $thumbnailsMode = extension_loaded('gd') ? $_POST['enableThumbnails'] : Thumbnailer
::MODE_NONE
;
1036 if ($thumbnailsMode !== Thumbnailer
::MODE_NONE
1037 && $thumbnailsMode !== $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
)
1039 $_SESSION['warnings'][] = t(
1040 'You have enabled or changed thumbnails mode. '
1041 .'<a href="?do=thumbs_update">Please synchronize them</a>.'
1044 $conf->set('thumbnails.mode', $thumbnailsMode);
1047 $conf->write($loginManager->isLoggedIn());
1048 $history->updateSettings();
1049 invalidateCaches($conf->get('resource.page_cache'));
1050 } catch (Exception
$e) {
1052 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1056 // TODO: do not handle exceptions/errors in JS.
1057 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1060 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1063 // Show the configuration form.
1064 $PAGE->assign('title', $conf->get('general.title'));
1065 $PAGE->assign('theme', $conf->get('resource.theme'));
1066 $PAGE->assign('theme_available', ThemeUtils
::getThemes($conf->get('resource.raintpl_tpl')));
1067 list($continents, $cities) = generateTimeZoneData(
1068 timezone_identifiers_list(),
1069 $conf->get('general.timezone')
1071 $PAGE->assign('continents', $continents);
1072 $PAGE->assign('cities', $cities);
1073 $PAGE->assign('retrieve_description', $conf->get('general.retrieve_description'));
1074 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
1075 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1076 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1077 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1078 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1079 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1080 $PAGE->assign('api_secret', $conf->get('api.secret'));
1081 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1082 $PAGE->assign('gd_enabled', extension_loaded('gd'));
1083 $PAGE->assign('thumbnails_mode', $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
));
1084 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
1085 $PAGE->renderPage('configure');
1090 // -------- User wants to rename a tag or delete it
1091 if ($targetPage == Router
::$PAGE_CHANGETAG) {
1092 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1093 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1094 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
1095 $PAGE->renderPage('changetag');
1099 if (!$sessionManager->checkToken($_POST['token'])) {
1100 die(t('Wrong token.'));
1103 $toTag = isset($_POST['totag']) ? escape($_POST['totag']) : null;
1104 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), $toTag);
1105 $LINKSDB->save($conf->get('resource.page_cache'));
1106 foreach ($alteredLinks as $link) {
1107 $history->updateLink($link);
1109 $delete = empty($_POST['totag']);
1110 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1111 $count = count($alteredLinks);
1113 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d links.', $count), $count)
1114 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d links.', $count), $count);
1115 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1119 // -------- User wants to add a link without using the bookmarklet: Show form.
1120 if ($targetPage == Router
::$PAGE_ADDLINK) {
1121 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1122 $PAGE->renderPage('addlink');
1126 // -------- User clicked the "Save" button when editing a link: Save link to database.
1127 if (isset($_POST['save_edit'])) {
1129 if (! $sessionManager->checkToken($_POST['token'])) {
1130 die(t('Wrong token.'));
1133 // lf_id should only be present if the link exists.
1134 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
1136 // Linkdate is kept here to:
1137 // - use the same permalink for notes as they're displayed when creating them
1138 // - let users hack creation date of their posts
1139 // See: https://shaarli.readthedocs.io/en/master/guides/various-hacks/#changing-the-timestamp-for-a-shaare
1140 $linkdate = escape($_POST['lf_linkdate']);
1141 $link['created'] = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1142 if (isset($LINKSDB[$id])) {
1144 $link['updated'] = new DateTime();
1145 $link['shorturl'] = $LINKSDB[$id]['shorturl'];
1146 $link['sticky'] = isset($LINKSDB[$id]['sticky']) ? $LINKSDB[$id]['sticky'] : false;
1150 $link['updated'] = null;
1151 $link['shorturl'] = link_small_hash($link['created'], $id);
1152 $link['sticky'] = false;
1156 // Remove multiple spaces.
1157 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
1158 // Remove first '-' char in tags.
1159 $tags = preg_replace('/(^| )\-/', '$1', $tags);
1160 // Remove duplicates.
1161 $tags = implode(' ', array_unique(explode(' ', $tags)));
1163 if (empty(trim($_POST['lf_url
']))) {
1164 $_POST['lf_url
'] = '?' . smallHash($linkdate . $id);
1166 $url = whitelist_protocols(trim($_POST['lf_url
']), $conf->get('security
.allowed_protocols
'));
1168 $link = array_merge($link, [
1169 'title
' => trim($_POST['lf_title
']),
1171 'description
' => $_POST['lf_description
'],
1172 'private' => (isset($_POST['lf_private
']) ? 1 : 0),
1173 'tags
' => str_replace(',', ' ', $tags),
1176 // If title is empty, use the URL as title.
1177 if ($link['title
'] == '') {
1178 $link['title
'] = $link['url
'];
1181 if ($conf->get('thumbnails
.mode
', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE
1182 && ! is_note($link['url
'])
1184 $thumbnailer = new Thumbnailer($conf);
1185 $link['thumbnail
'] = $thumbnailer->get($url);
1188 $link['sticky
'] = isset($link['sticky
']) ? $link['sticky
'] : false;
1190 $pluginManager->executeHooks('save_link
', $link);
1192 $LINKSDB[$id] = $link;
1193 $LINKSDB->save($conf->get('resource.page_cache
'));
1195 $history->addLink($link);
1197 $history->updateLink($link);
1200 // If we are called from the bookmarklet, we must close the popup:
1201 if (isset($_GET['source
']) && ($_GET['source
']=='bookmarklet
' || $_GET['source
']=='firefoxsocialapi
')) {
1202 echo '<script
>self
.close();</script
>';
1206 $returnurl = !empty($_POST['returnurl
']) ? $_POST['returnurl
'] : '?';
1207 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST
'], array('addlink
', 'post
', 'edit_link
'));
1208 // Scroll to the link which has been edited.
1209 $location .= '#' . $link['shorturl'];
1210 // After saving the link, redirect to the page the user was on.
1211 header('Location: '. $location);
1215 // -------- User clicked the "Cancel" button when editing a link.
1216 if (isset($_POST['cancel_edit'])) {
1217 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1218 if (! isset($LINKSDB[$id])) {
1219 header('Location: ?');
1221 // If we are called from the bookmarklet, we must close the popup:
1222 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1223 echo '<script>self.close();</script>';
1226 $link = $LINKSDB[$id];
1227 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1228 // Scroll to the link which has been edited.
1229 $returnurl .= '#'. $link['shorturl'];
1230 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1231 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1235 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1236 if ($targetPage == Router
::$PAGE_DELETELINK) {
1237 if (! $sessionManager->checkToken($_GET['token'])) {
1238 die(t('Wrong token.'));
1241 $ids = trim($_GET['lf_linkdate']);
1242 if (strpos($ids, ' ') !== false) {
1243 // multiple, space-separated ids provided
1244 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1246 // only a single id provided
1249 // assert at least one id is given
1251 die('no id provided');
1253 foreach ($ids as $id) {
1254 $id = (int) escape($id);
1255 $link = $LINKSDB[$id];
1256 $pluginManager->executeHooks('delete_link', $link);
1257 $history->deleteLink($link);
1258 unset($LINKSDB[$id]);
1260 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1262 // If we are called from the bookmarklet, we must close the popup:
1263 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1264 echo '<script>self.close();</script>';
1269 if (isset($_SERVER['HTTP_REFERER'])) {
1270 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1271 $location = generateLocation(
1272 $_SERVER['HTTP_REFERER'],
1273 $_SERVER['HTTP_HOST'],
1274 ['delete_link', 'edit_link', $link['shorturl']]
1278 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1282 // -------- User clicked either "Set public" or "Set private" bulk operation
1283 if ($targetPage == Router
::$PAGE_CHANGE_VISIBILITY) {
1284 if (! $sessionManager->checkToken($_GET['token'])) {
1285 die(t('Wrong token.'));
1288 $ids = trim($_GET['ids']);
1289 if (strpos($ids, ' ') !== false) {
1290 // multiple, space-separated ids provided
1291 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1293 // only a single id provided
1297 // assert at least one id is given
1299 die('no id provided');
1301 // assert that the visibility is valid
1302 if (!isset($_GET['newVisibility']) || !in_array($_GET['newVisibility'], ['public', 'private'])) {
1303 die('invalid visibility');
1305 $private = $_GET['newVisibility'] === 'private';
1307 foreach ($ids as $id) {
1308 $id = (int) escape($id);
1309 $link = $LINKSDB[$id];
1310 $link['private'] = $private;
1311 $pluginManager->executeHooks('save_link', $link);
1312 $LINKSDB[$id] = $link;
1314 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1317 if (isset($_SERVER['HTTP_REFERER'])) {
1318 $location = generateLocation(
1319 $_SERVER['HTTP_REFERER'],
1320 $_SERVER['HTTP_HOST']
1323 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1327 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1328 if (isset($_GET['edit_link'])) {
1329 $id = (int) escape($_GET['edit_link']);
1330 $link = $LINKSDB[$id]; // Read database
1332 header('Location: ?');
1334 } // Link not found in database.
1335 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1338 'link_is_new' => false,
1339 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1340 'tags' => $LINKSDB->linksCountPerTag(),
1342 $pluginManager->executeHooks('render_editlink', $data);
1344 foreach ($data as $key => $value) {
1345 $PAGE->assign($key, $value);
1348 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1349 $PAGE->renderPage('editlink');
1353 // -------- User want to post a new link: Display link edit form.
1354 if (isset($_GET['post'])) {
1355 $url = cleanup_url($_GET['post']);
1357 $link_is_new = false;
1358 // Check if URL is not already in database (in this case, we will edit the existing link)
1359 $link = $LINKSDB->getLinkFromUrl($url);
1361 $link_is_new = true;
1362 $linkdate = strval(date(LinkDB
::LINK_DATE_FORMAT
));
1363 // Get title if it was provided in URL (by the bookmarklet).
1364 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1365 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1366 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1367 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1368 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1370 // If this is an HTTP(S) link, we try go get the page to extract
1371 // the title (otherwise we will to straight to the edit form.)
1372 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1373 $retrieveDescription = $conf->get('general.retrieve_description');
1374 // Short timeout to keep the application responsive
1375 // The callback will fill $charset and $title with data from the downloaded page.
1378 $conf->get('general.download_timeout', 30),
1379 $conf->get('general.download_max_size', 4194304),
1380 get_curl_download_callback($charset, $title, $description, $tags, $retrieveDescription)
1382 if (! empty($title) && strtolower($charset) != 'utf-8') {
1383 $title = mb_convert_encoding($title, 'utf-8', $charset);
1388 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1389 $title = $conf->get('general.default_note_title', t('Note: '));
1391 $url = escape($url);
1392 $title = escape($title);
1395 'linkdate' => $linkdate,
1398 'description' => $description,
1400 'private' => $private,
1403 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1408 'link_is_new' => $link_is_new,
1409 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1410 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1411 'tags' => $LINKSDB->linksCountPerTag(),
1412 'default_private_links' => $conf->get('privacy.default_private_links', false),
1414 $pluginManager->executeHooks('render_editlink', $data);
1416 foreach ($data as $key => $value) {
1417 $PAGE->assign($key, $value);
1420 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1421 $PAGE->renderPage('editlink');
1425 if ($targetPage == Router
::$PAGE_PINLINK) {
1426 if (! isset($_GET['id']) || empty($LINKSDB[$_GET['id']])) {
1427 // FIXME! Use a proper error system.
1428 $msg = t('Invalid link ID provided');
1429 echo '<script>alert("'. $msg .'");document.location=\''. index_url($_SERVER) .'\';</script>';
1432 if (! $sessionManager->checkToken($_GET['token'])) {
1433 die('Wrong token.');
1436 $link = $LINKSDB[$_GET['id']];
1437 $link['sticky'] = ! $link['sticky'];
1438 $LINKSDB[(int) $_GET['id']] = $link;
1439 $LINKSDB->save($conf->get('resource.page_cache'));
1440 header('Location: '.index_url($_SERVER));
1444 if ($targetPage == Router
::$PAGE_EXPORT) {
1445 // Export links as a Netscape Bookmarks file
1447 if (empty($_GET['selection'])) {
1448 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1449 $PAGE->renderPage('export');
1453 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1454 $selection = $_GET['selection'];
1455 if (isset($_GET['prepend_note_url'])) {
1456 $prependNoteUrl = $_GET['prepend_note_url'];
1458 $prependNoteUrl = false;
1464 NetscapeBookmarkUtils
::filterAndFormat(
1471 } catch (Exception
$exc) {
1472 header('Content-Type: text/plain; charset=utf-8');
1473 echo $exc->getMessage();
1476 $now = new DateTime();
1477 header('Content-Type: text/html; charset=utf-8');
1479 'Content-disposition: attachment; filename=bookmarks_'
1480 .$selection.'_'.$now->format(LinkDB
::LINK_DATE_FORMAT
).'.html'
1482 $PAGE->assign('date', $now->format(DateTime
::RFC822
));
1483 $PAGE->assign('eol', PHP_EOL
);
1484 $PAGE->assign('selection', $selection);
1485 $PAGE->renderPage('export.bookmarks');
1489 if ($targetPage == Router
::$PAGE_IMPORT) {
1490 // Upload a Netscape bookmark dump to import its contents
1492 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1493 // Show import dialog
1496 get_max_upload_size(
1497 ini_get('post_max_size'),
1498 ini_get('upload_max_filesize'),
1504 get_max_upload_size(
1505 ini_get('post_max_size'),
1506 ini_get('upload_max_filesize'),
1510 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1511 $PAGE->renderPage('import');
1515 // Import bookmarks from an uploaded file
1516 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1517 // The file is too big or some form field may be missing.
1520 'The file you are trying to upload is probably bigger than what this webserver can accept'
1521 .' (%s). Please upload in smaller chunks.'
1523 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1525 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router
::$PAGE_IMPORT .'\';</script>';
1528 if (! $sessionManager->checkToken($_POST['token'])) {
1529 die('Wrong token.');
1531 $status = NetscapeBookmarkUtils
::import(
1538 echo '<script>alert("'.$status.'");document.location=\'?do='
1539 .Router
::$PAGE_IMPORT .'\';</script>';
1543 // Plugin administration page
1544 if ($targetPage == Router
::$PAGE_PLUGINSADMIN) {
1545 $pluginMeta = $pluginManager->getPluginsMeta();
1547 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1548 $enabledPlugins = array_filter($pluginMeta, function ($v) {
1549 return $v['order'] !== false;
1552 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1556 return $a['order'] - $b['order'];
1559 $disabledPlugins = array_filter($pluginMeta, function ($v) {
1560 return $v['order'] === false;
1563 $PAGE->assign('enabledPlugins', $enabledPlugins);
1564 $PAGE->assign('disabledPlugins', $disabledPlugins);
1565 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
1566 $PAGE->renderPage('pluginsadmin');
1570 // Plugin administration form action
1571 if ($targetPage == Router
::$PAGE_SAVE_PLUGINSADMIN) {
1573 if (isset($_POST['parameters_form'])) {
1574 $pluginManager->executeHooks('save_plugin_parameters', $_POST);
1575 unset($_POST['parameters_form']);
1576 foreach ($_POST as $param => $value) {
1577 $conf->set('plugins.'. $param, escape($value));
1580 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1582 $conf->write($loginManager->isLoggedIn());
1583 $history->updateSettings();
1584 } catch (Exception
$e) {
1586 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1590 // TODO: do not handle exceptions/errors in JS.
1591 echo '<script>alert("'
1593 .'");document.location=\'?do='
1594 . Router
::$PAGE_PLUGINSADMIN
1598 header('Location: ?do='. Router
::$PAGE_PLUGINSADMIN);
1602 // Get a fresh token
1603 if ($targetPage == Router
::$GET_TOKEN) {
1604 header('Content-Type:text/plain');
1605 echo $sessionManager->generateToken($conf);
1609 // -------- Thumbnails Update
1610 if ($targetPage == Router
::$PAGE_THUMBS_UPDATE) {
1612 foreach ($LINKSDB as $link) {
1613 // A note or not HTTP(S)
1614 if (is_note($link['url']) || ! startsWith(strtolower($link['url']), 'http')) {
1617 $ids[] = $link['id'];
1619 $PAGE->assign('ids', $ids);
1620 $PAGE->assign('pagetitle', t('Thumbnails update') .' - '. $conf->get('general.title', 'Shaarli'));
1621 $PAGE->renderPage('thumbnails');
1625 // -------- Single Thumbnail Update
1626 if ($targetPage == Router
::$AJAX_THUMB_UPDATE) {
1627 if (! isset($_POST['id']) || ! ctype_digit($_POST['id'])) {
1628 http_response_code(400);
1631 $id = (int) $_POST['id'];
1632 if (empty($LINKSDB[$id])) {
1633 http_response_code(404);
1636 $thumbnailer = new Thumbnailer($conf);
1637 $link = $LINKSDB[$id];
1638 $link['thumbnail'] = $thumbnailer->get($link['url']);
1639 $LINKSDB[$id] = $link;
1640 $LINKSDB->save($conf->get('resource.page_cache'));
1642 echo json_encode($link);
1646 // -------- Otherwise, simply display search form and links:
1647 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
1652 * Template for the list of links (<div id="linklist">)
1653 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1655 * @param pageBuilder $PAGE pageBuilder instance.
1656 * @param LinkDB $LINKSDB LinkDB instance.
1657 * @param ConfigManager $conf Configuration Manager instance.
1658 * @param PluginManager $pluginManager Plugin Manager instance.
1659 * @param LoginManager $loginManager LoginManager instance
1661 function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1663 // Used in templates
1664 if (isset($_GET['searchtags'])) {
1665 if (! empty($_GET['searchtags'])) {
1666 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1668 $searchtags = false;
1673 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1676 if (! empty($_SERVER['QUERY_STRING'])
1677 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1679 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1680 } catch (LinkNotFoundException
$e) {
1681 $PAGE->render404($e->getMessage());
1685 // Filter links according search parameters.
1686 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
1688 'searchtags' => $searchtags,
1689 'searchterm' => $searchterm,
1691 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
1694 // ---- Handle paging.
1696 foreach ($linksToDisplay as $key => $value) {
1700 // Select articles according to paging.
1701 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1702 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1703 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1704 $page = $page < 1 ? 1 : $page;
1705 $page = $page > $pagecount ? $pagecount : $page;
1707 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1708 $end = $i +
$_SESSION['LINKS_PER_PAGE'];
1710 $thumbnailsEnabled = $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
) !== Thumbnailer
::MODE_NONE
;
1711 if ($thumbnailsEnabled) {
1712 $thumbnailer = new Thumbnailer($conf);
1715 $linkDisp = array();
1716 while ($i<$end && $i<count($keys)) {
1717 $link = $linksToDisplay[$keys[$i]];
1718 $link['description'] = format_description($link['description']);
1719 $classLi = ($i %
2) != 0 ? '' : 'publicLinkHightLight';
1720 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
1721 $link['timestamp'] = $link['created']->getTimestamp();
1722 if (! empty($link['updated'])) {
1723 $link['updated_timestamp'] = $link['updated']->getTimestamp();
1725 $link['updated_timestamp'] = '';
1727 $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY
);
1728 uasort($taglist, 'strcasecmp');
1729 $link['taglist'] = $taglist;
1731 // Logged in, thumbnails enabled, not a note,
1732 // and (never retrieved yet or no valid cache file)
1733 if ($loginManager->isLoggedIn() && $thumbnailsEnabled && $link['url'][0] != '?'
1734 && (! isset($link['thumbnail']) || ($link['thumbnail'] !== false && ! is_file($link['thumbnail'])))
1736 $elem = $LINKSDB[$keys[$i]];
1737 $elem['thumbnail'] = $thumbnailer->get($link['url']);
1738 $LINKSDB[$keys[$i]] = $elem;
1740 $link['thumbnail'] = $elem['thumbnail'];
1743 // Check for both signs of a note: starting with ? and 7 chars long.
1744 if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
1745 $link['url'] = index_url($_SERVER) . $link['url'];
1748 $linkDisp[$keys[$i]] = $link;
1752 // If we retrieved new thumbnails, we update the database.
1753 if (!empty($updateDB)) {
1754 $LINKSDB->save($conf->get('resource.page_cache'));
1757 // Compute paging navigation
1758 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
1759 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1760 $previous_page_url = '';
1761 if ($i != count($keys)) {
1762 $previous_page_url = '?page=' . ($page+
1) . $searchtermUrl . $searchtagsUrl;
1766 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1769 // Fill all template fields.
1771 'previous_page_url' => $previous_page_url,
1772 'next_page_url' => $next_page_url,
1773 'page_current' => $page,
1774 'page_max' => $pagecount,
1775 'result_count' => count($linksToDisplay),
1776 'search_term' => $searchterm,
1777 'search_tags' => $searchtags,
1778 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
1779 'links' => $linkDisp,
1782 // If there is only a single link, we change on-the-fly the title of the page.
1783 if (count($linksToDisplay) == 1) {
1784 $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
1785 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1786 $data['pagetitle'] = t('Search: ');
1787 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1788 $bracketWrap = function ($tag) {
1789 return '['. $tag .']';
1791 $data['pagetitle'] .= ! empty($searchtags)
1792 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1794 $data['pagetitle'] .= '- '. $conf->get('general.title');
1797 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
1799 foreach ($data as $key => $value) {
1800 $PAGE->assign($key, $value);
1808 * This function should NEVER be called if the file data/config.php exists.
1810 * @param ConfigManager $conf Configuration Manager instance.
1811 * @param SessionManager $sessionManager SessionManager instance
1812 * @param LoginManager $loginManager LoginManager instance
1814 function install($conf, $sessionManager, $loginManager)
1816 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1817 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
1818 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
1822 // This part makes sure sessions works correctly.
1823 // (Because on some hosts, session.save_path may not be set correctly,
1824 // or we may not have write access to it.)
1825 if (isset($_GET['test_session'])
1826 && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
1827 // Step 2: Check if data in session is correct.
1829 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1830 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1831 'and that you have write access to it.<br>'.
1832 'It currently points to %s.<br>'.
1833 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1834 'or any custom hostname without a dot causes cookie storage to fail. '.
1835 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1837 $msg = sprintf($msg, session_save_path());
1839 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1842 if (!isset($_SESSION['session_tested'])) {
1843 // Step 1 : Try to store data in session and reload page.
1844 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1845 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1847 if (isset($_GET['test_session'])) {
1848 // Step 3: Sessions are OK. Remove test parameter from URL.
1849 header('Location: '.index_url($_SERVER));
1853 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
1855 if (!empty($_POST['continent']) && !empty($_POST['city'])
1856 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1858 $tz = $_POST['continent'].'/'.$_POST['city'];
1860 $conf->set('general.timezone', $tz);
1861 $login = $_POST['setlogin'];
1862 $conf->set('credentials.login', $login);
1863 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1864 $conf->set('credentials.salt', $salt);
1865 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
1866 if (!empty($_POST['title'])) {
1867 $conf->set('general.title', escape($_POST['title']));
1869 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
1871 $conf->set('translation.language', escape($_POST['language']));
1872 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1873 $conf->set('api.enabled', !empty($_POST['enableApi']));
1876 generate_api_secret(
1877 $conf->get('credentials.login'),
1878 $conf->get('credentials.salt')
1882 // Everything is ok, let's create config file.
1883 $conf->write($loginManager->isLoggedIn());
1884 } catch (Exception
$e) {
1886 'ERROR while writing config file after installation.' . PHP_EOL
.
1890 // TODO: do not handle exceptions/errors in JS.
1891 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1894 echo '<script>alert('
1895 .'"Shaarli is now configured. '
1896 .'Please enter your login/password and start shaaring your links!"'
1897 .');document.location=\'?do=login\';</script>';
1901 $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
1902 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1903 $PAGE->assign('continents', $continents);
1904 $PAGE->assign('cities', $cities);
1905 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1906 $PAGE->renderPage('install');
1910 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) {
1911 showDailyRSS($conf, $loginManager);
1915 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
1916 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
1920 $history = new History($conf->get('resource.history'));
1921 } catch (Exception
$e) {
1922 die($e->getMessage());
1925 $linkDb = new LinkDB(
1926 $conf->get('resource.datastore'),
1927 $loginManager->isLoggedIn(),
1928 $conf->get('privacy.hide_public_links')
1931 $container = new \Slim\
Container();
1932 $container['conf'] = $conf;
1933 $container['plugins'] = $pluginManager;
1934 $container['history'] = $history;
1935 $app = new \Slim\
App($container);
1938 $app->group('/api/v1', function () {
1939 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
1940 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
1941 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
1942 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
1943 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
1944 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
1946 $this->get('/tags', '\Shaarli\Api\Controllers\Tags:getTags')->setName('getTags');
1947 $this->get('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:getTag')->setName('getTag');
1948 $this->put('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:putTag')->setName('putTag');
1949 $this->delete('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:deleteTag')->setName('deleteTag');
1951 $this->get('/history', '\Shaarli\Api\Controllers\HistoryController:getHistory')->setName('getHistory');
1952 })->add('\Shaarli\Api\ApiMiddleware');
1954 $response = $app->run(true);
1956 // Hack to make Slim and Shaarli router work together:
1957 // If a Slim route isn't found and NOT API call, we call renderPage().
1958 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
1959 // We use UTF-8 for proper international characters handling.
1960 header('Content-Type: text/html; charset=utf-8');
1961 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
1963 $response = $response
1964 ->withHeader('Access-Control-Allow-Origin', '*')
1966 'Access-Control-Allow-Headers',
1967 'X-Requested-With, Content-Type, Accept, Origin, Authorization'
1969 ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
1970 $app->respond($response);