3 * Shaarli - The personal, minimalist, super-fast, database free, bookmarking service.
5 * Friendly fork by the Shaarli community:
6 * - https://github.com/shaarli/Shaarli
8 * Original project by sebsauvage.net:
9 * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
10 * - https://github.com/sebsauvage/Shaarli
12 * Licence: http://www.opensource.org/licenses/zlib-license.php
15 // Set 'UTC' as the default timezone if it is not defined in php.ini
16 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
17 if (date_default_timezone_get() == '') {
18 date_default_timezone_set('UTC');
25 // http://server.com/x/shaarli --> /shaarli/
26 define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+
strrpos($_SERVER['REQUEST_URI'], '/', 0)));
28 // High execution time in case of problematic imports/exports.
29 ini_set('max_input_time', '60');
31 // Try to set max upload file size and read
32 ini_set('memory_limit', '128M');
33 ini_set('post_max_size', '16M');
34 ini_set('upload_max_filesize', '16M');
36 // See all error except warnings
37 error_reporting(E_ALL^E_WARNING
);
39 // 3rd-party libraries
40 if (! file_exists(__DIR__
. '/vendor/autoload.php')) {
41 header('Content-Type: text/plain; charset=utf-8');
42 echo "Error: missing Composer configuration\n\n"
43 ."If you installed Shaarli through Git or using the development branch,\n"
44 ."please refer to the installation documentation to install PHP"
45 ." dependencies using Composer:\n"
46 ."- https://shaarli.readthedocs.io/en/master/Server-configuration/\n"
47 ."- https://shaarli.readthedocs.io/en/master/Download-and-Installation/";
50 require_once 'inc/rain.tpl.class.php';
51 require_once __DIR__
. '/vendor/autoload.php';
54 require_once 'application/bookmark/LinkUtils.php';
55 require_once 'application/config/ConfigPlugin.php';
56 require_once 'application/feed/Cache.php';
57 require_once 'application/http/HttpUtils.php';
58 require_once 'application/http/UrlUtils.php';
59 require_once 'application/updater/UpdaterUtils.php';
60 require_once 'application/FileUtils.php';
61 require_once 'application/TimeZone.php';
62 require_once 'application/Utils.php';
64 use \Shaarli\ApplicationUtils
;
65 use Shaarli\Bookmark\BookmarkServiceInterface
;
66 use \Shaarli\Bookmark\Exception\BookmarkNotFoundException
;
67 use Shaarli\Bookmark\Bookmark
;
68 use Shaarli\Bookmark\BookmarkFilter
;
69 use Shaarli\Bookmark\BookmarkFileService
;
70 use \Shaarli\Config\ConfigManager
;
71 use \Shaarli\Feed\CachedPage
;
72 use \Shaarli\Feed\FeedBuilder
;
73 use Shaarli\Formatter\FormatterFactory
;
75 use \Shaarli\Languages
;
76 use \Shaarli\Netscape\NetscapeBookmarkUtils
;
77 use \Shaarli\Plugin\PluginManager
;
78 use \Shaarli\Render\PageBuilder
;
79 use \Shaarli\Render\ThemeUtils
;
81 use \Shaarli\Security\LoginManager
;
82 use \Shaarli\Security\SessionManager
;
83 use \Shaarli\Thumbnailer
;
84 use \Shaarli\Updater\Updater
;
85 use \Shaarli\Updater\UpdaterUtils
;
87 // Ensure the PHP version is supported
89 ApplicationUtils
::checkPHPVersion('7.1', PHP_VERSION
);
90 } catch (Exception
$exc) {
91 header('Content-Type: text/plain; charset=utf-8');
92 echo $exc->getMessage();
96 define('SHAARLI_VERSION', ApplicationUtils
::getVersion(__DIR__
.'/'. ApplicationUtils
::$VERSION_FILE));
98 // Force cookie path (but do not change lifetime)
99 $cookie = session_get_cookie_params();
101 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
102 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
104 // Set default cookie expiration and path.
105 session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
106 // Set session parameters on server side.
107 // Use cookies to store session.
108 ini_set('session.use_cookies', 1);
109 // Force cookies for session (phpsessionID forbidden in URL).
110 ini_set('session.use_only_cookies', 1);
111 // Prevent PHP form using sessionID in URL if cookies are disabled.
112 ini_set('session.use_trans_sid', false);
114 session_name('shaarli');
115 // Start session if needed (Some server auto-start sessions).
116 if (session_status() == PHP_SESSION_NONE
) {
120 // Regenerate session ID if invalid or not defined in cookie.
121 if (isset($_COOKIE['shaarli']) && !SessionManager
::checkId($_COOKIE['shaarli'])) {
122 session_regenerate_id(true);
123 $_COOKIE['shaarli'] = session_id();
126 $conf = new ConfigManager();
128 // In dev mode, throw exception on any warning
129 if ($conf->get('dev.debug', false)) {
130 // See all errors (for debugging only)
133 set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
134 throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
138 $sessionManager = new SessionManager($_SESSION, $conf);
139 $loginManager = new LoginManager($conf, $sessionManager);
140 $loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
141 $clientIpId = client_ip_id($_SERVER);
143 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
144 if (! defined('LC_MESSAGES')) {
145 define('LC_MESSAGES', LC_COLLATE
);
148 // Sniff browser language and set date format accordingly.
149 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
150 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
153 new Languages(setlocale(LC_MESSAGES
, 0), $conf);
155 $conf->setEmpty('general.timezone', date_default_timezone_get());
156 $conf->setEmpty('general.title', t('Shared bookmarks on '). escape(index_url($_SERVER)));
157 RainTPL
::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
158 RainTPL
::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
160 $pluginManager = new PluginManager($conf);
161 $pluginManager->load($conf->get('general.enabled_plugins'));
163 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
165 ob_start(); // Output buffering for the page cache.
167 // Prevent caching on client side or proxy: (yes, it's ugly)
168 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
169 header("Cache-Control: no-store, no-cache, must-revalidate");
170 header("Cache-Control: post-check=0, pre-check=0", false);
171 header("Pragma: no-cache");
173 if (! is_file($conf->getConfigFileExt())) {
174 // Ensure Shaarli has proper access to its resources
175 $errors = ApplicationUtils
::checkResourcePermissions($conf);
177 if ($errors != array()) {
178 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
180 foreach ($errors as $error) {
181 $message .= '<li>'.$error.'</li>';
185 header('Content-Type: text/html; charset=utf-8');
190 // Display the installation form if no existing config is found
191 install($conf, $sessionManager, $loginManager);
194 $loginManager->checkLoginState($_COOKIE, $clientIpId);
197 * Adapter function to ensure compatibility with third-party templates
199 * @see https://github.com/shaarli/Shaarli/pull/1086
201 * @return bool true when the user is logged in, false otherwise
203 function isLoggedIn()
205 global $loginManager;
206 return $loginManager->isLoggedIn();
210 // ------------------------------------------------------------------------------------------
211 // Process login form: Check if login/password is correct.
212 if (isset($_POST['login'])) {
213 if (! $loginManager->canLogin($_SERVER)) {
214 die(t('I said: NO. You are banned for the moment. Go away.'));
216 if (isset($_POST['password'])
217 && $sessionManager->checkToken($_POST['token'])
218 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
220 $loginManager->handleSuccessfulLogin($_SERVER);
223 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
224 // Note: Never forget the trailing slash on the cookie path!
225 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
228 if (!empty($_POST['longlastingsession'])) {
229 // Keep the session cookie even after the browser closes
230 $sessionManager->setStaySignedIn(true);
231 $expirationTime = $sessionManager->extendSession();
234 $loginManager::$STAY_SIGNED_IN_COOKIE,
235 $loginManager->getStaySignedInToken(),
240 // Standard session expiration (=when browser closes)
244 // Send cookie with the new expiration date to the browser
245 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
246 session_regenerate_id(true);
248 // Optional redirect after login:
249 if (isset($_GET['post'])) {
250 $uri = '?post='. urlencode($_GET['post']);
251 foreach (array('description', 'source', 'title', 'tags') as $param) {
252 if (!empty($_GET[$param])) {
253 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
256 header('Location: '. $uri);
260 if (isset($_GET['edit_link'])) {
261 header('Location: ?edit_link='. escape($_GET['edit_link']));
265 if (isset($_POST['returnurl'])) {
266 // Prevent loops over login screen.
267 if (strpos($_POST['returnurl'], 'do=login') === false) {
268 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
272 header('Location: ?');
275 $loginManager->handleFailedLogin($_SERVER);
276 $redir = '&username='. urlencode($_POST['login']);
277 if (isset($_GET['post'])) {
278 $redir .= '&post=' . urlencode($_GET['post']);
279 foreach (array('description', 'source', 'title', 'tags') as $param) {
280 if (!empty($_GET[$param])) {
281 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
285 // Redirect to login screen.
286 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
291 // ------------------------------------------------------------------------------------------
292 // Token management for XSRF protection
293 // Token should be used in any form which acts on data (create,update,delete,import...).
294 if (!isset($_SESSION['tokens'])) {
295 $_SESSION['tokens']=array(); // Token are attached to the session.
299 * Daily RSS feed: 1 RSS entry per day giving all the bookmarks on that day.
300 * Gives the last 7 days (which have bookmarks).
301 * This RSS feed cannot be filtered.
303 * @param BookmarkServiceInterface $bookmarkService
304 * @param ConfigManager $conf Configuration Manager instance
305 * @param LoginManager $loginManager LoginManager instance
307 function showDailyRSS($bookmarkService, $conf, $loginManager)
310 $query = $_SERVER['QUERY_STRING'];
311 $cache = new CachedPage(
312 $conf->get('config.PAGE_CACHE'),
314 startsWith($query, 'do=dailyrss') && !$loginManager->isLoggedIn()
316 $cached = $cache->cachedVersion();
317 if (!empty($cached)) {
322 /* Some Shaarlies may have very few bookmarks, so we need to look
323 back in time until we have enough days ($nb_of_days).
325 $nb_of_days = 7; // We take 7 days.
326 $today = date('Ymd');
329 foreach ($bookmarkService->search() as $bookmark) {
330 $day = $bookmark->getCreated()->format('Ymd'); // Extract day (without time)
331 if (strcmp($day, $today) < 0) {
332 if (empty($days[$day])) {
333 $days[$day] = array();
335 $days[$day][] = $bookmark;
338 if (count($days) > $nb_of_days) {
339 break; // Have we collected enough days?
343 // Build the RSS feed.
344 header('Content-Type: application/rss+xml; charset=utf-8');
345 $pageaddr = escape(index_url($_SERVER));
346 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
348 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
349 echo '<link>'. $pageaddr .'</link>';
350 echo '<description>Daily shared bookmarks</description>';
351 echo '<language>en-en</language>';
352 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL
;
354 $factory = new FormatterFactory($conf);
355 $formatter = $factory->getFormatter();
356 $formatter->addContextData('index_url', index_url($_SERVER));
358 /** @var Bookmark[] $bookmarks */
359 foreach ($days as $day => $bookmarks) {
360 $formattedBookmarks = [];
361 $dayDate = DateTime
::createFromFormat(Bookmark
::LINK_DATE_FORMAT
, $day.'_000000');
362 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
364 // We pre-format some fields for proper output.
365 foreach ($bookmarks as $key => $bookmark) {
366 $formattedBookmarks[$key] = $formatter->format($bookmark);
367 // This page is a bit specific, we need raw description to calculate the length
368 $formattedBookmarks[$key]['formatedDescription'] = $formattedBookmarks[$key]['description'];
369 $formattedBookmarks[$key]['description'] = $bookmark->getDescription();
371 if ($bookmark->isNote()) {
372 $link['url'] = index_url($_SERVER) . $bookmark->getUrl(); // make permalink URL absolute
376 // Then build the HTML for this day:
377 $tpl = new RainTPL();
378 $tpl->assign('title', $conf->get('general.title'));
379 $tpl->assign('daydate', $dayDate->getTimestamp());
380 $tpl->assign('absurl', $absurl);
381 $tpl->assign('links', $formattedBookmarks);
382 $tpl->assign('rssdate', escape($dayDate->format(DateTime
::RSS
)));
383 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
384 $tpl->assign('index_url', $pageaddr);
385 $html = $tpl->draw('dailyrss', true);
387 echo $html . PHP_EOL
;
389 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
391 $cache->cache(ob_get_contents());
397 * Show the 'Daily' page.
399 * @param PageBuilder $pageBuilder Template engine wrapper.
400 * @param BookmarkServiceInterface $bookmarkService instance.
401 * @param ConfigManager $conf Configuration Manager instance.
402 * @param PluginManager $pluginManager Plugin Manager instance.
403 * @param LoginManager $loginManager Login Manager instance
405 function showDaily($pageBuilder, $bookmarkService, $conf, $pluginManager, $loginManager)
407 if (isset($_GET['day'])) {
409 if ($day === date('Ymd', strtotime('now'))) {
410 $pageBuilder->assign('dayDesc', t('Today'));
411 } elseif ($day === date('Ymd', strtotime('-1 days'))) {
412 $pageBuilder->assign('dayDesc', t('Yesterday'));
415 $day = date('Ymd', strtotime('now')); // Today, in format YYYYMMDD.
416 $pageBuilder->assign('dayDesc', t('Today'));
419 $days = $bookmarkService->days();
420 $i = array_search($day, $days);
421 if ($i === false && count($days)) {
422 // no bookmarks for day, but at least one day with bookmarks
423 $i = count($days) - 1;
431 $previousday = $days[$i - 1];
433 if ($i < count($days) - 1) {
434 $nextday = $days[$i +
1];
438 $linksToDisplay = $bookmarkService->filterDay($day);
439 } catch (Exception
$exc) {
441 $linksToDisplay = [];
444 $factory = new FormatterFactory($conf);
445 $formatter = $factory->getFormatter();
446 // We pre-format some fields for proper output.
447 foreach ($linksToDisplay as $key => $bookmark) {
448 $linksToDisplay[$key] = $formatter->format($bookmark);
449 // This page is a bit specific, we need raw description to calculate the length
450 $linksToDisplay[$key]['formatedDescription'] = $linksToDisplay[$key]['description'];
451 $linksToDisplay[$key]['description'] = $bookmark->getDescription();
454 $dayDate = DateTime
::createFromFormat(Bookmark
::LINK_DATE_FORMAT
, $day.'_000000');
456 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
457 'linksToDisplay' => $linksToDisplay,
458 'day' => $dayDate->getTimestamp(),
459 'dayDate' => $dayDate,
460 'previousday' => $previousday,
461 'nextday' => $nextday,
464 /* Hook is called before column construction so that plugins don't have
465 to deal with columns. */
466 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
468 /* We need to spread the articles on 3 columns.
469 I did not want to use a JavaScript lib like http://masonry.desandro.com/
470 so I manually spread entries with a simple method: I roughly evaluate the
471 height of a div according to title and description length.
473 $columns = array(array(), array(), array()); // Entries to display, for each column.
474 $fill = array(0, 0, 0); // Rough estimate of columns fill.
475 foreach ($data['linksToDisplay'] as $key => $bookmark) {
476 // Roughly estimate length of entry (by counting characters)
477 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
478 // Description: 836 characters gives roughly 342 pixel height.
479 // This is not perfect, but it's usually OK.
480 $length = strlen($bookmark['title']) +
(342 * strlen($bookmark['description'])) / 836;
481 if (! empty($bookmark['thumbnail'])) {
482 $length +
= 100; // 1 thumbnails roughly takes 100 pixels height.
484 // Then put in column which is the less filled:
485 $smallest = min($fill); // find smallest value in array.
486 $index = array_search($smallest, $fill); // find index of this smallest value.
487 array_push($columns[$index], $bookmark); // Put entry in this column.
488 $fill[$index] +
= $length;
491 $data['cols'] = $columns;
493 foreach ($data as $key => $value) {
494 $pageBuilder->assign($key, $value);
497 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
498 $pageBuilder->renderPage('daily');
503 * Renders the linklist
505 * @param pageBuilder $PAGE pageBuilder instance.
506 * @param BookmarkServiceInterface $linkDb instance.
507 * @param ConfigManager $conf Configuration Manager instance.
508 * @param PluginManager $pluginManager Plugin Manager instance.
510 function showLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager)
512 buildLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager);
513 $PAGE->renderPage('linklist');
517 * Render HTML page (according to URL parameters and user rights)
519 * @param ConfigManager $conf Configuration Manager instance.
520 * @param PluginManager $pluginManager Plugin Manager instance,
521 * @param BookmarkServiceInterface $bookmarkService
522 * @param History $history instance
523 * @param SessionManager $sessionManager SessionManager instance
524 * @param LoginManager $loginManager LoginManager instance
526 function renderPage($conf, $pluginManager, $bookmarkService, $history, $sessionManager, $loginManager)
528 $updater = new Updater(
529 UpdaterUtils
::read_updates_file($conf->get('resource.updates')),
532 $loginManager->isLoggedIn()
535 $newUpdates = $updater->update();
536 if (! empty($newUpdates)) {
537 UpdaterUtils
::write_updates_file(
538 $conf->get('resource.updates'),
539 $updater->getDoneUpdates()
542 } catch (Exception
$e) {
543 die($e->getMessage());
546 $PAGE = new PageBuilder($conf, $_SESSION, $bookmarkService, $sessionManager->generateToken(), $loginManager->isLoggedIn());
547 $PAGE->assign('linkcount', $bookmarkService->count(BookmarkFilter
::$ALL));
548 $PAGE->assign('privateLinkcount', $bookmarkService->count(BookmarkFilter
::$PRIVATE));
549 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
551 // Determine which page will be rendered.
552 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
553 $targetPage = Router
::findPage($query, $_GET, $loginManager->isLoggedIn());
555 if (// if the user isn't logged in
556 !$loginManager->isLoggedIn() &&
557 // and Shaarli doesn't have public content...
558 $conf->get('privacy.hide_public_links') &&
559 // and is configured to enforce the login
560 $conf->get('privacy.force_login') &&
561 // and the current page isn't already the login page
562 $targetPage !== Router
::$PAGE_LOGIN &&
563 // and the user is not requesting a feed (which would lead to a different content-type as expected)
564 $targetPage !== Router
::$PAGE_FEED_ATOM &&
565 $targetPage !== Router
::$PAGE_FEED_RSS
567 // force current page to be the login page
568 $targetPage = Router
::$PAGE_LOGIN;
571 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
572 // Then assign generated data to RainTPL.
573 $common_hooks = array(
579 foreach ($common_hooks as $name) {
580 $plugin_data = array();
581 $pluginManager->executeHooks(
585 'target' => $targetPage,
586 'loggedin' => $loginManager->isLoggedIn()
589 $PAGE->assign('plugins_' . $name, $plugin_data);
592 // -------- Display login form.
593 if ($targetPage == Router
::$PAGE_LOGIN) {
594 if ($conf->get('security.open_shaarli')) {
595 header('Location: ?');
597 } // No need to login for open Shaarli
598 if (isset($_GET['username'])) {
599 $PAGE->assign('username', escape($_GET['username']));
601 $PAGE->assign('returnurl', (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
602 // add default state of the 'remember me' checkbox
603 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
604 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
605 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
606 $PAGE->renderPage('loginform');
609 // -------- User wants to logout.
610 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) {
611 invalidateCaches($conf->get('resource.page_cache'));
612 $sessionManager->logout();
613 setcookie(LoginManager
::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH
);
614 header('Location: ?');
618 // -------- Picture wall
619 if ($targetPage == Router
::$PAGE_PICWALL) {
620 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
621 if (! $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
) === Thumbnailer
::MODE_NONE
) {
622 $PAGE->assign('linksToDisplay', []);
623 $PAGE->renderPage('picwall');
627 // Optionally filter the results:
628 $links = $bookmarkService->search($_GET);
629 $linksToDisplay = [];
631 // Get only bookmarks which have a thumbnail.
632 // Note: we do not retrieve thumbnails here, the request is too heavy.
633 $factory = new FormatterFactory($conf);
634 $formatter = $factory->getFormatter();
635 foreach ($links as $key => $link) {
636 if ($link->getThumbnail() !== false) {
637 $linksToDisplay[] = $formatter->format($link);
642 'linksToDisplay' => $linksToDisplay,
644 $pluginManager->executeHooks('render_picwall', $data, ['loggedin' => $loginManager->isLoggedIn()]);
646 foreach ($data as $key => $value) {
647 $PAGE->assign($key, $value);
650 $PAGE->renderPage('picwall');
654 // -------- Tag cloud
655 if ($targetPage == Router
::$PAGE_TAGCLOUD) {
656 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
657 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
658 $tags = $bookmarkService->bookmarksCountPerTag($filteringTags, $visibility);
660 // We sort tags alphabetically, then choose a font size according to count.
661 // First, find max value.
663 foreach ($tags as $value) {
664 $maxcount = max($maxcount, $value);
667 alphabetical_sort($tags, false, true);
670 foreach ($tags as $key => $value) {
671 if (in_array($key, $filteringTags)) {
674 // Tag font size scaling:
675 // default 15 and 30 logarithm bases affect scaling,
676 // 22 and 6 are arbitrary font sizes for max and min sizes.
677 $size = log($value, 15) / log($maxcount, 30) * 2.2 +
0.8;
678 $tagList[$key] = array(
680 'size' => number_format($size, 2, '.', ''),
684 $searchTags = implode(' ', escape($filteringTags));
686 'search_tags' => $searchTags,
689 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
691 foreach ($data as $key => $value) {
692 $PAGE->assign($key, $value);
695 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
696 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
697 $PAGE->renderPage('tag.cloud');
702 if ($targetPage == Router
::$PAGE_TAGLIST) {
703 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
704 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
705 $tags = $bookmarkService->bookmarksCountPerTag($filteringTags, $visibility);
706 foreach ($filteringTags as $tag) {
707 if (array_key_exists($tag, $tags)) {
712 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
713 alphabetical_sort($tags, false, true);
716 $searchTags = implode(' ', escape($filteringTags));
718 'search_tags' => $searchTags,
721 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
723 foreach ($data as $key => $value) {
724 $PAGE->assign($key, $value);
727 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
728 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
729 $PAGE->renderPage('tag.list');
734 if ($targetPage == Router
::$PAGE_DAILY) {
735 showDaily($PAGE, $bookmarkService, $conf, $pluginManager, $loginManager);
738 // ATOM and RSS feed.
739 if ($targetPage == Router
::$PAGE_FEED_ATOM || $targetPage == Router
::$PAGE_FEED_RSS) {
740 $feedType = $targetPage == Router
::$PAGE_FEED_RSS ? FeedBuilder
::$FEED_RSS : FeedBuilder
::$FEED_ATOM;
741 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
744 $query = $_SERVER['QUERY_STRING'];
745 $cache = new CachedPage(
746 $conf->get('resource.page_cache'),
748 startsWith($query, 'do='. $targetPage) && !$loginManager->isLoggedIn()
750 $cached = $cache->cachedVersion();
751 if (!empty($cached)) {
756 $factory = new FormatterFactory($conf);
758 $feedGenerator = new FeedBuilder(
760 $factory->getFormatter(),
764 $loginManager->isLoggedIn()
766 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE
, 0)));
767 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
768 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
769 $data = $feedGenerator->buildData();
771 // Process plugin hook.
772 $pluginManager->executeHooks('render_feed', $data, array(
773 'loggedin' => $loginManager->isLoggedIn(),
774 'target' => $targetPage,
777 // Render the template.
778 $PAGE->assignAll($data);
779 $PAGE->renderPage('feed.'. $feedType);
780 $cache->cache(ob_get_contents());
785 // Display opensearch plugin (XML)
786 if ($targetPage == Router
::$PAGE_OPENSEARCH) {
787 header('Content-Type: application/xml; charset=utf-8');
788 $PAGE->assign('serverurl', index_url($_SERVER));
789 $PAGE->renderPage('opensearch');
793 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
794 if (isset($_GET['addtag'])) {
795 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
796 if (empty($_SERVER['HTTP_REFERER'])) {
797 // In case browser does not send HTTP_REFERER
798 header('Location: ?searchtags='.urlencode($_GET['addtag']));
801 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
803 // Prevent redirection loop
804 if (isset($params['addtag'])) {
805 unset($params['addtag']);
808 // Check if this tag is already in the search query and ignore it if it is.
809 // Each tag is always separated by a space
810 if (isset($params['searchtags'])) {
811 $current_tags = explode(' ', $params['searchtags']);
813 $current_tags = array();
816 foreach ($current_tags as $value) {
817 if ($value === $_GET['addtag']) {
822 // Append the tag if necessary
823 if (empty($params['searchtags'])) {
824 $params['searchtags'] = trim($_GET['addtag']);
826 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
829 // We also remove page (keeping the same page has no sense, since the
830 // results are different)
831 unset($params['page']);
833 header('Location: ?'.http_build_query($params));
837 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
838 if (isset($_GET['removetag'])) {
839 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
840 if (empty($_SERVER['HTTP_REFERER'])) {
841 header('Location: ?');
845 // In case browser does not send HTTP_REFERER
846 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
848 // Prevent redirection loop
849 if (isset($params['removetag'])) {
850 unset($params['removetag']);
853 if (isset($params['searchtags'])) {
854 $tags = explode(' ', $params['searchtags']);
855 // Remove value from array $tags.
856 $tags = array_diff($tags, array($_GET['removetag']));
857 $params['searchtags'] = implode(' ', $tags);
859 if (empty($params['searchtags'])) {
860 unset($params['searchtags']);
863 // We also remove page (keeping the same page has no sense, since
864 // the results are different)
865 unset($params['page']);
867 header('Location: ?'.http_build_query($params));
871 // -------- User wants to change the number of bookmarks per page (linksperpage=...)
872 if (isset($_GET['linksperpage'])) {
873 if (is_numeric($_GET['linksperpage'])) {
874 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
877 if (! empty($_SERVER['HTTP_REFERER'])) {
878 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
882 header('Location: '. $location);
886 // -------- User wants to see only private bookmarks (toggle)
887 if (isset($_GET['visibility'])) {
888 if ($_GET['visibility'] === 'private') {
889 // Visibility not set or not already private, set private, otherwise reset it
890 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
891 // See only private bookmarks
892 $_SESSION['visibility'] = 'private';
894 unset($_SESSION['visibility']);
896 } elseif ($_GET['visibility'] === 'public') {
897 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
898 // See only public bookmarks
899 $_SESSION['visibility'] = 'public';
901 unset($_SESSION['visibility']);
905 if (! empty($_SERVER['HTTP_REFERER'])) {
906 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
910 header('Location: '. $location);
914 // -------- User wants to see only untagged bookmarks (toggle)
915 if (isset($_GET['untaggedonly'])) {
916 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
918 if (! empty($_SERVER['HTTP_REFERER'])) {
919 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
923 header('Location: '. $location);
927 // -------- Handle other actions allowed for non-logged in users:
928 if (!$loginManager->isLoggedIn()) {
929 // User tries to post new link but is not logged in:
930 // Show login screen, then redirect to ?post=...
931 if (isset($_GET['post'])) {
932 header( // Redirect to login page, then back to post link.
933 'Location: ?do=login&post='.urlencode($_GET['post']).
934 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
935 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
936 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
937 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
942 showLinkList($PAGE, $bookmarkService, $conf, $pluginManager, $loginManager);
943 if (isset($_GET['edit_link'])) {
944 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
948 exit; // Never remove this one! All operations below are reserved for logged in user.
951 // -------- All other functions are reserved for the registered user:
953 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
954 if ($targetPage == Router
::$PAGE_TOOLS) {
956 'pageabsaddr' => index_url($_SERVER),
957 'sslenabled' => is_https($_SERVER),
959 $pluginManager->executeHooks('render_tools', $data);
961 foreach ($data as $key => $value) {
962 $PAGE->assign($key, $value);
965 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
966 $PAGE->renderPage('tools');
970 // -------- User wants to change his/her password.
971 if ($targetPage == Router
::$PAGE_CHANGEPASSWORD) {
972 if ($conf->get('security.open_shaarli')) {
973 die(t('You are not supposed to change a password on an Open Shaarli.'));
976 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) {
977 if (!$sessionManager->checkToken($_POST['token'])) {
978 die(t('Wrong token.')); // Go away!
981 // Make sure old password is correct.
983 $_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt')
985 if ($oldhash != $conf->get('credentials.hash')) {
986 echo '<script>alert("'
987 . t('The old password is not correct.')
988 .'");document.location=\'?do=changepasswd\';</script>';
992 // Salt renders rainbow-tables attacks useless.
993 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
997 $_POST['setpassword']
998 . $conf->get('credentials.login')
999 . $conf->get('credentials.salt')
1003 $conf->write($loginManager->isLoggedIn());
1004 } catch (Exception
$e) {
1006 'ERROR while writing config file after changing password.' . PHP_EOL
.
1010 // TODO: do not handle exceptions/errors in JS.
1011 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
1014 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
1017 // show the change password form.
1018 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
1019 $PAGE->renderPage('changepassword');
1024 // -------- User wants to change configuration
1025 if ($targetPage == Router
::$PAGE_CONFIGURE) {
1026 if (!empty($_POST['title'])) {
1027 if (!$sessionManager->checkToken($_POST['token'])) {
1028 die(t('Wrong token.')); // Go away!
1031 if (!empty($_POST['continent']) && !empty($_POST['city'])
1032 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1034 $tz = $_POST['continent'] . '/' . $_POST['city'];
1036 $conf->set('general.timezone', $tz);
1037 $conf->set('general.title', escape($_POST['title']));
1038 $conf->set('general.header_link', escape($_POST['titleLink']));
1039 $conf->set('general.retrieve_description', !empty($_POST['retrieveDescription']));
1040 $conf->set('resource.theme', escape($_POST['theme']));
1041 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
1042 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
1043 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1044 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1045 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
1046 $conf->set('api.enabled', !empty($_POST['enableApi']));
1047 $conf->set('api.secret', escape($_POST['apiSecret']));
1048 $conf->set('formatter', escape($_POST['formatter']));
1050 if (! empty($_POST['language'])) {
1051 $conf->set('translation.language', escape($_POST['language']));
1054 $thumbnailsMode = extension_loaded('gd') ? $_POST['enableThumbnails'] : Thumbnailer
::MODE_NONE
;
1055 if ($thumbnailsMode !== Thumbnailer
::MODE_NONE
1056 && $thumbnailsMode !== $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
)
1058 $_SESSION['warnings'][] = t(
1059 'You have enabled or changed thumbnails mode. '
1060 .'<a href="?do=thumbs_update">Please synchronize them</a>.'
1063 $conf->set('thumbnails.mode', $thumbnailsMode);
1066 $conf->write($loginManager->isLoggedIn());
1067 $history->updateSettings();
1068 invalidateCaches($conf->get('resource.page_cache'));
1069 } catch (Exception
$e) {
1071 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1075 // TODO: do not handle exceptions/errors in JS.
1076 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1079 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1082 // Show the configuration form.
1083 $PAGE->assign('title', $conf->get('general.title'));
1084 $PAGE->assign('theme', $conf->get('resource.theme'));
1085 $PAGE->assign('theme_available', ThemeUtils
::getThemes($conf->get('resource.raintpl_tpl')));
1086 $PAGE->assign('formatter_available', ['default', 'markdown']);
1087 list($continents, $cities) = generateTimeZoneData(
1088 timezone_identifiers_list(),
1089 $conf->get('general.timezone')
1091 $PAGE->assign('continents', $continents);
1092 $PAGE->assign('cities', $cities);
1093 $PAGE->assign('retrieve_description', $conf->get('general.retrieve_description'));
1094 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
1095 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1096 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1097 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1098 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1099 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1100 $PAGE->assign('api_secret', $conf->get('api.secret'));
1101 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1102 $PAGE->assign('gd_enabled', extension_loaded('gd'));
1103 $PAGE->assign('thumbnails_mode', $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
));
1104 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
1105 $PAGE->renderPage('configure');
1110 // -------- User wants to rename a tag or delete it
1111 if ($targetPage == Router
::$PAGE_CHANGETAG) {
1112 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1113 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1114 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
1115 $PAGE->renderPage('changetag');
1119 if (!$sessionManager->checkToken($_POST['token'])) {
1120 die(t('Wrong token.'));
1123 $toTag = isset($_POST['totag']) ? escape($_POST['totag']) : null;
1124 $fromTag = escape($_POST['fromtag']);
1126 $bookmarks = $bookmarkService->search(['searchtags' => $fromTag], BookmarkFilter
::$ALL, true);
1127 foreach ($bookmarks as $bookmark) {
1129 $bookmark->renameTag($fromTag, $toTag);
1131 $bookmark->deleteTag($fromTag);
1133 $bookmarkService->set($bookmark, false);
1134 $history->updateLink($bookmark);
1137 $bookmarkService->save();
1138 $delete = empty($_POST['totag']);
1139 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1141 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d bookmarks.', $count), $count)
1142 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d bookmarks.', $count), $count);
1143 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1147 // -------- User wants to add a link without using the bookmarklet: Show form.
1148 if ($targetPage == Router
::$PAGE_ADDLINK) {
1149 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1150 $PAGE->renderPage('addlink');
1154 // -------- User clicked the "Save" button when editing a link: Save link to database.
1155 if (isset($_POST['save_edit'])) {
1157 if (! $sessionManager->checkToken($_POST['token'])) {
1158 die(t('Wrong token.'));
1161 // lf_id should only be present if the link exists.
1162 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : null;
1163 if ($id && $bookmarkService->exists($id)) {
1165 $bookmark = $bookmarkService->get($id);
1168 $bookmark = new Bookmark();
1171 $bookmark->setTitle($_POST['lf_title']);
1172 $bookmark->setDescription($_POST['lf_description']);
1173 $bookmark->setUrl($_POST['lf_url'], $conf->get('security.allowed_protocols'));
1174 $bookmark->setPrivate(isset($_POST['lf_private']));
1175 $bookmark->setTagsString($_POST['lf_tags']);
1177 if ($conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
) !== Thumbnailer
::MODE_NONE
1178 && ! $bookmark->isNote()
1180 $thumbnailer = new Thumbnailer($conf);
1181 $bookmark->setThumbnail($thumbnailer->get($bookmark->getUrl()));
1183 $bookmarkService->addOrSet($bookmark, false);
1185 // To preserve backward compatibility with 3rd parties, plugins still use arrays
1186 $factory = new FormatterFactory($conf);
1187 $formatter = $factory->getFormatter('raw');
1188 $data = $formatter->format($bookmark);
1189 $pluginManager->executeHooks('save_link', $data);
1191 $bookmark->fromArray($data);
1192 $bookmarkService->set($bookmark);
1194 // If we are called from the bookmarklet, we must close the popup:
1195 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1196 echo '<script>self.close();</script>';
1200 $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?';
1201 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1202 // Scroll to the link which has been edited.
1203 $location .= '#' . $bookmark->getShortUrl();
1204 // After saving the link, redirect to the page the user was on.
1205 header('Location: '. $location);
1209 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1210 if ($targetPage == Router
::$PAGE_DELETELINK) {
1211 if (! $sessionManager->checkToken($_GET['token'])) {
1212 die(t('Wrong token.'));
1215 $ids = trim($_GET['lf_linkdate']);
1216 if (strpos($ids, ' ') !== false) {
1217 // multiple, space-separated ids provided
1218 $ids = array_values(array_filter(
1219 preg_split('/\s+/', escape($ids)),
1221 return $item !== '';
1225 // only a single id provided
1226 $shortUrl = $bookmarkService->get($ids)->getShortUrl();
1229 // assert at least one id is given
1231 die('no id provided');
1233 $factory = new FormatterFactory($conf);
1234 $formatter = $factory->getFormatter('raw');
1235 foreach ($ids as $id) {
1236 $id = (int) escape($id);
1237 $bookmark = $bookmarkService->get($id);
1238 $data = $formatter->format($bookmark);
1239 $pluginManager->executeHooks('delete_link', $data);
1240 $bookmarkService->remove($bookmark, false);
1242 $bookmarkService->save();
1244 // If we are called from the bookmarklet, we must close the popup:
1245 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1246 echo '<script>self.close();</script>';
1251 if (isset($_SERVER['HTTP_REFERER'])) {
1252 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1253 $location = generateLocation(
1254 $_SERVER['HTTP_REFERER'],
1255 $_SERVER['HTTP_HOST'],
1256 ['delete_link', 'edit_link', ! empty($shortUrl) ? $shortUrl : null]
1260 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1264 // -------- User clicked either "Set public" or "Set private" bulk operation
1265 if ($targetPage == Router
::$PAGE_CHANGE_VISIBILITY) {
1266 if (! $sessionManager->checkToken($_GET['token'])) {
1267 die(t('Wrong token.'));
1270 $ids = trim($_GET['ids']);
1271 if (strpos($ids, ' ') !== false) {
1272 // multiple, space-separated ids provided
1273 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1275 // only a single id provided
1279 // assert at least one id is given
1281 die('no id provided');
1283 // assert that the visibility is valid
1284 if (!isset($_GET['newVisibility']) || !in_array($_GET['newVisibility'], ['public', 'private'])) {
1285 die('invalid visibility');
1287 $private = $_GET['newVisibility'] === 'private';
1289 $factory = new FormatterFactory($conf);
1290 $formatter = $factory->getFormatter('raw');
1291 foreach ($ids as $id) {
1292 $id = (int) escape($id);
1293 $bookmark = $bookmarkService->get($id);
1294 $bookmark->setPrivate($private);
1296 // To preserve backward compatibility with 3rd parties, plugins still use arrays
1297 $data = $formatter->format($bookmark);
1298 $pluginManager->executeHooks('save_link', $data);
1299 $bookmark->fromArray($data);
1301 $bookmarkService->set($bookmark);
1303 $bookmarkService->save();
1306 if (isset($_SERVER['HTTP_REFERER'])) {
1307 $location = generateLocation(
1308 $_SERVER['HTTP_REFERER'],
1309 $_SERVER['HTTP_HOST']
1312 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1316 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1317 if (isset($_GET['edit_link'])) {
1318 $id = (int) escape($_GET['edit_link']);
1320 $link = $bookmarkService->get($id); // Read database
1321 } catch (BookmarkNotFoundException
$e) {
1322 // Link not found in database.
1323 header('Location: ?');
1327 $factory = new FormatterFactory($conf);
1328 $formatter = $factory->getFormatter('raw');
1329 $formattedLink = $formatter->format($link);
1331 'link' => $formattedLink,
1332 'link_is_new' => false,
1333 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1334 'tags' => $bookmarkService->bookmarksCountPerTag(),
1336 $pluginManager->executeHooks('render_editlink', $data);
1338 foreach ($data as $key => $value) {
1339 $PAGE->assign($key, $value);
1342 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1343 $PAGE->renderPage('editlink');
1347 // -------- User want to post a new link: Display link edit form.
1348 if (isset($_GET['post'])) {
1349 $url = cleanup_url($_GET['post']);
1351 $link_is_new = false;
1352 // Check if URL is not already in database (in this case, we will edit the existing link)
1353 $bookmark = $bookmarkService->findByUrl($url);
1355 $link_is_new = true;
1356 // Get title if it was provided in URL (by the bookmarklet).
1357 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1358 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1359 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1360 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1361 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1363 // If this is an HTTP(S) link, we try go get the page to extract
1364 // the title (otherwise we will to straight to the edit form.)
1365 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1366 $retrieveDescription = $conf->get('general.retrieve_description');
1367 // Short timeout to keep the application responsive
1368 // The callback will fill $charset and $title with data from the downloaded page.
1371 $conf->get('general.download_timeout', 30),
1372 $conf->get('general.download_max_size', 4194304),
1373 get_curl_download_callback($charset, $title, $description, $tags, $retrieveDescription)
1375 if (! empty($title) && strtolower($charset) != 'utf-8') {
1376 $title = mb_convert_encoding($title, 'utf-8', $charset);
1381 $title = $conf->get('general.default_note_title', t('Note: '));
1383 $url = escape($url);
1384 $title = escape($title);
1389 'description' => $description,
1391 'private' => $private,
1394 $factory = new FormatterFactory($conf);
1395 $formatter = $factory->getFormatter('raw');
1396 $link = $formatter->format($bookmark);
1401 'link_is_new' => $link_is_new,
1402 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1403 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1404 'tags' => $bookmarkService->bookmarksCountPerTag(),
1405 'default_private_links' => $conf->get('privacy.default_private_links', false),
1407 $pluginManager->executeHooks('render_editlink', $data);
1409 foreach ($data as $key => $value) {
1410 $PAGE->assign($key, $value);
1413 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1414 $PAGE->renderPage('editlink');
1418 if ($targetPage == Router
::$PAGE_PINLINK) {
1419 if (! isset($_GET['id']) || !$bookmarkService->exists($_GET['id'])) {
1420 // FIXME! Use a proper error system.
1421 $msg = t('Invalid link ID provided');
1422 echo '<script>alert("'. $msg .'");document.location=\''. index_url($_SERVER) .'\';</script>';
1425 if (! $sessionManager->checkToken($_GET['token'])) {
1426 die('Wrong token.');
1429 $link = $bookmarkService->get($_GET['id']);
1430 $link->setSticky(! $link->isSticky());
1431 $bookmarkService->set($link);
1432 header('Location: '.index_url($_SERVER));
1436 if ($targetPage == Router
::$PAGE_EXPORT) {
1437 // Export bookmarks as a Netscape Bookmarks file
1439 if (empty($_GET['selection'])) {
1440 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1441 $PAGE->renderPage('export');
1445 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1446 $selection = $_GET['selection'];
1447 if (isset($_GET['prepend_note_url'])) {
1448 $prependNoteUrl = $_GET['prepend_note_url'];
1450 $prependNoteUrl = false;
1454 $factory = new FormatterFactory($conf);
1455 $formatter = $factory->getFormatter('raw');
1458 NetscapeBookmarkUtils
::filterAndFormat(
1466 } catch (Exception
$exc) {
1467 header('Content-Type: text/plain; charset=utf-8');
1468 echo $exc->getMessage();
1471 $now = new DateTime();
1472 header('Content-Type: text/html; charset=utf-8');
1474 'Content-disposition: attachment; filename=bookmarks_'
1475 .$selection.'_'.$now->format(Bookmark
::LINK_DATE_FORMAT
).'.html'
1477 $PAGE->assign('date', $now->format(DateTime
::RFC822
));
1478 $PAGE->assign('eol', PHP_EOL
);
1479 $PAGE->assign('selection', $selection);
1480 $PAGE->renderPage('export.bookmarks');
1484 if ($targetPage == Router
::$PAGE_IMPORT) {
1485 // Upload a Netscape bookmark dump to import its contents
1487 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1488 // Show import dialog
1491 get_max_upload_size(
1492 ini_get('post_max_size'),
1493 ini_get('upload_max_filesize'),
1499 get_max_upload_size(
1500 ini_get('post_max_size'),
1501 ini_get('upload_max_filesize'),
1505 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1506 $PAGE->renderPage('import');
1510 // Import bookmarks from an uploaded file
1511 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1512 // The file is too big or some form field may be missing.
1515 'The file you are trying to upload is probably bigger than what this webserver can accept'
1516 .' (%s). Please upload in smaller chunks.'
1518 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1520 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router
::$PAGE_IMPORT .'\';</script>';
1523 if (! $sessionManager->checkToken($_POST['token'])) {
1524 die('Wrong token.');
1526 $status = NetscapeBookmarkUtils
::import(
1533 echo '<script>alert("'.$status.'");document.location=\'?do='
1534 .Router
::$PAGE_IMPORT .'\';</script>';
1538 // Plugin administration page
1539 if ($targetPage == Router
::$PAGE_PLUGINSADMIN) {
1540 $pluginMeta = $pluginManager->getPluginsMeta();
1542 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1543 $enabledPlugins = array_filter($pluginMeta, function ($v) {
1544 return $v['order'] !== false;
1547 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1551 return $a['order'] - $b['order'];
1554 $disabledPlugins = array_filter($pluginMeta, function ($v) {
1555 return $v['order'] === false;
1558 $PAGE->assign('enabledPlugins', $enabledPlugins);
1559 $PAGE->assign('disabledPlugins', $disabledPlugins);
1560 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
1561 $PAGE->renderPage('pluginsadmin');
1565 // Plugin administration form action
1566 if ($targetPage == Router
::$PAGE_SAVE_PLUGINSADMIN) {
1568 if (isset($_POST['parameters_form'])) {
1569 $pluginManager->executeHooks('save_plugin_parameters', $_POST);
1570 unset($_POST['parameters_form']);
1571 foreach ($_POST as $param => $value) {
1572 $conf->set('plugins.'. $param, escape($value));
1575 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1577 $conf->write($loginManager->isLoggedIn());
1578 $history->updateSettings();
1579 } catch (Exception
$e) {
1581 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1585 // TODO: do not handle exceptions/errors in JS.
1586 echo '<script>alert("'
1588 .'");document.location=\'?do='
1589 . Router
::$PAGE_PLUGINSADMIN
1593 header('Location: ?do='. Router
::$PAGE_PLUGINSADMIN);
1597 // Get a fresh token
1598 if ($targetPage == Router
::$GET_TOKEN) {
1599 header('Content-Type:text/plain');
1600 echo $sessionManager->generateToken();
1604 // -------- Thumbnails Update
1605 if ($targetPage == Router
::$PAGE_THUMBS_UPDATE) {
1607 foreach ($bookmarkService->search() as $bookmark) {
1608 // A note or not HTTP(S)
1609 if ($bookmark->isNote() || ! startsWith(strtolower($bookmark->getUrl()), 'http')) {
1612 $ids[] = $bookmark->getId();
1614 $PAGE->assign('ids', $ids);
1615 $PAGE->assign('pagetitle', t('Thumbnails update') .' - '. $conf->get('general.title', 'Shaarli'));
1616 $PAGE->renderPage('thumbnails');
1620 // -------- Single Thumbnail Update
1621 if ($targetPage == Router
::$AJAX_THUMB_UPDATE) {
1622 if (! isset($_POST['id']) || ! ctype_digit($_POST['id'])) {
1623 http_response_code(400);
1626 $id = (int) $_POST['id'];
1627 if (! $bookmarkService->exists($id)) {
1628 http_response_code(404);
1631 $thumbnailer = new Thumbnailer($conf);
1632 $bookmark = $bookmarkService->get($id);
1633 $bookmark->setThumbnail($thumbnailer->get($bookmark->getUrl()));
1634 $bookmarkService->set($bookmark);
1636 $factory = new FormatterFactory($conf);
1637 echo json_encode($factory->getFormatter('raw')->format($bookmark));
1641 // -------- Otherwise, simply display search form and bookmarks:
1642 showLinkList($PAGE, $bookmarkService, $conf, $pluginManager, $loginManager);
1647 * Template for the list of bookmarks (<div id="linklist">)
1648 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1650 * @param pageBuilder $PAGE pageBuilder instance.
1651 * @param BookmarkServiceInterface $linkDb LinkDB instance.
1652 * @param ConfigManager $conf Configuration Manager instance.
1653 * @param PluginManager $pluginManager Plugin Manager instance.
1654 * @param LoginManager $loginManager LoginManager instance
1656 function buildLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager)
1658 $factory = new FormatterFactory($conf);
1659 $formatter = $factory->getFormatter();
1661 // Used in templates
1662 if (isset($_GET['searchtags'])) {
1663 if (! empty($_GET['searchtags'])) {
1664 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1666 $searchtags = false;
1671 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1674 if (! empty($_SERVER['QUERY_STRING'])
1675 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1677 $linksToDisplay = $linkDb->findByHash($_SERVER['QUERY_STRING']);
1678 } catch (BookmarkNotFoundException
$e) {
1679 $PAGE->render404($e->getMessage());
1683 // Filter bookmarks according search parameters.
1684 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : null;
1686 'searchtags' => $searchtags,
1687 'searchterm' => $searchterm,
1689 $linksToDisplay = $linkDb->search($request, $visibility, false, !empty($_SESSION['untaggedonly']));
1692 // ---- Handle paging.
1694 foreach ($linksToDisplay as $key => $value) {
1698 // Select articles according to paging.
1699 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1700 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1701 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1702 $page = $page < 1 ? 1 : $page;
1703 $page = $page > $pagecount ? $pagecount : $page;
1705 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1706 $end = $i +
$_SESSION['LINKS_PER_PAGE'];
1708 $thumbnailsEnabled = $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
) !== Thumbnailer
::MODE_NONE
;
1709 if ($thumbnailsEnabled) {
1710 $thumbnailer = new Thumbnailer($conf);
1713 $linkDisp = array();
1714 while ($i<$end && $i<count($keys)) {
1715 $link = $formatter->format($linksToDisplay[$keys[$i]]);
1717 // Logged in, thumbnails enabled, not a note,
1718 // and (never retrieved yet or no valid cache file)
1719 if ($loginManager->isLoggedIn()
1720 && $thumbnailsEnabled
1721 && !$linksToDisplay[$keys[$i]]->isNote()
1722 && $linksToDisplay[$keys[$i]]->getThumbnail() !== false
1723 && ! is_file($linksToDisplay[$keys[$i]]->getThumbnail())
1725 $linksToDisplay[$keys[$i]]->setThumbnail($thumbnailer->get($link['url']));
1726 $linkDb->set($linksToDisplay[$keys[$i]], false);
1728 $link['thumbnail'] = $linksToDisplay[$keys[$i]]->getThumbnail();
1731 // Check for both signs of a note: starting with ? and 7 chars long.
1732 // if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
1733 // $link['url'] = index_url($_SERVER) . $link['url'];
1736 $linkDisp[$keys[$i]] = $link;
1740 // If we retrieved new thumbnails, we update the database.
1741 if (!empty($updateDB)) {
1745 // Compute paging navigation
1746 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
1747 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1748 $previous_page_url = '';
1749 if ($i != count($keys)) {
1750 $previous_page_url = '?page=' . ($page+
1) . $searchtermUrl . $searchtagsUrl;
1754 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1757 // Fill all template fields.
1759 'previous_page_url' => $previous_page_url,
1760 'next_page_url' => $next_page_url,
1761 'page_current' => $page,
1762 'page_max' => $pagecount,
1763 'result_count' => count($linksToDisplay),
1764 'search_term' => $searchterm,
1765 'search_tags' => $searchtags,
1766 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
1767 'links' => $linkDisp,
1770 // If there is only a single link, we change on-the-fly the title of the page.
1771 if (count($linksToDisplay) == 1) {
1772 $data['pagetitle'] = $linksToDisplay[$keys[0]]->getTitle() .' - '. $conf->get('general.title');
1773 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1774 $data['pagetitle'] = t('Search: ');
1775 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1776 $bracketWrap = function ($tag) {
1777 return '['. $tag .']';
1779 $data['pagetitle'] .= ! empty($searchtags)
1780 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1782 $data['pagetitle'] .= '- '. $conf->get('general.title');
1785 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
1787 foreach ($data as $key => $value) {
1788 $PAGE->assign($key, $value);
1796 * This function should NEVER be called if the file data/config.php exists.
1798 * @param ConfigManager $conf Configuration Manager instance.
1799 * @param SessionManager $sessionManager SessionManager instance
1800 * @param LoginManager $loginManager LoginManager instance
1802 function install($conf, $sessionManager, $loginManager)
1804 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1805 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
1806 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
1810 // This part makes sure sessions works correctly.
1811 // (Because on some hosts, session.save_path may not be set correctly,
1812 // or we may not have write access to it.)
1813 if (isset($_GET['test_session'])
1814 && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
1815 // Step 2: Check if data in session is correct.
1817 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1818 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1819 'and that you have write access to it.<br>'.
1820 'It currently points to %s.<br>'.
1821 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1822 'or any custom hostname without a dot causes cookie storage to fail. '.
1823 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1825 $msg = sprintf($msg, session_save_path());
1827 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1830 if (!isset($_SESSION['session_tested'])) {
1831 // Step 1 : Try to store data in session and reload page.
1832 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1833 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1835 if (isset($_GET['test_session'])) {
1836 // Step 3: Sessions are OK. Remove test parameter from URL.
1837 header('Location: '.index_url($_SERVER));
1841 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
1843 if (!empty($_POST['continent']) && !empty($_POST['city'])
1844 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1846 $tz = $_POST['continent'].'/'.$_POST['city'];
1848 $conf->set('general.timezone', $tz);
1849 $login = $_POST['setlogin'];
1850 $conf->set('credentials.login', $login);
1851 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1852 $conf->set('credentials.salt', $salt);
1853 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
1854 if (!empty($_POST['title'])) {
1855 $conf->set('general.title', escape($_POST['title']));
1857 $conf->set('general.title', 'Shared bookmarks on '.escape(index_url($_SERVER)));
1859 $conf->set('translation.language', escape($_POST['language']));
1860 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1861 $conf->set('api.enabled', !empty($_POST['enableApi']));
1864 generate_api_secret(
1865 $conf->get('credentials.login'),
1866 $conf->get('credentials.salt')
1870 // Everything is ok, let's create config file.
1871 $conf->write($loginManager->isLoggedIn());
1872 } catch (Exception
$e) {
1874 'ERROR while writing config file after installation.' . PHP_EOL
.
1878 // TODO: do not handle exceptions/errors in JS.
1879 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1883 $history = new History($conf->get('resource.history'));
1884 $bookmarkService = new BookmarkFileService($conf, $history, true);
1885 if ($bookmarkService->count() === 0) {
1886 $bookmarkService->initialize();
1889 echo '<script>alert('
1890 .'"Shaarli is now configured. '
1891 .'Please enter your login/password and start shaaring your bookmarks!"'
1892 .');document.location=\'?do=login\';</script>';
1896 $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
1897 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1898 $PAGE->assign('continents', $continents);
1899 $PAGE->assign('cities', $cities);
1900 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1901 $PAGE->renderPage('install');
1905 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
1906 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
1910 $history = new History($conf->get('resource.history'));
1911 } catch (Exception
$e) {
1912 die($e->getMessage());
1915 $linkDb = new BookmarkFileService($conf, $history, $loginManager->isLoggedIn());
1917 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) {
1918 showDailyRSS($linkDb, $conf, $loginManager);
1922 $container = new \Slim\
Container();
1923 $container['conf'] = $conf;
1924 $container['plugins'] = $pluginManager;
1925 $container['history'] = $history;
1926 $app = new \Slim\
App($container);
1929 $app->group('/api/v1', function () {
1930 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
1931 $this->get('/bookmarks', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
1932 $this->get('/bookmarks/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
1933 $this->post('/bookmarks', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
1934 $this->put('/bookmarks/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
1935 $this->delete('/bookmarks/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
1937 $this->get('/tags', '\Shaarli\Api\Controllers\Tags:getTags')->setName('getTags');
1938 $this->get('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:getTag')->setName('getTag');
1939 $this->put('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:putTag')->setName('putTag');
1940 $this->delete('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:deleteTag')->setName('deleteTag');
1942 $this->get('/history', '\Shaarli\Api\Controllers\HistoryController:getHistory')->setName('getHistory');
1943 })->add('\Shaarli\Api\ApiMiddleware');
1945 $response = $app->run(true);
1947 // Hack to make Slim and Shaarli router work together:
1948 // If a Slim route isn't found and NOT API call, we call renderPage().
1949 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
1950 // We use UTF-8 for proper international characters handling.
1951 header('Content-Type: text/html; charset=utf-8');
1952 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
1954 $response = $response
1955 ->withHeader('Access-Control-Allow-Origin', '*')
1957 'Access-Control-Allow-Headers',
1958 'X-Requested-With, Content-Type, Accept, Origin, Authorization'
1960 ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
1961 $app->respond($response);