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
17 // Set 'UTC' as the default timezone if it is not defined in php.ini
18 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
19 if (date_default_timezone_get() == '') {
20 date_default_timezone_set('UTC');
27 // http://server.com/x/shaarli --> /shaarli/
28 define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+
strrpos($_SERVER['REQUEST_URI'], '/', 0)));
30 // High execution time in case of problematic imports/exports.
31 ini_set('max_input_time', '60');
33 // Try to set max upload file size and read
34 ini_set('memory_limit', '128M');
35 ini_set('post_max_size', '16M');
36 ini_set('upload_max_filesize', '16M');
38 // See all error except warnings
39 error_reporting(E_ALL^E_WARNING
);
40 // See all errors (for debugging only)
41 //error_reporting(-1);
44 // 3rd-party libraries
45 if (! file_exists(__DIR__
. '/vendor/autoload.php')) {
46 header('Content-Type: text/plain; charset=utf-8');
47 echo "Error: missing Composer configuration\n\n"
48 ."If you installed Shaarli through Git or using the development branch,\n"
49 ."please refer to the installation documentation to install PHP"
50 ." dependencies using Composer:\n"
51 ."- https://shaarli.readthedocs.io/en/master/Server-configuration/\n"
52 ."- https://shaarli.readthedocs.io/en/master/Download-and-Installation/";
55 require_once 'inc/rain.tpl.class.php';
56 require_once __DIR__
. '/vendor/autoload.php';
59 require_once 'application/ApplicationUtils.php';
60 require_once 'application/bookmark/LinkUtils.php';
61 require_once 'application/config/ConfigPlugin.php';
62 require_once 'application/feed/Cache.php';
63 require_once 'application/http/HttpUtils.php';
64 require_once 'application/http/UrlUtils.php';
65 require_once 'application/updater/UpdaterUtils.php';
66 require_once 'application/FileUtils.php';
67 require_once 'application/History.php';
68 require_once 'application/NetscapeBookmarkUtils.php';
69 require_once 'application/TimeZone.php';
70 require_once 'application/Utils.php';
71 require_once 'application/PluginManager.php';
72 require_once 'application/Router.php';
74 use \Shaarli\Bookmark\Exception\LinkNotFoundException
;
75 use \Shaarli\Bookmark\LinkDB
;
76 use \Shaarli\Config\ConfigManager
;
77 use \Shaarli\Feed\CachedPage
;
78 use \Shaarli\Feed\FeedBuilder
;
80 use \Shaarli\Languages
;
81 use \Shaarli\Render\PageBuilder
;
82 use \Shaarli\Render\ThemeUtils
;
83 use \Shaarli\Security\LoginManager
;
84 use \Shaarli\Security\SessionManager
;
85 use \Shaarli\Thumbnailer
;
86 use Shaarli\Updater\Updater
;
88 // Ensure the PHP version is supported
90 ApplicationUtils
::checkPHPVersion('5.5', PHP_VERSION
);
91 } catch (Exception
$exc) {
92 header('Content-Type: text/plain; charset=utf-8');
93 echo $exc->getMessage();
97 define('SHAARLI_VERSION', ApplicationUtils
::getVersion(__DIR__
.'/'. ApplicationUtils
::$VERSION_FILE));
99 // Force cookie path (but do not change lifetime)
100 $cookie = session_get_cookie_params();
102 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
103 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
105 // Set default cookie expiration and path.
106 session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
107 // Set session parameters on server side.
108 // Use cookies to store session.
109 ini_set('session.use_cookies', 1);
110 // Force cookies for session (phpsessionID forbidden in URL).
111 ini_set('session.use_only_cookies', 1);
112 // Prevent PHP form using sessionID in URL if cookies are disabled.
113 ini_set('session.use_trans_sid', false);
115 session_name('shaarli');
116 // Start session if needed (Some server auto-start sessions).
117 if (session_status() == PHP_SESSION_NONE
) {
121 // Regenerate session ID if invalid or not defined in cookie.
122 if (isset($_COOKIE['shaarli']) && !SessionManager
::checkId($_COOKIE['shaarli'])) {
123 session_regenerate_id(true);
124 $_COOKIE['shaarli'] = session_id();
127 $conf = new ConfigManager();
128 $sessionManager = new SessionManager($_SESSION, $conf);
129 $loginManager = new LoginManager($GLOBALS, $conf, $sessionManager);
130 $loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
131 $clientIpId = client_ip_id($_SERVER);
133 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
134 if (! defined('LC_MESSAGES')) {
135 define('LC_MESSAGES', LC_COLLATE
);
138 // Sniff browser language and set date format accordingly.
139 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
140 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
143 new Languages(setlocale(LC_MESSAGES
, 0), $conf);
145 $conf->setEmpty('general.timezone', date_default_timezone_get());
146 $conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
147 RainTPL
::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
148 RainTPL
::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
150 $pluginManager = new PluginManager($conf);
151 $pluginManager->load($conf->get('general.enabled_plugins'));
153 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
155 ob_start(); // Output buffering for the page cache.
157 // Prevent caching on client side or proxy: (yes, it's ugly)
158 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
159 header("Cache-Control: no-store, no-cache, must-revalidate");
160 header("Cache-Control: post-check=0, pre-check=0", false);
161 header("Pragma: no-cache");
163 if (! is_file($conf->getConfigFileExt())) {
164 // Ensure Shaarli has proper access to its resources
165 $errors = ApplicationUtils
::checkResourcePermissions($conf);
167 if ($errors != array()) {
168 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
170 foreach ($errors as $error) {
171 $message .= '<li>'.$error.'</li>';
175 header('Content-Type: text/html; charset=utf-8');
180 // Display the installation form if no existing config is found
181 install($conf, $sessionManager, $loginManager);
184 $loginManager->checkLoginState($_COOKIE, $clientIpId);
187 * Adapter function to ensure compatibility with third-party templates
189 * @see https://github.com/shaarli/Shaarli/pull/1086
191 * @return bool true when the user is logged in, false otherwise
193 function isLoggedIn()
195 global $loginManager;
196 return $loginManager->isLoggedIn();
200 // ------------------------------------------------------------------------------------------
201 // Process login form: Check if login/password is correct.
202 if (isset($_POST['login'])) {
203 if (! $loginManager->canLogin($_SERVER)) {
204 die(t('I said: NO. You are banned for the moment. Go away.'));
206 if (isset($_POST['password'])
207 && $sessionManager->checkToken($_POST['token'])
208 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
210 $loginManager->handleSuccessfulLogin($_SERVER);
213 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
214 // Note: Never forget the trailing slash on the cookie path!
215 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
218 if (!empty($_POST['longlastingsession'])) {
219 // Keep the session cookie even after the browser closes
220 $sessionManager->setStaySignedIn(true);
221 $expirationTime = $sessionManager->extendSession();
224 $loginManager::$STAY_SIGNED_IN_COOKIE,
225 $loginManager->getStaySignedInToken(),
230 // Standard session expiration (=when browser closes)
234 // Send cookie with the new expiration date to the browser
235 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
236 session_regenerate_id(true);
238 // Optional redirect after login:
239 if (isset($_GET['post'])) {
240 $uri = '?post='. urlencode($_GET['post']);
241 foreach (array('description', 'source', 'title', 'tags') as $param) {
242 if (!empty($_GET[$param])) {
243 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
246 header('Location: '. $uri);
250 if (isset($_GET['edit_link'])) {
251 header('Location: ?edit_link='. escape($_GET['edit_link']));
255 if (isset($_POST['returnurl'])) {
256 // Prevent loops over login screen.
257 if (strpos($_POST['returnurl'], 'do=login') === false) {
258 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
262 header('Location: ?');
265 $loginManager->handleFailedLogin($_SERVER);
266 $redir = '&username='. urlencode($_POST['login']);
267 if (isset($_GET['post'])) {
268 $redir .= '&post=' . urlencode($_GET['post']);
269 foreach (array('description', 'source', 'title', 'tags') as $param) {
270 if (!empty($_GET[$param])) {
271 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
275 // Redirect to login screen.
276 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
281 // ------------------------------------------------------------------------------------------
282 // Token management for XSRF protection
283 // Token should be used in any form which acts on data (create,update,delete,import...).
284 if (!isset($_SESSION['tokens'])) {
285 $_SESSION['tokens']=array(); // Token are attached to the session.
289 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
290 * Gives the last 7 days (which have links).
291 * This RSS feed cannot be filtered.
293 * @param ConfigManager $conf Configuration Manager instance
294 * @param LoginManager $loginManager LoginManager instance
296 function showDailyRSS($conf, $loginManager)
299 $query = $_SERVER['QUERY_STRING'];
300 $cache = new CachedPage(
301 $conf->get('config.PAGE_CACHE'),
303 startsWith($query, 'do=dailyrss') && !$loginManager->isLoggedIn()
305 $cached = $cache->cachedVersion();
306 if (!empty($cached)) {
311 // If cached was not found (or not usable), then read the database and build the response:
312 // Read links from database (and filter private links if used it not logged in).
313 $LINKSDB = new LinkDB(
314 $conf->get('resource.datastore'),
315 $loginManager->isLoggedIn(),
316 $conf->get('privacy.hide_public_links'),
317 $conf->get('redirector.url'),
318 $conf->get('redirector.encode_url')
321 /* Some Shaarlies may have very few links, so we need to look
322 back in time until we have enough days ($nb_of_days).
324 $nb_of_days = 7; // We take 7 days.
325 $today = date('Ymd');
328 foreach ($LINKSDB as $link) {
329 $day = $link['created']->format('Ymd'); // Extract day (without time)
330 if (strcmp($day, $today) < 0) {
331 if (empty($days[$day])) {
332 $days[$day] = array();
334 $days[$day][] = $link;
337 if (count($days) > $nb_of_days) {
338 break; // Have we collected enough days?
342 // Build the RSS feed.
343 header('Content-Type: application/rss+xml; charset=utf-8');
344 $pageaddr = escape(index_url($_SERVER));
345 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
347 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
348 echo '<link>'. $pageaddr .'</link>';
349 echo '<description>Daily shared links</description>';
350 echo '<language>en-en</language>';
351 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL
;
354 foreach ($days as $day => $links) {
355 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
356 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
358 // We pre-format some fields for proper output.
359 foreach ($links as &$link) {
360 $link['formatedDescription'] = format_description(
361 $link['description'],
362 $conf->get('redirector.url'),
363 $conf->get('redirector.encode_url')
365 $link['timestamp'] = $link['created']->getTimestamp();
366 if (startsWith($link['url'], '?')) {
367 $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
371 // Then build the HTML for this day:
373 $tpl->assign('title', $conf->get('general.title'));
374 $tpl->assign('daydate', $dayDate->getTimestamp());
375 $tpl->assign('absurl', $absurl);
376 $tpl->assign('links', $links);
377 $tpl->assign('rssdate', escape($dayDate->format(DateTime
::RSS
)));
378 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
379 $tpl->assign('index_url', $pageaddr);
380 $html = $tpl->draw('dailyrss', true);
382 echo $html . PHP_EOL
;
384 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
386 $cache->cache(ob_get_contents());
392 * Show the 'Daily' page.
394 * @param PageBuilder $pageBuilder Template engine wrapper.
395 * @param LinkDB $LINKSDB LinkDB instance.
396 * @param ConfigManager $conf Configuration Manager instance.
397 * @param PluginManager $pluginManager Plugin Manager instance.
398 * @param LoginManager $loginManager Login Manager instance
400 function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
402 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
403 if (isset($_GET['day'])) {
407 $days = $LINKSDB->days();
408 $i = array_search($day, $days);
409 if ($i === false && count($days)) {
410 // no links for day, but at least one day with links
411 $i = count($days) - 1;
419 $previousday=$days[$i - 1];
421 if ($i < count($days) - 1) {
422 $nextday = $days[$i +
1];
426 $linksToDisplay = $LINKSDB->filterDay($day);
427 } catch (Exception
$exc) {
429 $linksToDisplay = array();
432 // We pre-format some fields for proper output.
433 foreach ($linksToDisplay as $key => $link) {
434 $taglist = explode(' ', $link['tags']);
435 uasort($taglist, 'strcasecmp');
436 $linksToDisplay[$key]['taglist']=$taglist;
437 $linksToDisplay[$key]['formatedDescription'] = format_description(
438 $link['description'],
439 $conf->get('redirector.url'),
440 $conf->get('redirector.encode_url')
442 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
445 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
447 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
448 'linksToDisplay' => $linksToDisplay,
449 'day' => $dayDate->getTimestamp(),
450 'dayDate' => $dayDate,
451 'previousday' => $previousday,
452 'nextday' => $nextday,
455 /* Hook is called before column construction so that plugins don't have
456 to deal with columns. */
457 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
459 /* We need to spread the articles on 3 columns.
460 I did not want to use a JavaScript lib like http://masonry.desandro.com/
461 so I manually spread entries with a simple method: I roughly evaluate the
462 height of a div according to title and description length.
464 $columns = array(array(), array(), array()); // Entries to display, for each column.
465 $fill = array(0, 0, 0); // Rough estimate of columns fill.
466 foreach ($data['linksToDisplay'] as $key => $link) {
467 // Roughly estimate length of entry (by counting characters)
468 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
469 // Description: 836 characters gives roughly 342 pixel height.
470 // This is not perfect, but it's usually OK.
471 $length = strlen($link['title']) +
(342 * strlen($link['description'])) / 836;
472 if ($link['thumbnail']) {
473 $length +
= 100; // 1 thumbnails roughly takes 100 pixels height.
475 // Then put in column which is the less filled:
476 $smallest = min($fill); // find smallest value in array.
477 $index = array_search($smallest, $fill); // find index of this smallest value.
478 array_push($columns[$index], $link); // Put entry in this column.
479 $fill[$index] +
= $length;
482 $data['cols'] = $columns;
484 foreach ($data as $key => $value) {
485 $pageBuilder->assign($key, $value);
488 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
489 $pageBuilder->renderPage('daily');
494 * Renders the linklist
496 * @param pageBuilder $PAGE pageBuilder instance.
497 * @param LinkDB $LINKSDB LinkDB instance.
498 * @param ConfigManager $conf Configuration Manager instance.
499 * @param PluginManager $pluginManager Plugin Manager instance.
501 function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
503 buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
504 $PAGE->renderPage('linklist');
508 * Render HTML page (according to URL parameters and user rights)
510 * @param ConfigManager $conf Configuration Manager instance.
511 * @param PluginManager $pluginManager Plugin Manager instance,
512 * @param LinkDB $LINKSDB
513 * @param History $history instance
514 * @param SessionManager $sessionManager SessionManager instance
515 * @param LoginManager $loginManager LoginManager instance
517 function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
519 $updater = new Updater(
520 read_updates_file($conf->get('resource.updates')),
523 $loginManager->isLoggedIn(),
527 $newUpdates = $updater->update();
528 if (! empty($newUpdates)) {
530 $conf->get('resource.updates'),
531 $updater->getDoneUpdates()
534 } catch (Exception
$e) {
535 die($e->getMessage());
538 $PAGE = new PageBuilder($conf, $_SESSION, $LINKSDB, $sessionManager->generateToken(), $loginManager->isLoggedIn());
539 $PAGE->assign('linkcount', count($LINKSDB));
540 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
541 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
543 // Determine which page will be rendered.
544 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
545 $targetPage = Router
::findPage($query, $_GET, $loginManager->isLoggedIn());
547 if (// if the user isn't logged in
548 !$loginManager->isLoggedIn() &&
549 // and Shaarli doesn't have public content...
550 $conf->get('privacy.hide_public_links') &&
551 // and is configured to enforce the login
552 $conf->get('privacy.force_login') &&
553 // and the current page isn't already the login page
554 $targetPage !== Router
::$PAGE_LOGIN &&
555 // and the user is not requesting a feed (which would lead to a different content-type as expected)
556 $targetPage !== Router
::$PAGE_FEED_ATOM &&
557 $targetPage !== Router
::$PAGE_FEED_RSS
559 // force current page to be the login page
560 $targetPage = Router
::$PAGE_LOGIN;
563 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
564 // Then assign generated data to RainTPL.
565 $common_hooks = array(
571 foreach ($common_hooks as $name) {
572 $plugin_data = array();
573 $pluginManager->executeHooks(
577 'target' => $targetPage,
578 'loggedin' => $loginManager->isLoggedIn()
581 $PAGE->assign('plugins_' . $name, $plugin_data);
584 // -------- Display login form.
585 if ($targetPage == Router
::$PAGE_LOGIN) {
586 if ($conf->get('security.open_shaarli')) {
587 header('Location: ?');
589 } // No need to login for open Shaarli
590 if (isset($_GET['username'])) {
591 $PAGE->assign('username', escape($_GET['username']));
593 $PAGE->assign('returnurl', (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
594 // add default state of the 'remember me' checkbox
595 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
596 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
597 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
598 $PAGE->renderPage('loginform');
601 // -------- User wants to logout.
602 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) {
603 invalidateCaches($conf->get('resource.page_cache'));
604 $sessionManager->logout();
605 setcookie(LoginManager
::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH
);
606 header('Location: ?');
610 // -------- Picture wall
611 if ($targetPage == Router
::$PAGE_PICWALL) {
612 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
613 if (! $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
) === Thumbnailer
::MODE_NONE
) {
614 $PAGE->assign('linksToDisplay', []);
615 $PAGE->renderPage('picwall');
619 // Optionally filter the results:
620 $links = $LINKSDB->filterSearch($_GET);
621 $linksToDisplay = array();
623 // Get only links which have a thumbnail.
624 // Note: we do not retrieve thumbnails here, the request is too heavy.
625 foreach ($links as $key => $link) {
626 if (isset($link['thumbnail']) && $link['thumbnail'] !== false) {
627 $linksToDisplay[] = $link; // Add to array.
632 'linksToDisplay' => $linksToDisplay,
634 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => $loginManager->isLoggedIn()));
636 foreach ($data as $key => $value) {
637 $PAGE->assign($key, $value);
641 $PAGE->renderPage('picwall');
645 // -------- Tag cloud
646 if ($targetPage == Router
::$PAGE_TAGCLOUD) {
647 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
648 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
649 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
651 // We sort tags alphabetically, then choose a font size according to count.
652 // First, find max value.
654 foreach ($tags as $value) {
655 $maxcount = max($maxcount, $value);
658 alphabetical_sort($tags, false, true);
661 foreach ($tags as $key => $value) {
662 if (in_array($key, $filteringTags)) {
665 // Tag font size scaling:
666 // default 15 and 30 logarithm bases affect scaling,
667 // 22 and 6 are arbitrary font sizes for max and min sizes.
668 $size = log($value, 15) / log($maxcount, 30) * 2.2 +
0.8;
669 $tagList[$key] = array(
671 'size' => number_format($size, 2, '.', ''),
675 $searchTags = implode(' ', escape($filteringTags));
677 'search_tags' => $searchTags,
680 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
682 foreach ($data as $key => $value) {
683 $PAGE->assign($key, $value);
686 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
687 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
688 $PAGE->renderPage('tag.cloud');
693 if ($targetPage == Router
::$PAGE_TAGLIST) {
694 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
695 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
696 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
697 foreach ($filteringTags as $tag) {
698 if (array_key_exists($tag, $tags)) {
703 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
704 alphabetical_sort($tags, false, true);
707 $searchTags = implode(' ', escape($filteringTags));
709 'search_tags' => $searchTags,
712 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
714 foreach ($data as $key => $value) {
715 $PAGE->assign($key, $value);
718 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
719 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
720 $PAGE->renderPage('tag.list');
725 if ($targetPage == Router
::$PAGE_DAILY) {
726 showDaily($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
729 // ATOM and RSS feed.
730 if ($targetPage == Router
::$PAGE_FEED_ATOM || $targetPage == Router
::$PAGE_FEED_RSS) {
731 $feedType = $targetPage == Router
::$PAGE_FEED_RSS ? FeedBuilder
::$FEED_RSS : FeedBuilder
::$FEED_ATOM;
732 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
735 $query = $_SERVER['QUERY_STRING'];
736 $cache = new CachedPage(
737 $conf->get('resource.page_cache'),
739 startsWith($query, 'do='. $targetPage) && !$loginManager->isLoggedIn()
741 $cached = $cache->cachedVersion();
742 if (!empty($cached)) {
748 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, $loginManager->isLoggedIn());
749 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE
, 0)));
750 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
751 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
752 $data = $feedGenerator->buildData();
754 // Process plugin hook.
755 $pluginManager->executeHooks('render_feed', $data, array(
756 'loggedin' => $loginManager->isLoggedIn(),
757 'target' => $targetPage,
760 // Render the template.
761 $PAGE->assignAll($data);
762 $PAGE->renderPage('feed.'. $feedType);
763 $cache->cache(ob_get_contents());
768 // Display opensearch plugin (XML)
769 if ($targetPage == Router
::$PAGE_OPENSEARCH) {
770 header('Content-Type: application/xml; charset=utf-8');
771 $PAGE->assign('serverurl', index_url($_SERVER));
772 $PAGE->renderPage('opensearch');
776 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
777 if (isset($_GET['addtag'])) {
778 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
779 if (empty($_SERVER['HTTP_REFERER'])) {
780 // In case browser does not send HTTP_REFERER
781 header('Location: ?searchtags='.urlencode($_GET['addtag']));
784 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
786 // Prevent redirection loop
787 if (isset($params['addtag'])) {
788 unset($params['addtag']);
791 // Check if this tag is already in the search query and ignore it if it is.
792 // Each tag is always separated by a space
793 if (isset($params['searchtags'])) {
794 $current_tags = explode(' ', $params['searchtags']);
796 $current_tags = array();
799 foreach ($current_tags as $value) {
800 if ($value === $_GET['addtag']) {
805 // Append the tag if necessary
806 if (empty($params['searchtags'])) {
807 $params['searchtags'] = trim($_GET['addtag']);
809 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
812 // We also remove page (keeping the same page has no sense, since the
813 // results are different)
814 unset($params['page']);
816 header('Location: ?'.http_build_query($params));
820 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
821 if (isset($_GET['removetag'])) {
822 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
823 if (empty($_SERVER['HTTP_REFERER'])) {
824 header('Location: ?');
828 // In case browser does not send HTTP_REFERER
829 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
831 // Prevent redirection loop
832 if (isset($params['removetag'])) {
833 unset($params['removetag']);
836 if (isset($params['searchtags'])) {
837 $tags = explode(' ', $params['searchtags']);
838 // Remove value from array $tags.
839 $tags = array_diff($tags, array($_GET['removetag']));
840 $params['searchtags'] = implode(' ', $tags);
842 if (empty($params['searchtags'])) {
843 unset($params['searchtags']);
846 // We also remove page (keeping the same page has no sense, since
847 // the results are different)
848 unset($params['page']);
850 header('Location: ?'.http_build_query($params));
854 // -------- User wants to change the number of links per page (linksperpage=...)
855 if (isset($_GET['linksperpage'])) {
856 if (is_numeric($_GET['linksperpage'])) {
857 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
860 if (! empty($_SERVER['HTTP_REFERER'])) {
861 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
865 header('Location: '. $location);
869 // -------- User wants to see only private links (toggle)
870 if (isset($_GET['visibility'])) {
871 if ($_GET['visibility'] === 'private') {
872 // Visibility not set or not already private, set private, otherwise reset it
873 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
874 // See only private links
875 $_SESSION['visibility'] = 'private';
877 unset($_SESSION['visibility']);
879 } elseif ($_GET['visibility'] === 'public') {
880 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
881 // See only public links
882 $_SESSION['visibility'] = 'public';
884 unset($_SESSION['visibility']);
888 if (! empty($_SERVER['HTTP_REFERER'])) {
889 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
893 header('Location: '. $location);
897 // -------- User wants to see only untagged links (toggle)
898 if (isset($_GET['untaggedonly'])) {
899 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
901 if (! empty($_SERVER['HTTP_REFERER'])) {
902 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
906 header('Location: '. $location);
910 // -------- Handle other actions allowed for non-logged in users:
911 if (!$loginManager->isLoggedIn()) {
912 // User tries to post new link but is not logged in:
913 // Show login screen, then redirect to ?post=...
914 if (isset($_GET['post'])) {
915 header( // Redirect to login page, then back to post link.
916 'Location: ?do=login&post='.urlencode($_GET['post']).
917 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
918 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
919 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
920 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
925 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
926 if (isset($_GET['edit_link'])) {
927 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
931 exit; // Never remove this one! All operations below are reserved for logged in user.
934 // -------- All other functions are reserved for the registered user:
936 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
937 if ($targetPage == Router
::$PAGE_TOOLS) {
939 'pageabsaddr' => index_url($_SERVER),
940 'sslenabled' => is_https($_SERVER),
942 $pluginManager->executeHooks('render_tools', $data);
944 foreach ($data as $key => $value) {
945 $PAGE->assign($key, $value);
948 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
949 $PAGE->renderPage('tools');
953 // -------- User wants to change his/her password.
954 if ($targetPage == Router
::$PAGE_CHANGEPASSWORD) {
955 if ($conf->get('security.open_shaarli')) {
956 die(t('You are not supposed to change a password on an Open Shaarli.'));
959 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) {
960 if (!$sessionManager->checkToken($_POST['token'])) {
961 die(t('Wrong token.')); // Go away!
964 // Make sure old password is correct.
966 $_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt')
968 if ($oldhash != $conf->get('credentials.hash')) {
969 echo '<script>alert("'
970 . t('The old password is not correct.')
971 .'");document.location=\'?do=changepasswd\';</script>';
975 // Salt renders rainbow-tables attacks useless.
976 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
980 $_POST['setpassword']
981 . $conf->get('credentials.login')
982 . $conf->get('credentials.salt')
986 $conf->write($loginManager->isLoggedIn());
987 } catch (Exception
$e) {
989 'ERROR while writing config file after changing password.' . PHP_EOL
.
993 // TODO: do not handle exceptions/errors in JS.
994 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
997 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
1000 // show the change password form.
1001 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
1002 $PAGE->renderPage('changepassword');
1007 // -------- User wants to change configuration
1008 if ($targetPage == Router
::$PAGE_CONFIGURE) {
1009 if (!empty($_POST['title'])) {
1010 if (!$sessionManager->checkToken($_POST['token'])) {
1011 die(t('Wrong token.')); // Go away!
1014 if (!empty($_POST['continent']) && !empty($_POST['city'])
1015 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1017 $tz = $_POST['continent'] . '/' . $_POST['city'];
1019 $conf->set('general.timezone', $tz);
1020 $conf->set('general.title', escape($_POST['title']));
1021 $conf->set('general.header_link', escape($_POST['titleLink']));
1022 $conf->set('resource.theme', escape($_POST['theme']));
1023 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
1024 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
1025 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1026 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1027 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
1028 $conf->set('api.enabled', !empty($_POST['enableApi']));
1029 $conf->set('api.secret', escape($_POST['apiSecret']));
1030 $conf->set('translation.language', escape($_POST['language']));
1032 $thumbnailsMode = extension_loaded('gd') ? $_POST['enableThumbnails'] : Thumbnailer
::MODE_NONE
;
1033 if ($thumbnailsMode !== Thumbnailer
::MODE_NONE
1034 && $thumbnailsMode !== $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
)
1036 $_SESSION['warnings'][] = t(
1037 'You have enabled or changed thumbnails mode. '
1038 .'<a href="?do=thumbs_update">Please synchronize them</a>.'
1041 $conf->set('thumbnails.mode', $thumbnailsMode);
1044 $conf->write($loginManager->isLoggedIn());
1045 $history->updateSettings();
1046 invalidateCaches($conf->get('resource.page_cache'));
1047 } catch (Exception
$e) {
1049 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1053 // TODO: do not handle exceptions/errors in JS.
1054 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1057 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1060 // Show the configuration form.
1061 $PAGE->assign('title', $conf->get('general.title'));
1062 $PAGE->assign('theme', $conf->get('resource.theme'));
1063 $PAGE->assign('theme_available', ThemeUtils
::getThemes($conf->get('resource.raintpl_tpl')));
1064 list($continents, $cities) = generateTimeZoneData(
1065 timezone_identifiers_list(),
1066 $conf->get('general.timezone')
1068 $PAGE->assign('continents', $continents);
1069 $PAGE->assign('cities', $cities);
1070 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
1071 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1072 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1073 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1074 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1075 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1076 $PAGE->assign('api_secret', $conf->get('api.secret'));
1077 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1078 $PAGE->assign('language', $conf->get('translation.language'));
1079 $PAGE->assign('gd_enabled', extension_loaded('gd'));
1080 $PAGE->assign('thumbnails_mode', $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
));
1081 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
1082 $PAGE->renderPage('configure');
1087 // -------- User wants to rename a tag or delete it
1088 if ($targetPage == Router
::$PAGE_CHANGETAG) {
1089 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1090 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1091 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
1092 $PAGE->renderPage('changetag');
1096 if (!$sessionManager->checkToken($_POST['token'])) {
1097 die(t('Wrong token.'));
1100 $toTag = isset($_POST['totag']) ? escape($_POST['totag']) : null;
1101 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), $toTag);
1102 $LINKSDB->save($conf->get('resource.page_cache'));
1103 foreach ($alteredLinks as $link) {
1104 $history->updateLink($link);
1106 $delete = empty($_POST['totag']);
1107 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1108 $count = count($alteredLinks);
1110 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d links.', $count), $count)
1111 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d links.', $count), $count);
1112 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1116 // -------- User wants to add a link without using the bookmarklet: Show form.
1117 if ($targetPage == Router
::$PAGE_ADDLINK) {
1118 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1119 $PAGE->renderPage('addlink');
1123 // -------- User clicked the "Save" button when editing a link: Save link to database.
1124 if (isset($_POST['save_edit'])) {
1126 if (! $sessionManager->checkToken($_POST['token'])) {
1127 die(t('Wrong token.'));
1130 // lf_id should only be present if the link exists.
1131 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
1132 // Linkdate is kept here to:
1133 // - use the same permalink for notes as they're displayed when creating them
1134 // - let users hack creation date of their posts
1135 // See: https://shaarli.readthedocs.io/en/master/guides/various-hacks/#changing-the-timestamp-for-a-shaare
1136 $linkdate = escape($_POST['lf_linkdate']);
1137 if (isset($LINKSDB[$id])) {
1139 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1140 $updated = new DateTime();
1141 $shortUrl = $LINKSDB[$id]['shorturl'];
1145 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1147 $shortUrl = link_small_hash($created, $id);
1151 // Remove multiple spaces.
1152 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
1153 // Remove first '-' char in tags.
1154 $tags = preg_replace('/(^| )\-/', '$1', $tags);
1155 // Remove duplicates.
1156 $tags = implode(' ', array_unique(explode(' ', $tags)));
1158 if (empty(trim($_POST['lf_url
']))) {
1159 $_POST['lf_url
'] = '?' . smallHash($linkdate . $id);
1161 $url = whitelist_protocols(trim($_POST['lf_url
']), $conf->get('security
.allowed_protocols
'));
1165 'title
' => trim($_POST['lf_title
']),
1167 'description
' => $_POST['lf_description
'],
1168 'private' => (isset($_POST['lf_private
']) ? 1 : 0),
1169 'created
' => $created,
1170 'updated
' => $updated,
1171 'tags
' => str_replace(',', ' ', $tags),
1172 'shorturl
' => $shortUrl,
1175 // If title is empty, use the URL as title.
1176 if ($link['title
'] == '') {
1177 $link['title
'] = $link['url
'];
1180 if ($conf->get('thumbnails
.mode
', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE) {
1181 $thumbnailer = new Thumbnailer($conf);
1182 $link['thumbnail
'] = $thumbnailer->get($url);
1185 $pluginManager->executeHooks('save_link
', $link);
1187 $LINKSDB[$id] = $link;
1188 $LINKSDB->save($conf->get('resource.page_cache
'));
1190 $history->addLink($link);
1192 $history->updateLink($link);
1195 // If we are called from the bookmarklet, we must close the popup:
1196 if (isset($_GET['source
']) && ($_GET['source
']=='bookmarklet
' || $_GET['source
']=='firefoxsocialapi
')) {
1197 echo '<script
>self
.close();</script
>';
1201 $returnurl = !empty($_POST['returnurl
']) ? $_POST['returnurl
'] : '?';
1202 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST
'], array('addlink
', 'post
', 'edit_link
'));
1203 // Scroll to the link which has been edited.
1204 $location .= '#' . $link['shorturl'];
1205 // After saving the link, redirect to the page the user was on.
1206 header('Location: '. $location);
1210 // -------- User clicked the "Cancel" button when editing a link.
1211 if (isset($_POST['cancel_edit'])) {
1212 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1213 if (! isset($LINKSDB[$id])) {
1214 header('Location: ?');
1216 // If we are called from the bookmarklet, we must close the popup:
1217 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1218 echo '<script>self.close();</script>';
1221 $link = $LINKSDB[$id];
1222 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1223 // Scroll to the link which has been edited.
1224 $returnurl .= '#'. $link['shorturl'];
1225 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1226 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1230 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1231 if ($targetPage == Router
::$PAGE_DELETELINK) {
1232 if (! $sessionManager->checkToken($_GET['token'])) {
1233 die(t('Wrong token.'));
1236 $ids = trim($_GET['lf_linkdate']);
1237 if (strpos($ids, ' ') !== false) {
1238 // multiple, space-separated ids provided
1239 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1241 // only a single id provided
1244 // assert at least one id is given
1246 die('no id provided');
1248 foreach ($ids as $id) {
1249 $id = (int) escape($id);
1250 $link = $LINKSDB[$id];
1251 $pluginManager->executeHooks('delete_link', $link);
1252 $history->deleteLink($link);
1253 unset($LINKSDB[$id]);
1255 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1257 // If we are called from the bookmarklet, we must close the popup:
1258 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1259 echo '<script>self.close();</script>';
1264 if (isset($_SERVER['HTTP_REFERER'])) {
1265 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1266 $location = generateLocation(
1267 $_SERVER['HTTP_REFERER'],
1268 $_SERVER['HTTP_HOST'],
1269 ['delete_link', 'edit_link', $link['shorturl']]
1273 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1277 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1278 if (isset($_GET['edit_link'])) {
1279 $id = (int) escape($_GET['edit_link']);
1280 $link = $LINKSDB[$id]; // Read database
1282 header('Location: ?');
1284 } // Link not found in database.
1285 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1288 'link_is_new' => false,
1289 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1290 'tags' => $LINKSDB->linksCountPerTag(),
1292 $pluginManager->executeHooks('render_editlink', $data);
1294 foreach ($data as $key => $value) {
1295 $PAGE->assign($key, $value);
1298 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1299 $PAGE->renderPage('editlink');
1303 // -------- User want to post a new link: Display link edit form.
1304 if (isset($_GET['post'])) {
1305 $url = cleanup_url($_GET['post']);
1307 $link_is_new = false;
1308 // Check if URL is not already in database (in this case, we will edit the existing link)
1309 $link = $LINKSDB->getLinkFromUrl($url);
1311 $link_is_new = true;
1312 $linkdate = strval(date(LinkDB
::LINK_DATE_FORMAT
));
1313 // Get title if it was provided in URL (by the bookmarklet).
1314 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1315 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1316 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1317 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1318 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1320 // If this is an HTTP(S) link, we try go get the page to extract
1321 // the title (otherwise we will to straight to the edit form.)
1322 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1323 // Short timeout to keep the application responsive
1324 // The callback will fill $charset and $title with data from the downloaded page.
1327 $conf->get('general.download_timeout', 30),
1328 $conf->get('general.download_max_size', 4194304),
1329 get_curl_download_callback($charset, $title)
1331 if (! empty($title) && strtolower($charset) != 'utf-8') {
1332 $title = mb_convert_encoding($title, 'utf-8', $charset);
1337 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1338 $title = $conf->get('general.default_note_title', t('Note: '));
1340 $url = escape($url);
1341 $title = escape($title);
1344 'linkdate' => $linkdate,
1347 'description' => $description,
1349 'private' => $private,
1352 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1357 'link_is_new' => $link_is_new,
1358 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1359 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1360 'tags' => $LINKSDB->linksCountPerTag(),
1361 'default_private_links' => $conf->get('privacy.default_private_links', false),
1363 $pluginManager->executeHooks('render_editlink', $data);
1365 foreach ($data as $key => $value) {
1366 $PAGE->assign($key, $value);
1369 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1370 $PAGE->renderPage('editlink');
1374 if ($targetPage == Router
::$PAGE_PINLINK) {
1375 if (! isset($_GET['id']) || empty($LINKSDB[$_GET['id']])) {
1376 // FIXME! Use a proper error system.
1377 $msg = t('Invalid link ID provided');
1378 echo '<script>alert("'. $msg .'");document.location=\''. index_url($_SERVER) .'\';</script>';
1381 if (! $sessionManager->checkToken($_GET['token'])) {
1382 die('Wrong token.');
1385 $link = $LINKSDB[$_GET['id']];
1386 $link['sticky'] = ! $link['sticky'];
1387 $LINKSDB[(int) $_GET['id']] = $link;
1388 $LINKSDB->save($conf->get('resource.page_cache'));
1389 header('Location: '.index_url($_SERVER));
1393 if ($targetPage == Router
::$PAGE_EXPORT) {
1394 // Export links as a Netscape Bookmarks file
1396 if (empty($_GET['selection'])) {
1397 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1398 $PAGE->renderPage('export');
1402 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1403 $selection = $_GET['selection'];
1404 if (isset($_GET['prepend_note_url'])) {
1405 $prependNoteUrl = $_GET['prepend_note_url'];
1407 $prependNoteUrl = false;
1413 NetscapeBookmarkUtils
::filterAndFormat(
1420 } catch (Exception
$exc) {
1421 header('Content-Type: text/plain; charset=utf-8');
1422 echo $exc->getMessage();
1425 $now = new DateTime();
1426 header('Content-Type: text/html; charset=utf-8');
1428 'Content-disposition: attachment; filename=bookmarks_'
1429 .$selection.'_'.$now->format(LinkDB
::LINK_DATE_FORMAT
).'.html'
1431 $PAGE->assign('date', $now->format(DateTime
::RFC822
));
1432 $PAGE->assign('eol', PHP_EOL
);
1433 $PAGE->assign('selection', $selection);
1434 $PAGE->renderPage('export.bookmarks');
1438 if ($targetPage == Router
::$PAGE_IMPORT) {
1439 // Upload a Netscape bookmark dump to import its contents
1441 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1442 // Show import dialog
1445 get_max_upload_size(
1446 ini_get('post_max_size'),
1447 ini_get('upload_max_filesize'),
1453 get_max_upload_size(
1454 ini_get('post_max_size'),
1455 ini_get('upload_max_filesize'),
1459 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1460 $PAGE->renderPage('import');
1464 // Import bookmarks from an uploaded file
1465 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1466 // The file is too big or some form field may be missing.
1469 'The file you are trying to upload is probably bigger than what this webserver can accept'
1470 .' (%s). Please upload in smaller chunks.'
1472 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1474 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router
::$PAGE_IMPORT .'\';</script>';
1477 if (! $sessionManager->checkToken($_POST['token'])) {
1478 die('Wrong token.');
1480 $status = NetscapeBookmarkUtils
::import(
1487 echo '<script>alert("'.$status.'");document.location=\'?do='
1488 .Router
::$PAGE_IMPORT .'\';</script>';
1492 // Plugin administration page
1493 if ($targetPage == Router
::$PAGE_PLUGINSADMIN) {
1494 $pluginMeta = $pluginManager->getPluginsMeta();
1496 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1497 $enabledPlugins = array_filter($pluginMeta, function ($v) {
1498 return $v['order'] !== false;
1501 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1505 return $a['order'] - $b['order'];
1508 $disabledPlugins = array_filter($pluginMeta, function ($v) {
1509 return $v['order'] === false;
1512 $PAGE->assign('enabledPlugins', $enabledPlugins);
1513 $PAGE->assign('disabledPlugins', $disabledPlugins);
1514 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
1515 $PAGE->renderPage('pluginsadmin');
1519 // Plugin administration form action
1520 if ($targetPage == Router
::$PAGE_SAVE_PLUGINSADMIN) {
1522 if (isset($_POST['parameters_form'])) {
1523 unset($_POST['parameters_form']);
1524 foreach ($_POST as $param => $value) {
1525 $conf->set('plugins.'. $param, escape($value));
1528 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1530 $conf->write($loginManager->isLoggedIn());
1531 $history->updateSettings();
1532 } catch (Exception
$e) {
1534 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1538 // TODO: do not handle exceptions/errors in JS.
1539 echo '<script>alert("'
1541 .'");document.location=\'?do='
1542 . Router
::$PAGE_PLUGINSADMIN
1546 header('Location: ?do='. Router
::$PAGE_PLUGINSADMIN);
1550 // Get a fresh token
1551 if ($targetPage == Router
::$GET_TOKEN) {
1552 header('Content-Type:text/plain');
1553 echo $sessionManager->generateToken($conf);
1557 // -------- Thumbnails Update
1558 if ($targetPage == Router
::$PAGE_THUMBS_UPDATE) {
1560 foreach ($LINKSDB as $link) {
1561 // A note or not HTTP(S)
1562 if ($link['url'][0] === '?' || ! startsWith(strtolower($link['url']), 'http')) {
1565 $ids[] = $link['id'];
1567 $PAGE->assign('ids', $ids);
1568 $PAGE->assign('pagetitle', t('Thumbnails update') .' - '. $conf->get('general.title', 'Shaarli'));
1569 $PAGE->renderPage('thumbnails');
1573 // -------- Single Thumbnail Update
1574 if ($targetPage == Router
::$AJAX_THUMB_UPDATE) {
1575 if (! isset($_POST['id']) || ! ctype_digit($_POST['id'])) {
1576 http_response_code(400);
1579 $id = (int) $_POST['id'];
1580 if (empty($LINKSDB[$id])) {
1581 http_response_code(404);
1584 $thumbnailer = new Thumbnailer($conf);
1585 $link = $LINKSDB[$id];
1586 $link['thumbnail'] = $thumbnailer->get($link['url']);
1587 $LINKSDB[$id] = $link;
1588 $LINKSDB->save($conf->get('resource.page_cache'));
1590 echo json_encode($link);
1594 // -------- Otherwise, simply display search form and links:
1595 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
1600 * Template for the list of links (<div id="linklist">)
1601 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1603 * @param pageBuilder $PAGE pageBuilder instance.
1604 * @param LinkDB $LINKSDB LinkDB instance.
1605 * @param ConfigManager $conf Configuration Manager instance.
1606 * @param PluginManager $pluginManager Plugin Manager instance.
1607 * @param LoginManager $loginManager LoginManager instance
1609 function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1611 // Used in templates
1612 if (isset($_GET['searchtags'])) {
1613 if (! empty($_GET['searchtags'])) {
1614 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1616 $searchtags = false;
1621 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1624 if (! empty($_SERVER['QUERY_STRING'])
1625 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1627 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1628 } catch (LinkNotFoundException
$e) {
1629 $PAGE->render404($e->getMessage());
1633 // Filter links according search parameters.
1634 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
1636 'searchtags' => $searchtags,
1637 'searchterm' => $searchterm,
1639 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
1642 // ---- Handle paging.
1644 foreach ($linksToDisplay as $key => $value) {
1648 // Select articles according to paging.
1649 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1650 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1651 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1652 $page = $page < 1 ? 1 : $page;
1653 $page = $page > $pagecount ? $pagecount : $page;
1655 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1656 $end = $i +
$_SESSION['LINKS_PER_PAGE'];
1658 $thumbnailsEnabled = $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
) !== Thumbnailer
::MODE_NONE
;
1659 if ($thumbnailsEnabled) {
1660 $thumbnailer = new Thumbnailer($conf);
1663 $linkDisp = array();
1664 while ($i<$end && $i<count($keys)) {
1665 $link = $linksToDisplay[$keys[$i]];
1666 $link['description'] = format_description(
1667 $link['description'],
1668 $conf->get('redirector.url'),
1669 $conf->get('redirector.encode_url')
1671 $classLi = ($i %
2) != 0 ? '' : 'publicLinkHightLight';
1672 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
1673 $link['timestamp'] = $link['created']->getTimestamp();
1674 if (! empty($link['updated'])) {
1675 $link['updated_timestamp'] = $link['updated']->getTimestamp();
1677 $link['updated_timestamp'] = '';
1679 $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY
);
1680 uasort($taglist, 'strcasecmp');
1681 $link['taglist'] = $taglist;
1683 // Logged in, thumbnails enabled, not a note,
1684 // and (never retrieved yet or no valid cache file)
1685 if ($loginManager->isLoggedIn() && $thumbnailsEnabled && $link['url'][0] != '?'
1686 && (! isset($link['thumbnail']) || ($link['thumbnail'] !== false && ! is_file($link['thumbnail'])))
1688 $elem = $LINKSDB[$keys[$i]];
1689 $elem['thumbnail'] = $thumbnailer->get($link['url']);
1690 $LINKSDB[$keys[$i]] = $elem;
1692 $link['thumbnail'] = $elem['thumbnail'];
1695 // Check for both signs of a note: starting with ? and 7 chars long.
1696 if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
1697 $link['url'] = index_url($_SERVER) . $link['url'];
1700 $linkDisp[$keys[$i]] = $link;
1704 // If we retrieved new thumbnails, we update the database.
1705 if (!empty($updateDB)) {
1706 $LINKSDB->save($conf->get('resource.page_cache'));
1709 // Compute paging navigation
1710 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
1711 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1712 $previous_page_url = '';
1713 if ($i != count($keys)) {
1714 $previous_page_url = '?page=' . ($page+
1) . $searchtermUrl . $searchtagsUrl;
1718 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1721 // Fill all template fields.
1723 'previous_page_url' => $previous_page_url,
1724 'next_page_url' => $next_page_url,
1725 'page_current' => $page,
1726 'page_max' => $pagecount,
1727 'result_count' => count($linksToDisplay),
1728 'search_term' => $searchterm,
1729 'search_tags' => $searchtags,
1730 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
1731 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
1732 'links' => $linkDisp,
1735 // If there is only a single link, we change on-the-fly the title of the page.
1736 if (count($linksToDisplay) == 1) {
1737 $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
1738 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1739 $data['pagetitle'] = t('Search: ');
1740 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1741 $bracketWrap = function ($tag) {
1742 return '['. $tag .']';
1744 $data['pagetitle'] .= ! empty($searchtags)
1745 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1747 $data['pagetitle'] .= '- '. $conf->get('general.title');
1750 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
1752 foreach ($data as $key => $value) {
1753 $PAGE->assign($key, $value);
1761 * This function should NEVER be called if the file data/config.php exists.
1763 * @param ConfigManager $conf Configuration Manager instance.
1764 * @param SessionManager $sessionManager SessionManager instance
1765 * @param LoginManager $loginManager LoginManager instance
1767 function install($conf, $sessionManager, $loginManager)
1769 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1770 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
1771 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
1775 // This part makes sure sessions works correctly.
1776 // (Because on some hosts, session.save_path may not be set correctly,
1777 // or we may not have write access to it.)
1778 if (isset($_GET['test_session'])
1779 && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
1780 // Step 2: Check if data in session is correct.
1782 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1783 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1784 'and that you have write access to it.<br>'.
1785 'It currently points to %s.<br>'.
1786 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1787 'or any custom hostname without a dot causes cookie storage to fail. '.
1788 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1790 $msg = sprintf($msg, session_save_path());
1792 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1795 if (!isset($_SESSION['session_tested'])) {
1796 // Step 1 : Try to store data in session and reload page.
1797 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1798 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1800 if (isset($_GET['test_session'])) {
1801 // Step 3: Sessions are OK. Remove test parameter from URL.
1802 header('Location: '.index_url($_SERVER));
1806 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
1808 if (!empty($_POST['continent']) && !empty($_POST['city'])
1809 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1811 $tz = $_POST['continent'].'/'.$_POST['city'];
1813 $conf->set('general.timezone', $tz);
1814 $login = $_POST['setlogin'];
1815 $conf->set('credentials.login', $login);
1816 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1817 $conf->set('credentials.salt', $salt);
1818 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
1819 if (!empty($_POST['title'])) {
1820 $conf->set('general.title', escape($_POST['title']));
1822 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
1824 $conf->set('translation.language', escape($_POST['language']));
1825 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1826 $conf->set('api.enabled', !empty($_POST['enableApi']));
1829 generate_api_secret(
1830 $conf->get('credentials.login'),
1831 $conf->get('credentials.salt')
1835 // Everything is ok, let's create config file.
1836 $conf->write($loginManager->isLoggedIn());
1837 } catch (Exception
$e) {
1839 'ERROR while writing config file after installation.' . PHP_EOL
.
1843 // TODO: do not handle exceptions/errors in JS.
1844 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1847 echo '<script>alert('
1848 .'"Shaarli is now configured. '
1849 .'Please enter your login/password and start shaaring your links!"'
1850 .');document.location=\'?do=login\';</script>';
1854 $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
1855 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1856 $PAGE->assign('continents', $continents);
1857 $PAGE->assign('cities', $cities);
1858 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1859 $PAGE->renderPage('install');
1863 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) {
1864 showDailyRSS($conf, $loginManager);
1868 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
1869 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
1873 $history = new History($conf->get('resource.history'));
1874 } catch (Exception
$e) {
1875 die($e->getMessage());
1878 $linkDb = new LinkDB(
1879 $conf->get('resource.datastore'),
1880 $loginManager->isLoggedIn(),
1881 $conf->get('privacy.hide_public_links'),
1882 $conf->get('redirector.url'),
1883 $conf->get('redirector.encode_url')
1886 $container = new \Slim\
Container();
1887 $container['conf'] = $conf;
1888 $container['plugins'] = $pluginManager;
1889 $container['history'] = $history;
1890 $app = new \Slim\
App($container);
1893 $app->group('/api/v1', function () {
1894 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
1895 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
1896 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
1897 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
1898 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
1899 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
1901 $this->get('/tags', '\Shaarli\Api\Controllers\Tags:getTags')->setName('getTags');
1902 $this->get('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:getTag')->setName('getTag');
1903 $this->put('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:putTag')->setName('putTag');
1904 $this->delete('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:deleteTag')->setName('deleteTag');
1906 $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
1907 })->add('\Shaarli\Api\ApiMiddleware');
1909 $response = $app->run(true);
1911 // Hack to make Slim and Shaarli router work together:
1912 // If a Slim route isn't found and NOT API call, we call renderPage().
1913 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
1914 // We use UTF-8 for proper international characters handling.
1915 header('Content-Type: text/html; charset=utf-8');
1916 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
1918 $response = $response
1919 ->withHeader('Access-Control-Allow-Origin', '*')
1921 'Access-Control-Allow-Headers',
1922 'X-Requested-With, Content-Type, Accept, Origin, Authorization'
1924 ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
1925 $app->respond($response);