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/ApplicationUtils.php';
66 require_once 'application/Cache.php';
67 require_once 'application/CachedPage.php';
68 require_once 'application/config/ConfigPlugin.php';
69 require_once 'application/FeedBuilder.php';
70 require_once 'application/FileUtils.php';
71 require_once 'application/History.php';
72 require_once 'application/HttpUtils.php';
73 require_once 'application/LinkDB.php';
74 require_once 'application/LinkFilter.php';
75 require_once 'application/LinkUtils.php';
76 require_once 'application/NetscapeBookmarkUtils.php';
77 require_once 'application/PageBuilder.php';
78 require_once 'application/TimeZone.php';
79 require_once 'application/Url.php';
80 require_once 'application/Utils.php';
81 require_once 'application/PluginManager.php';
82 require_once 'application/Router.php';
83 require_once 'application/Updater.php';
84 use \Shaarli\Config\ConfigManager
;
85 use \Shaarli\Languages
;
86 use \Shaarli\Security\LoginManager
;
87 use \Shaarli\Security\SessionManager
;
88 use \Shaarli\ThemeUtils
;
89 use \Shaarli\Thumbnailer
;
91 // Ensure the PHP version is supported
93 ApplicationUtils
::checkPHPVersion('5.5', PHP_VERSION
);
94 } catch (Exception
$exc) {
95 header('Content-Type: text/plain; charset=utf-8');
96 echo $exc->getMessage();
100 define('SHAARLI_VERSION', ApplicationUtils
::getVersion(__DIR__
.'/'. ApplicationUtils
::$VERSION_FILE));
102 // Force cookie path (but do not change lifetime)
103 $cookie = session_get_cookie_params();
105 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
106 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
108 // Set default cookie expiration and path.
109 session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
110 // Set session parameters on server side.
111 // Use cookies to store session.
112 ini_set('session.use_cookies', 1);
113 // Force cookies for session (phpsessionID forbidden in URL).
114 ini_set('session.use_only_cookies', 1);
115 // Prevent PHP form using sessionID in URL if cookies are disabled.
116 ini_set('session.use_trans_sid', false);
118 session_name('shaarli');
119 // Start session if needed (Some server auto-start sessions).
120 if (session_status() == PHP_SESSION_NONE
) {
124 // Regenerate session ID if invalid or not defined in cookie.
125 if (isset($_COOKIE['shaarli']) && !SessionManager
::checkId($_COOKIE['shaarli'])) {
126 session_regenerate_id(true);
127 $_COOKIE['shaarli'] = session_id();
130 $conf = new ConfigManager();
131 $sessionManager = new SessionManager($_SESSION, $conf);
132 $loginManager = new LoginManager($GLOBALS, $conf, $sessionManager);
133 $loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
134 $clientIpId = client_ip_id($_SERVER);
136 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
137 if (! defined('LC_MESSAGES')) {
138 define('LC_MESSAGES', LC_COLLATE
);
141 // Sniff browser language and set date format accordingly.
142 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
143 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
146 new Languages(setlocale(LC_MESSAGES
, 0), $conf);
148 $conf->setEmpty('general.timezone', date_default_timezone_get());
149 $conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
150 RainTPL
::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
151 RainTPL
::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
153 $pluginManager = new PluginManager($conf);
154 $pluginManager->load($conf->get('general.enabled_plugins'));
156 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
158 ob_start(); // Output buffering for the page cache.
160 // Prevent caching on client side or proxy: (yes, it's ugly)
161 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
162 header("Cache-Control: no-store, no-cache, must-revalidate");
163 header("Cache-Control: post-check=0, pre-check=0", false);
164 header("Pragma: no-cache");
166 if (! is_file($conf->getConfigFileExt())) {
167 // Ensure Shaarli has proper access to its resources
168 $errors = ApplicationUtils
::checkResourcePermissions($conf);
170 if ($errors != array()) {
171 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
173 foreach ($errors as $error) {
174 $message .= '<li>'.$error.'</li>';
178 header('Content-Type: text/html; charset=utf-8');
183 // Display the installation form if no existing config is found
184 install($conf, $sessionManager, $loginManager);
187 $loginManager->checkLoginState($_COOKIE, $clientIpId);
190 * Adapter function to ensure compatibility with third-party templates
192 * @see https://github.com/shaarli/Shaarli/pull/1086
194 * @return bool true when the user is logged in, false otherwise
196 function isLoggedIn()
198 global $loginManager;
199 return $loginManager->isLoggedIn();
203 // ------------------------------------------------------------------------------------------
204 // Process login form: Check if login/password is correct.
205 if (isset($_POST['login'])) {
206 if (! $loginManager->canLogin($_SERVER)) {
207 die(t('I said: NO. You are banned for the moment. Go away.'));
209 if (isset($_POST['password'])
210 && $sessionManager->checkToken($_POST['token'])
211 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
213 $loginManager->handleSuccessfulLogin($_SERVER);
216 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
217 // Note: Never forget the trailing slash on the cookie path!
218 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
221 if (!empty($_POST['longlastingsession'])) {
222 // Keep the session cookie even after the browser closes
223 $sessionManager->setStaySignedIn(true);
224 $expirationTime = $sessionManager->extendSession();
227 $loginManager::$STAY_SIGNED_IN_COOKIE,
228 $loginManager->getStaySignedInToken(),
233 // Standard session expiration (=when browser closes)
237 // Send cookie with the new expiration date to the browser
238 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
239 session_regenerate_id(true);
241 // Optional redirect after login:
242 if (isset($_GET['post'])) {
243 $uri = '?post='. urlencode($_GET['post']);
244 foreach (array('description', 'source', 'title', 'tags') as $param) {
245 if (!empty($_GET[$param])) {
246 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
249 header('Location: '. $uri);
253 if (isset($_GET['edit_link'])) {
254 header('Location: ?edit_link='. escape($_GET['edit_link']));
258 if (isset($_POST['returnurl'])) {
259 // Prevent loops over login screen.
260 if (strpos($_POST['returnurl'], 'do=login') === false) {
261 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
265 header('Location: ?');
268 $loginManager->handleFailedLogin($_SERVER);
269 $redir = '&username='. urlencode($_POST['login']);
270 if (isset($_GET['post'])) {
271 $redir .= '&post=' . urlencode($_GET['post']);
272 foreach (array('description', 'source', 'title', 'tags') as $param) {
273 if (!empty($_GET[$param])) {
274 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
278 // Redirect to login screen.
279 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
284 // ------------------------------------------------------------------------------------------
285 // Token management for XSRF protection
286 // Token should be used in any form which acts on data (create,update,delete,import...).
287 if (!isset($_SESSION['tokens'])) {
288 $_SESSION['tokens']=array(); // Token are attached to the session.
292 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
293 * Gives the last 7 days (which have links).
294 * This RSS feed cannot be filtered.
296 * @param ConfigManager $conf Configuration Manager instance
297 * @param LoginManager $loginManager LoginManager instance
299 function showDailyRSS($conf, $loginManager)
302 $query = $_SERVER['QUERY_STRING'];
303 $cache = new CachedPage(
304 $conf->get('config.PAGE_CACHE'),
306 startsWith($query, 'do=dailyrss') && !$loginManager->isLoggedIn()
308 $cached = $cache->cachedVersion();
309 if (!empty($cached)) {
314 // If cached was not found (or not usable), then read the database and build the response:
315 // Read links from database (and filter private links if used it not logged in).
316 $LINKSDB = new LinkDB(
317 $conf->get('resource.datastore'),
318 $loginManager->isLoggedIn(),
319 $conf->get('privacy.hide_public_links'),
320 $conf->get('redirector.url'),
321 $conf->get('redirector.encode_url')
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(
364 $link['description'],
365 $conf->get('redirector.url'),
366 $conf->get('redirector.encode_url')
368 $link['timestamp'] = $link['created']->getTimestamp();
369 if (startsWith($link['url'], '?')) {
370 $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
374 // Then build the HTML for this day:
376 $tpl->assign('title', $conf->get('general.title'));
377 $tpl->assign('daydate', $dayDate->getTimestamp());
378 $tpl->assign('absurl', $absurl);
379 $tpl->assign('links', $links);
380 $tpl->assign('rssdate', escape($dayDate->format(DateTime
::RSS
)));
381 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
382 $tpl->assign('index_url', $pageaddr);
383 $html = $tpl->draw('dailyrss', true);
385 echo $html . PHP_EOL
;
387 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
389 $cache->cache(ob_get_contents());
395 * Show the 'Daily' page.
397 * @param PageBuilder $pageBuilder Template engine wrapper.
398 * @param LinkDB $LINKSDB LinkDB instance.
399 * @param ConfigManager $conf Configuration Manager instance.
400 * @param PluginManager $pluginManager Plugin Manager instance.
401 * @param LoginManager $loginManager Login Manager instance
403 function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
405 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
406 if (isset($_GET['day'])) {
410 $days = $LINKSDB->days();
411 $i = array_search($day, $days);
412 if ($i === false && count($days)) {
413 // no links for day, but at least one day with links
414 $i = count($days) - 1;
422 $previousday=$days[$i - 1];
424 if ($i < count($days) - 1) {
425 $nextday = $days[$i +
1];
429 $linksToDisplay = $LINKSDB->filterDay($day);
430 } catch (Exception
$exc) {
432 $linksToDisplay = array();
435 // We pre-format some fields for proper output.
436 foreach ($linksToDisplay as $key => $link) {
437 $taglist = explode(' ', $link['tags']);
438 uasort($taglist, 'strcasecmp');
439 $linksToDisplay[$key]['taglist']=$taglist;
440 $linksToDisplay[$key]['formatedDescription'] = format_description(
441 $link['description'],
442 $conf->get('redirector.url'),
443 $conf->get('redirector.encode_url')
445 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
448 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
450 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
451 'linksToDisplay' => $linksToDisplay,
452 'day' => $dayDate->getTimestamp(),
453 'dayDate' => $dayDate,
454 'previousday' => $previousday,
455 'nextday' => $nextday,
458 /* Hook is called before column construction so that plugins don't have
459 to deal with columns. */
460 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
462 /* We need to spread the articles on 3 columns.
463 I did not want to use a JavaScript lib like http://masonry.desandro.com/
464 so I manually spread entries with a simple method: I roughly evaluate the
465 height of a div according to title and description length.
467 $columns = array(array(), array(), array()); // Entries to display, for each column.
468 $fill = array(0, 0, 0); // Rough estimate of columns fill.
469 foreach ($data['linksToDisplay'] as $key => $link) {
470 // Roughly estimate length of entry (by counting characters)
471 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
472 // Description: 836 characters gives roughly 342 pixel height.
473 // This is not perfect, but it's usually OK.
474 $length = strlen($link['title']) +
(342 * strlen($link['description'])) / 836;
475 if ($link['thumbnail']) {
476 $length +
= 100; // 1 thumbnails roughly takes 100 pixels height.
478 // Then put in column which is the less filled:
479 $smallest = min($fill); // find smallest value in array.
480 $index = array_search($smallest, $fill); // find index of this smallest value.
481 array_push($columns[$index], $link); // Put entry in this column.
482 $fill[$index] +
= $length;
485 $data['cols'] = $columns;
487 foreach ($data as $key => $value) {
488 $pageBuilder->assign($key, $value);
491 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
492 $pageBuilder->renderPage('daily');
497 * Renders the linklist
499 * @param pageBuilder $PAGE pageBuilder instance.
500 * @param LinkDB $LINKSDB LinkDB instance.
501 * @param ConfigManager $conf Configuration Manager instance.
502 * @param PluginManager $pluginManager Plugin Manager instance.
504 function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
506 buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
507 $PAGE->renderPage('linklist');
511 * Render HTML page (according to URL parameters and user rights)
513 * @param ConfigManager $conf Configuration Manager instance.
514 * @param PluginManager $pluginManager Plugin Manager instance,
515 * @param LinkDB $LINKSDB
516 * @param History $history instance
517 * @param SessionManager $sessionManager SessionManager instance
518 * @param LoginManager $loginManager LoginManager instance
520 function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
522 $updater = new Updater(
523 read_updates_file($conf->get('resource.updates')),
526 $loginManager->isLoggedIn(),
530 $newUpdates = $updater->update();
531 if (! empty($newUpdates)) {
533 $conf->get('resource.updates'),
534 $updater->getDoneUpdates()
537 } catch (Exception
$e) {
538 die($e->getMessage());
541 $PAGE = new PageBuilder($conf, $_SESSION, $LINKSDB, $sessionManager->generateToken(), $loginManager->isLoggedIn());
542 $PAGE->assign('linkcount', count($LINKSDB));
543 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
544 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
546 // Determine which page will be rendered.
547 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
548 $targetPage = Router
::findPage($query, $_GET, $loginManager->isLoggedIn());
550 if (// if the user isn't logged in
551 !$loginManager->isLoggedIn() &&
552 // and Shaarli doesn't have public content...
553 $conf->get('privacy.hide_public_links') &&
554 // and is configured to enforce the login
555 $conf->get('privacy.force_login') &&
556 // and the current page isn't already the login page
557 $targetPage !== Router
::$PAGE_LOGIN &&
558 // and the user is not requesting a feed (which would lead to a different content-type as expected)
559 $targetPage !== Router
::$PAGE_FEED_ATOM &&
560 $targetPage !== Router
::$PAGE_FEED_RSS
562 // force current page to be the login page
563 $targetPage = Router
::$PAGE_LOGIN;
566 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
567 // Then assign generated data to RainTPL.
568 $common_hooks = array(
574 foreach ($common_hooks as $name) {
575 $plugin_data = array();
576 $pluginManager->executeHooks(
580 'target' => $targetPage,
581 'loggedin' => $loginManager->isLoggedIn()
584 $PAGE->assign('plugins_' . $name, $plugin_data);
587 // -------- Display login form.
588 if ($targetPage == Router
::$PAGE_LOGIN) {
589 if ($conf->get('security.open_shaarli')) {
590 header('Location: ?');
592 } // No need to login for open Shaarli
593 if (isset($_GET['username'])) {
594 $PAGE->assign('username', escape($_GET['username']));
596 $PAGE->assign('returnurl', (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
597 // add default state of the 'remember me' checkbox
598 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
599 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
600 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
601 $PAGE->renderPage('loginform');
604 // -------- User wants to logout.
605 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) {
606 invalidateCaches($conf->get('resource.page_cache'));
607 $sessionManager->logout();
608 setcookie(LoginManager
::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH
);
609 header('Location: ?');
613 // -------- Picture wall
614 if ($targetPage == Router
::$PAGE_PICWALL) {
615 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
616 if (! $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
) === Thumbnailer
::MODE_NONE
) {
617 $PAGE->assign('linksToDisplay', []);
618 $PAGE->renderPage('picwall');
622 // Optionally filter the results:
623 $links = $LINKSDB->filterSearch($_GET);
624 $linksToDisplay = array();
626 // Get only links which have a thumbnail.
627 // Note: we do not retrieve thumbnails here, the request is too heavy.
628 foreach ($links as $key => $link) {
629 if (isset($link['thumbnail']) && $link['thumbnail'] !== false) {
630 $linksToDisplay[] = $link; // Add to array.
635 'linksToDisplay' => $linksToDisplay,
637 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => $loginManager->isLoggedIn()));
639 foreach ($data as $key => $value) {
640 $PAGE->assign($key, $value);
644 $PAGE->renderPage('picwall');
648 // -------- Tag cloud
649 if ($targetPage == Router
::$PAGE_TAGCLOUD) {
650 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
651 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
652 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
654 // We sort tags alphabetically, then choose a font size according to count.
655 // First, find max value.
657 foreach ($tags as $value) {
658 $maxcount = max($maxcount, $value);
661 alphabetical_sort($tags, false, true);
664 foreach ($tags as $key => $value) {
665 if (in_array($key, $filteringTags)) {
668 // Tag font size scaling:
669 // default 15 and 30 logarithm bases affect scaling,
670 // 22 and 6 are arbitrary font sizes for max and min sizes.
671 $size = log($value, 15) / log($maxcount, 30) * 2.2 +
0.8;
672 $tagList[$key] = array(
674 'size' => number_format($size, 2, '.', ''),
678 $searchTags = implode(' ', escape($filteringTags));
680 'search_tags' => $searchTags,
683 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
685 foreach ($data as $key => $value) {
686 $PAGE->assign($key, $value);
689 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
690 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
691 $PAGE->renderPage('tag.cloud');
696 if ($targetPage == Router
::$PAGE_TAGLIST) {
697 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
698 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
699 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
700 foreach ($filteringTags as $tag) {
701 if (array_key_exists($tag, $tags)) {
706 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
707 alphabetical_sort($tags, false, true);
710 $searchTags = implode(' ', escape($filteringTags));
712 'search_tags' => $searchTags,
715 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
717 foreach ($data as $key => $value) {
718 $PAGE->assign($key, $value);
721 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
722 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
723 $PAGE->renderPage('tag.list');
728 if ($targetPage == Router
::$PAGE_DAILY) {
729 showDaily($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
732 // ATOM and RSS feed.
733 if ($targetPage == Router
::$PAGE_FEED_ATOM || $targetPage == Router
::$PAGE_FEED_RSS) {
734 $feedType = $targetPage == Router
::$PAGE_FEED_RSS ? FeedBuilder
::$FEED_RSS : FeedBuilder
::$FEED_ATOM;
735 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
738 $query = $_SERVER['QUERY_STRING'];
739 $cache = new CachedPage(
740 $conf->get('resource.page_cache'),
742 startsWith($query, 'do='. $targetPage) && !$loginManager->isLoggedIn()
744 $cached = $cache->cachedVersion();
745 if (!empty($cached)) {
751 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, $loginManager->isLoggedIn());
752 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE
, 0)));
753 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
754 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
755 $data = $feedGenerator->buildData();
757 // Process plugin hook.
758 $pluginManager->executeHooks('render_feed', $data, array(
759 'loggedin' => $loginManager->isLoggedIn(),
760 'target' => $targetPage,
763 // Render the template.
764 $PAGE->assignAll($data);
765 $PAGE->renderPage('feed.'. $feedType);
766 $cache->cache(ob_get_contents());
771 // Display opensearch plugin (XML)
772 if ($targetPage == Router
::$PAGE_OPENSEARCH) {
773 header('Content-Type: application/xml; charset=utf-8');
774 $PAGE->assign('serverurl', index_url($_SERVER));
775 $PAGE->renderPage('opensearch');
779 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
780 if (isset($_GET['addtag'])) {
781 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
782 if (empty($_SERVER['HTTP_REFERER'])) {
783 // In case browser does not send HTTP_REFERER
784 header('Location: ?searchtags='.urlencode($_GET['addtag']));
787 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
789 // Prevent redirection loop
790 if (isset($params['addtag'])) {
791 unset($params['addtag']);
794 // Check if this tag is already in the search query and ignore it if it is.
795 // Each tag is always separated by a space
796 if (isset($params['searchtags'])) {
797 $current_tags = explode(' ', $params['searchtags']);
799 $current_tags = array();
802 foreach ($current_tags as $value) {
803 if ($value === $_GET['addtag']) {
808 // Append the tag if necessary
809 if (empty($params['searchtags'])) {
810 $params['searchtags'] = trim($_GET['addtag']);
812 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
815 // We also remove page (keeping the same page has no sense, since the
816 // results are different)
817 unset($params['page']);
819 header('Location: ?'.http_build_query($params));
823 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
824 if (isset($_GET['removetag'])) {
825 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
826 if (empty($_SERVER['HTTP_REFERER'])) {
827 header('Location: ?');
831 // In case browser does not send HTTP_REFERER
832 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
834 // Prevent redirection loop
835 if (isset($params['removetag'])) {
836 unset($params['removetag']);
839 if (isset($params['searchtags'])) {
840 $tags = explode(' ', $params['searchtags']);
841 // Remove value from array $tags.
842 $tags = array_diff($tags, array($_GET['removetag']));
843 $params['searchtags'] = implode(' ', $tags);
845 if (empty($params['searchtags'])) {
846 unset($params['searchtags']);
849 // We also remove page (keeping the same page has no sense, since
850 // the results are different)
851 unset($params['page']);
853 header('Location: ?'.http_build_query($params));
857 // -------- User wants to change the number of links per page (linksperpage=...)
858 if (isset($_GET['linksperpage'])) {
859 if (is_numeric($_GET['linksperpage'])) {
860 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
863 if (! empty($_SERVER['HTTP_REFERER'])) {
864 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
868 header('Location: '. $location);
872 // -------- User wants to see only private links (toggle)
873 if (isset($_GET['visibility'])) {
874 if ($_GET['visibility'] === 'private') {
875 // Visibility not set or not already private, set private, otherwise reset it
876 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
877 // See only private links
878 $_SESSION['visibility'] = 'private';
880 unset($_SESSION['visibility']);
882 } elseif ($_GET['visibility'] === 'public') {
883 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
884 // See only public links
885 $_SESSION['visibility'] = 'public';
887 unset($_SESSION['visibility']);
891 if (! empty($_SERVER['HTTP_REFERER'])) {
892 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
896 header('Location: '. $location);
900 // -------- User wants to see only untagged links (toggle)
901 if (isset($_GET['untaggedonly'])) {
902 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
904 if (! empty($_SERVER['HTTP_REFERER'])) {
905 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
909 header('Location: '. $location);
913 // -------- Handle other actions allowed for non-logged in users:
914 if (!$loginManager->isLoggedIn()) {
915 // User tries to post new link but is not logged in:
916 // Show login screen, then redirect to ?post=...
917 if (isset($_GET['post'])) {
918 header( // Redirect to login page, then back to post link.
919 'Location: ?do=login&post='.urlencode($_GET['post']).
920 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
921 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
922 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
923 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
928 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
929 if (isset($_GET['edit_link'])) {
930 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
934 exit; // Never remove this one! All operations below are reserved for logged in user.
937 // -------- All other functions are reserved for the registered user:
939 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
940 if ($targetPage == Router
::$PAGE_TOOLS) {
942 'pageabsaddr' => index_url($_SERVER),
943 'sslenabled' => is_https($_SERVER),
945 $pluginManager->executeHooks('render_tools', $data);
947 foreach ($data as $key => $value) {
948 $PAGE->assign($key, $value);
951 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
952 $PAGE->renderPage('tools');
956 // -------- User wants to change his/her password.
957 if ($targetPage == Router
::$PAGE_CHANGEPASSWORD) {
958 if ($conf->get('security.open_shaarli')) {
959 die(t('You are not supposed to change a password on an Open Shaarli.'));
962 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) {
963 if (!$sessionManager->checkToken($_POST['token'])) {
964 die(t('Wrong token.')); // Go away!
967 // Make sure old password is correct.
969 $_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt')
971 if ($oldhash != $conf->get('credentials.hash')) {
972 echo '<script>alert("'
973 . t('The old password is not correct.')
974 .'");document.location=\'?do=changepasswd\';</script>';
978 // Salt renders rainbow-tables attacks useless.
979 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
983 $_POST['setpassword']
984 . $conf->get('credentials.login')
985 . $conf->get('credentials.salt')
989 $conf->write($loginManager->isLoggedIn());
990 } catch (Exception
$e) {
992 'ERROR while writing config file after changing password.' . PHP_EOL
.
996 // TODO: do not handle exceptions/errors in JS.
997 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
1000 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
1003 // show the change password form.
1004 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
1005 $PAGE->renderPage('changepassword');
1010 // -------- User wants to change configuration
1011 if ($targetPage == Router
::$PAGE_CONFIGURE) {
1012 if (!empty($_POST['title'])) {
1013 if (!$sessionManager->checkToken($_POST['token'])) {
1014 die(t('Wrong token.')); // Go away!
1017 if (!empty($_POST['continent']) && !empty($_POST['city'])
1018 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1020 $tz = $_POST['continent'] . '/' . $_POST['city'];
1022 $conf->set('general.timezone', $tz);
1023 $conf->set('general.title', escape($_POST['title']));
1024 $conf->set('general.header_link', escape($_POST['titleLink']));
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('private_links_default', $conf->get('privacy.default_private_links', false));
1074 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1075 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1076 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1077 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1078 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1079 $PAGE->assign('api_secret', $conf->get('api.secret'));
1080 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1081 $PAGE->assign('language', $conf->get('translation.language'));
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();
1135 // Linkdate is kept here to:
1136 // - use the same permalink for notes as they're displayed when creating them
1137 // - let users hack creation date of their posts
1138 // See: https://shaarli.readthedocs.io/en/master/guides/various-hacks/#changing-the-timestamp-for-a-shaare
1139 $linkdate = escape($_POST['lf_linkdate']);
1140 if (isset($LINKSDB[$id])) {
1142 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1143 $updated = new DateTime();
1144 $shortUrl = $LINKSDB[$id]['shorturl'];
1148 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1150 $shortUrl = link_small_hash($created, $id);
1154 // Remove multiple spaces.
1155 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
1156 // Remove first '-' char in tags.
1157 $tags = preg_replace('/(^| )\-/', '$1', $tags);
1158 // Remove duplicates.
1159 $tags = implode(' ', array_unique(explode(' ', $tags)));
1161 if (empty(trim($_POST['lf_url
']))) {
1162 $_POST['lf_url
'] = '?' . smallHash($linkdate . $id);
1164 $url = whitelist_protocols(trim($_POST['lf_url
']), $conf->get('security
.allowed_protocols
'));
1168 'title
' => trim($_POST['lf_title
']),
1170 'description
' => $_POST['lf_description
'],
1171 'private' => (isset($_POST['lf_private
']) ? 1 : 0),
1172 'created
' => $created,
1173 'updated
' => $updated,
1174 'tags
' => str_replace(',', ' ', $tags),
1175 'shorturl
' => $shortUrl,
1178 // If title is empty, use the URL as title.
1179 if ($link['title
'] == '') {
1180 $link['title
'] = $link['url
'];
1183 if ($conf->get('thumbnails
.mode
', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE) {
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 the "EDIT" button on a link: Display link edit form.
1283 if (isset($_GET['edit_link'])) {
1284 $id = (int) escape($_GET['edit_link']);
1285 $link = $LINKSDB[$id]; // Read database
1287 header('Location: ?');
1289 } // Link not found in database.
1290 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1293 'link_is_new' => false,
1294 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1295 'tags' => $LINKSDB->linksCountPerTag(),
1297 $pluginManager->executeHooks('render_editlink', $data);
1299 foreach ($data as $key => $value) {
1300 $PAGE->assign($key, $value);
1303 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1304 $PAGE->renderPage('editlink');
1308 // -------- User want to post a new link: Display link edit form.
1309 if (isset($_GET['post'])) {
1310 $url = cleanup_url($_GET['post']);
1312 $link_is_new = false;
1313 // Check if URL is not already in database (in this case, we will edit the existing link)
1314 $link = $LINKSDB->getLinkFromUrl($url);
1316 $link_is_new = true;
1317 $linkdate = strval(date(LinkDB
::LINK_DATE_FORMAT
));
1318 // Get title if it was provided in URL (by the bookmarklet).
1319 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1320 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1321 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1322 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1323 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1325 // If this is an HTTP(S) link, we try go get the page to extract
1326 // the title (otherwise we will to straight to the edit form.)
1327 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1328 // Short timeout to keep the application responsive
1329 // The callback will fill $charset and $title with data from the downloaded page.
1332 $conf->get('general.download_timeout', 30),
1333 $conf->get('general.download_max_size', 4194304),
1334 get_curl_download_callback($charset, $title)
1336 if (! empty($title) && strtolower($charset) != 'utf-8') {
1337 $title = mb_convert_encoding($title, 'utf-8', $charset);
1342 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1343 $title = $conf->get('general.default_note_title', t('Note: '));
1345 $url = escape($url);
1346 $title = escape($title);
1349 'linkdate' => $linkdate,
1352 'description' => $description,
1354 'private' => $private,
1357 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1362 'link_is_new' => $link_is_new,
1363 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1364 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1365 'tags' => $LINKSDB->linksCountPerTag(),
1366 'default_private_links' => $conf->get('privacy.default_private_links', false),
1368 $pluginManager->executeHooks('render_editlink', $data);
1370 foreach ($data as $key => $value) {
1371 $PAGE->assign($key, $value);
1374 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1375 $PAGE->renderPage('editlink');
1379 if ($targetPage == Router
::$PAGE_PINLINK) {
1380 if (! isset($_GET['id']) || empty($LINKSDB[$_GET['id']])) {
1381 // FIXME! Use a proper error system.
1382 $msg = t('Invalid link ID provided');
1383 echo '<script>alert("'. $msg .'");document.location=\''. index_url($_SERVER) .'\';</script>';
1386 if (! $sessionManager->checkToken($_GET['token'])) {
1387 die('Wrong token.');
1390 $link = $LINKSDB[$_GET['id']];
1391 $link['sticky'] = ! $link['sticky'];
1392 $LINKSDB[(int) $_GET['id']] = $link;
1393 $LINKSDB->save($conf->get('resource.page_cache'));
1394 header('Location: '.index_url($_SERVER));
1398 if ($targetPage == Router
::$PAGE_EXPORT) {
1399 // Export links as a Netscape Bookmarks file
1401 if (empty($_GET['selection'])) {
1402 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1403 $PAGE->renderPage('export');
1407 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1408 $selection = $_GET['selection'];
1409 if (isset($_GET['prepend_note_url'])) {
1410 $prependNoteUrl = $_GET['prepend_note_url'];
1412 $prependNoteUrl = false;
1418 NetscapeBookmarkUtils
::filterAndFormat(
1425 } catch (Exception
$exc) {
1426 header('Content-Type: text/plain; charset=utf-8');
1427 echo $exc->getMessage();
1430 $now = new DateTime();
1431 header('Content-Type: text/html; charset=utf-8');
1433 'Content-disposition: attachment; filename=bookmarks_'
1434 .$selection.'_'.$now->format(LinkDB
::LINK_DATE_FORMAT
).'.html'
1436 $PAGE->assign('date', $now->format(DateTime
::RFC822
));
1437 $PAGE->assign('eol', PHP_EOL
);
1438 $PAGE->assign('selection', $selection);
1439 $PAGE->renderPage('export.bookmarks');
1443 if ($targetPage == Router
::$PAGE_IMPORT) {
1444 // Upload a Netscape bookmark dump to import its contents
1446 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1447 // Show import dialog
1450 get_max_upload_size(
1451 ini_get('post_max_size'),
1452 ini_get('upload_max_filesize'),
1458 get_max_upload_size(
1459 ini_get('post_max_size'),
1460 ini_get('upload_max_filesize'),
1464 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1465 $PAGE->renderPage('import');
1469 // Import bookmarks from an uploaded file
1470 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1471 // The file is too big or some form field may be missing.
1474 'The file you are trying to upload is probably bigger than what this webserver can accept'
1475 .' (%s). Please upload in smaller chunks.'
1477 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1479 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router
::$PAGE_IMPORT .'\';</script>';
1482 if (! $sessionManager->checkToken($_POST['token'])) {
1483 die('Wrong token.');
1485 $status = NetscapeBookmarkUtils
::import(
1492 echo '<script>alert("'.$status.'");document.location=\'?do='
1493 .Router
::$PAGE_IMPORT .'\';</script>';
1497 // Plugin administration page
1498 if ($targetPage == Router
::$PAGE_PLUGINSADMIN) {
1499 $pluginMeta = $pluginManager->getPluginsMeta();
1501 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1502 $enabledPlugins = array_filter($pluginMeta, function ($v) {
1503 return $v['order'] !== false;
1506 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1510 return $a['order'] - $b['order'];
1513 $disabledPlugins = array_filter($pluginMeta, function ($v) {
1514 return $v['order'] === false;
1517 $PAGE->assign('enabledPlugins', $enabledPlugins);
1518 $PAGE->assign('disabledPlugins', $disabledPlugins);
1519 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
1520 $PAGE->renderPage('pluginsadmin');
1524 // Plugin administration form action
1525 if ($targetPage == Router
::$PAGE_SAVE_PLUGINSADMIN) {
1527 if (isset($_POST['parameters_form'])) {
1528 unset($_POST['parameters_form']);
1529 foreach ($_POST as $param => $value) {
1530 $conf->set('plugins.'. $param, escape($value));
1533 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1535 $conf->write($loginManager->isLoggedIn());
1536 $history->updateSettings();
1537 } catch (Exception
$e) {
1539 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1543 // TODO: do not handle exceptions/errors in JS.
1544 echo '<script>alert("'
1546 .'");document.location=\'?do='
1547 . Router
::$PAGE_PLUGINSADMIN
1551 header('Location: ?do='. Router
::$PAGE_PLUGINSADMIN);
1555 // Get a fresh token
1556 if ($targetPage == Router
::$GET_TOKEN) {
1557 header('Content-Type:text/plain');
1558 echo $sessionManager->generateToken($conf);
1562 // -------- Thumbnails Update
1563 if ($targetPage == Router
::$PAGE_THUMBS_UPDATE) {
1565 foreach ($LINKSDB as $link) {
1566 // A note or not HTTP(S)
1567 if ($link['url'][0] === '?' || ! startsWith(strtolower($link['url']), 'http')) {
1570 $ids[] = $link['id'];
1572 $PAGE->assign('ids', $ids);
1573 $PAGE->assign('pagetitle', t('Thumbnails update') .' - '. $conf->get('general.title', 'Shaarli'));
1574 $PAGE->renderPage('thumbnails');
1578 // -------- Single Thumbnail Update
1579 if ($targetPage == Router
::$AJAX_THUMB_UPDATE) {
1580 if (! isset($_POST['id']) || ! ctype_digit($_POST['id'])) {
1581 http_response_code(400);
1584 $id = (int) $_POST['id'];
1585 if (empty($LINKSDB[$id])) {
1586 http_response_code(404);
1589 $thumbnailer = new Thumbnailer($conf);
1590 $link = $LINKSDB[$id];
1591 $link['thumbnail'] = $thumbnailer->get($link['url']);
1592 $LINKSDB[$id] = $link;
1593 $LINKSDB->save($conf->get('resource.page_cache'));
1595 echo json_encode($link);
1599 // -------- Otherwise, simply display search form and links:
1600 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
1605 * Template for the list of links (<div id="linklist">)
1606 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1608 * @param pageBuilder $PAGE pageBuilder instance.
1609 * @param LinkDB $LINKSDB LinkDB instance.
1610 * @param ConfigManager $conf Configuration Manager instance.
1611 * @param PluginManager $pluginManager Plugin Manager instance.
1612 * @param LoginManager $loginManager LoginManager instance
1614 function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1616 // Used in templates
1617 if (isset($_GET['searchtags'])) {
1618 if (! empty($_GET['searchtags'])) {
1619 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1621 $searchtags = false;
1626 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1629 if (! empty($_SERVER['QUERY_STRING'])
1630 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1632 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1633 } catch (LinkNotFoundException
$e) {
1634 $PAGE->render404($e->getMessage());
1638 // Filter links according search parameters.
1639 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
1641 'searchtags' => $searchtags,
1642 'searchterm' => $searchterm,
1644 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
1647 // ---- Handle paging.
1649 foreach ($linksToDisplay as $key => $value) {
1653 // Select articles according to paging.
1654 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1655 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1656 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1657 $page = $page < 1 ? 1 : $page;
1658 $page = $page > $pagecount ? $pagecount : $page;
1660 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1661 $end = $i +
$_SESSION['LINKS_PER_PAGE'];
1663 $thumbnailsEnabled = $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
) !== Thumbnailer
::MODE_NONE
;
1664 if ($thumbnailsEnabled) {
1665 $thumbnailer = new Thumbnailer($conf);
1668 $linkDisp = array();
1669 while ($i<$end && $i<count($keys)) {
1670 $link = $linksToDisplay[$keys[$i]];
1671 $link['description'] = format_description(
1672 $link['description'],
1673 $conf->get('redirector.url'),
1674 $conf->get('redirector.encode_url')
1676 $classLi = ($i %
2) != 0 ? '' : 'publicLinkHightLight';
1677 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
1678 $link['timestamp'] = $link['created']->getTimestamp();
1679 if (! empty($link['updated'])) {
1680 $link['updated_timestamp'] = $link['updated']->getTimestamp();
1682 $link['updated_timestamp'] = '';
1684 $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY
);
1685 uasort($taglist, 'strcasecmp');
1686 $link['taglist'] = $taglist;
1688 // Logged in, thumbnails enabled, not a note,
1689 // and (never retrieved yet or no valid cache file)
1690 if ($loginManager->isLoggedIn() && $thumbnailsEnabled && $link['url'][0] != '?'
1691 && (! isset($link['thumbnail']) || ($link['thumbnail'] !== false && ! is_file($link['thumbnail'])))
1693 $elem = $LINKSDB[$keys[$i]];
1694 $elem['thumbnail'] = $thumbnailer->get($link['url']);
1695 $LINKSDB[$keys[$i]] = $elem;
1697 $link['thumbnail'] = $elem['thumbnail'];
1700 // Check for both signs of a note: starting with ? and 7 chars long.
1701 if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
1702 $link['url'] = index_url($_SERVER) . $link['url'];
1705 $linkDisp[$keys[$i]] = $link;
1709 // If we retrieved new thumbnails, we update the database.
1710 if (!empty($updateDB)) {
1711 $LINKSDB->save($conf->get('resource.page_cache'));
1714 // Compute paging navigation
1715 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
1716 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1717 $previous_page_url = '';
1718 if ($i != count($keys)) {
1719 $previous_page_url = '?page=' . ($page+
1) . $searchtermUrl . $searchtagsUrl;
1723 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1726 // Fill all template fields.
1728 'previous_page_url' => $previous_page_url,
1729 'next_page_url' => $next_page_url,
1730 'page_current' => $page,
1731 'page_max' => $pagecount,
1732 'result_count' => count($linksToDisplay),
1733 'search_term' => $searchterm,
1734 'search_tags' => $searchtags,
1735 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
1736 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
1737 'links' => $linkDisp,
1740 // If there is only a single link, we change on-the-fly the title of the page.
1741 if (count($linksToDisplay) == 1) {
1742 $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
1743 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1744 $data['pagetitle'] = t('Search: ');
1745 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1746 $bracketWrap = function ($tag) {
1747 return '['. $tag .']';
1749 $data['pagetitle'] .= ! empty($searchtags)
1750 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1752 $data['pagetitle'] .= '- '. $conf->get('general.title');
1755 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
1757 foreach ($data as $key => $value) {
1758 $PAGE->assign($key, $value);
1766 * This function should NEVER be called if the file data/config.php exists.
1768 * @param ConfigManager $conf Configuration Manager instance.
1769 * @param SessionManager $sessionManager SessionManager instance
1770 * @param LoginManager $loginManager LoginManager instance
1772 function install($conf, $sessionManager, $loginManager)
1774 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1775 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
1776 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
1780 // This part makes sure sessions works correctly.
1781 // (Because on some hosts, session.save_path may not be set correctly,
1782 // or we may not have write access to it.)
1783 if (isset($_GET['test_session'])
1784 && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
1785 // Step 2: Check if data in session is correct.
1787 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1788 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1789 'and that you have write access to it.<br>'.
1790 'It currently points to %s.<br>'.
1791 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1792 'or any custom hostname without a dot causes cookie storage to fail. '.
1793 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1795 $msg = sprintf($msg, session_save_path());
1797 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1800 if (!isset($_SESSION['session_tested'])) {
1801 // Step 1 : Try to store data in session and reload page.
1802 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1803 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1805 if (isset($_GET['test_session'])) {
1806 // Step 3: Sessions are OK. Remove test parameter from URL.
1807 header('Location: '.index_url($_SERVER));
1811 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
1813 if (!empty($_POST['continent']) && !empty($_POST['city'])
1814 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1816 $tz = $_POST['continent'].'/'.$_POST['city'];
1818 $conf->set('general.timezone', $tz);
1819 $login = $_POST['setlogin'];
1820 $conf->set('credentials.login', $login);
1821 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1822 $conf->set('credentials.salt', $salt);
1823 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
1824 if (!empty($_POST['title'])) {
1825 $conf->set('general.title', escape($_POST['title']));
1827 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
1829 $conf->set('translation.language', escape($_POST['language']));
1830 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1831 $conf->set('api.enabled', !empty($_POST['enableApi']));
1834 generate_api_secret(
1835 $conf->get('credentials.login'),
1836 $conf->get('credentials.salt')
1840 // Everything is ok, let's create config file.
1841 $conf->write($loginManager->isLoggedIn());
1842 } catch (Exception
$e) {
1844 'ERROR while writing config file after installation.' . PHP_EOL
.
1848 // TODO: do not handle exceptions/errors in JS.
1849 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1852 echo '<script>alert('
1853 .'"Shaarli is now configured. '
1854 .'Please enter your login/password and start shaaring your links!"'
1855 .');document.location=\'?do=login\';</script>';
1859 $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
1860 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1861 $PAGE->assign('continents', $continents);
1862 $PAGE->assign('cities', $cities);
1863 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1864 $PAGE->renderPage('install');
1868 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) {
1869 showDailyRSS($conf, $loginManager);
1873 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
1874 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
1878 $history = new History($conf->get('resource.history'));
1879 } catch (Exception
$e) {
1880 die($e->getMessage());
1883 $linkDb = new LinkDB(
1884 $conf->get('resource.datastore'),
1885 $loginManager->isLoggedIn(),
1886 $conf->get('privacy.hide_public_links'),
1887 $conf->get('redirector.url'),
1888 $conf->get('redirector.encode_url')
1891 $container = new \Slim\
Container();
1892 $container['conf'] = $conf;
1893 $container['plugins'] = $pluginManager;
1894 $container['history'] = $history;
1895 $app = new \Slim\
App($container);
1898 $app->group('/api/v1', function () {
1899 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
1900 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
1901 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
1902 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
1903 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
1904 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
1906 $this->get('/tags', '\Shaarli\Api\Controllers\Tags:getTags')->setName('getTags');
1907 $this->get('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:getTag')->setName('getTag');
1908 $this->put('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:putTag')->setName('putTag');
1909 $this->delete('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:deleteTag')->setName('deleteTag');
1911 $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
1912 })->add('\Shaarli\Api\ApiMiddleware');
1914 $response = $app->run(true);
1916 // Hack to make Slim and Shaarli router work together:
1917 // If a Slim route isn't found and NOT API call, we call renderPage().
1918 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
1919 // We use UTF-8 for proper international characters handling.
1920 header('Content-Type: text/html; charset=utf-8');
1921 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
1923 $response = $response
1924 ->withHeader('Access-Control-Allow-Origin', '*')
1926 'Access-Control-Allow-Headers',
1927 'X-Requested-With, Content-Type, Accept, Origin, Authorization'
1929 ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
1930 $app->respond($response);