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/Cache.php';
61 require_once 'application/CachedPage.php';
62 require_once 'application/config/ConfigPlugin.php';
63 require_once 'application/FeedBuilder.php';
64 require_once 'application/FileUtils.php';
65 require_once 'application/History.php';
66 require_once 'application/HttpUtils.php';
67 require_once 'application/LinkDB.php';
68 require_once 'application/LinkFilter.php';
69 require_once 'application/LinkUtils.php';
70 require_once 'application/NetscapeBookmarkUtils.php';
71 require_once 'application/PageBuilder.php';
72 require_once 'application/TimeZone.php';
73 require_once 'application/Url.php';
74 require_once 'application/Utils.php';
75 require_once 'application/PluginManager.php';
76 require_once 'application/Router.php';
77 require_once 'application/Updater.php';
78 use \Shaarli\Config\ConfigManager
;
79 use \Shaarli\Languages
;
80 use \Shaarli\Security\LoginManager
;
81 use \Shaarli\Security\SessionManager
;
82 use \Shaarli\ThemeUtils
;
83 use \Shaarli\Thumbnailer
;
85 // Ensure the PHP version is supported
87 ApplicationUtils
::checkPHPVersion('5.5', PHP_VERSION
);
88 } catch(Exception
$exc) {
89 header('Content-Type: text/plain; charset=utf-8');
90 echo $exc->getMessage();
94 define('SHAARLI_VERSION', ApplicationUtils
::getVersion(__DIR__
.'/'. ApplicationUtils
::$VERSION_FILE));
96 // Force cookie path (but do not change lifetime)
97 $cookie = session_get_cookie_params();
99 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
100 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
102 // Set default cookie expiration and path.
103 session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
104 // Set session parameters on server side.
105 // Use cookies to store session.
106 ini_set('session.use_cookies', 1);
107 // Force cookies for session (phpsessionID forbidden in URL).
108 ini_set('session.use_only_cookies', 1);
109 // Prevent PHP form using sessionID in URL if cookies are disabled.
110 ini_set('session.use_trans_sid', false);
112 session_name('shaarli');
113 // Start session if needed (Some server auto-start sessions).
114 if (session_id() == '') {
118 // Regenerate session ID if invalid or not defined in cookie.
119 if (isset($_COOKIE['shaarli']) && !SessionManager
::checkId($_COOKIE['shaarli'])) {
120 session_regenerate_id(true);
121 $_COOKIE['shaarli'] = session_id();
124 $folderBase = getenv("BASE");
126 if (getenv("USERSPACE")) {
127 if (isset($_GET["do"]) && $_GET["do"] == "login") {
128 header("Location: $folderBase/?do=login");
131 $userspace = preg_replace("/[^-_A-Za-z0-9]/", '', getenv("USERSPACE"));
132 } else if (isset($_SESSION["username"]) && $_SESSION["username"]) {
133 header("Location: " . $folderBase . "/" . $_SESSION["username"] . "?");
135 } else if (!isset($_GET["do"]) || $_GET["do"] != "login") {
136 header("Location: $folderBase/?do=login");
140 if (!isset($userspace) && isset($_POST["login"])) {
141 $userspace = preg_replace("/[^-_A-Za-z0-9]/", '', $_POST["login"]);
142 error_log("debugImmae: setting userspace from POST: " . $userspace);
145 if (isset($userspace)) {
146 $conf = new ConfigManager(null, $userspace);
148 $conf = new ConfigManager();
150 $sessionManager = new SessionManager($_SESSION, $conf);
151 $loginManager = new LoginManager($GLOBALS, $conf, $sessionManager);
152 $loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
153 $clientIpId = client_ip_id($_SERVER);
155 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
156 if (! defined('LC_MESSAGES')) {
157 define('LC_MESSAGES', LC_COLLATE
);
160 // Sniff browser language and set date format accordingly.
161 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
162 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
165 new Languages(setlocale(LC_MESSAGES
, 0), $conf);
167 $conf->setEmpty('general.timezone', date_default_timezone_get());
168 $conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
169 RainTPL
::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
170 RainTPL
::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
172 $pluginManager = new PluginManager($conf);
173 $pluginManager->load($conf->get('general.enabled_plugins'));
175 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
177 ob_start(); // Output buffering for the page cache.
179 // Prevent caching on client side or proxy: (yes, it's ugly)
180 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
181 header("Cache-Control: no-store, no-cache, must-revalidate");
182 header("Cache-Control: post-check=0, pre-check=0", false);
183 header("Pragma: no-cache");
185 if (! is_file($conf->getConfigFileExt())) {
186 // Ensure Shaarli has proper access to its resources
187 $errors = ApplicationUtils
::checkResourcePermissions($conf);
189 if ($errors != array()) {
190 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
192 foreach ($errors as $error) {
193 $message .= '<li>'.$error.'</li>';
197 header('Content-Type: text/html; charset=utf-8');
202 // Display the installation form if no existing config is found
203 install($conf, $sessionManager, $loginManager, $userspace);
206 $loginManager->checkLoginState($_COOKIE, $clientIpId);
209 * Adapter function to ensure compatibility with third-party templates
211 * @see https://github.com/shaarli/Shaarli/pull/1086
213 * @return bool true when the user is logged in, false otherwise
215 function isLoggedIn()
217 global $loginManager;
218 return $loginManager->isLoggedIn();
222 // ------------------------------------------------------------------------------------------
223 // Process login form: Check if login/password is correct.
224 if (isset($_POST['login'])) {
225 if (! $loginManager->canLogin($_SERVER)) {
226 die(t('I said: NO. You are banned for the moment. Go away.'));
228 if (isset($_POST['password'])
229 && $sessionManager->checkToken($_POST['token'])
230 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
232 $loginManager->handleSuccessfulLogin($_SERVER);
233 $userspace = $_POST['login'];
236 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
237 // Note: Never forget the trailing slash on the cookie path!
238 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
241 if (!empty($_POST['longlastingsession'])) {
242 // Keep the session cookie even after the browser closes
243 $sessionManager->setStaySignedIn(true);
244 $expirationTime = $sessionManager->extendSession();
247 $loginManager::$STAY_SIGNED_IN_COOKIE,
248 $loginManager->getStaySignedInToken(),
254 // Standard session expiration (=when browser closes)
258 // Send cookie with the new expiration date to the browser
259 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
260 session_regenerate_id(true);
262 // Optional redirect after login:
263 if (isset($_GET['post'])) {
264 $uri = '?post='. urlencode($_GET['post']);
265 foreach (array('description', 'source', 'title', 'tags') as $param) {
266 if (!empty($_GET[$param])) {
267 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
270 header('Location: '. $userspace . $uri);
274 if (isset($_GET['edit_link'])) {
275 header('Location: ' . $userspace . '?edit_link='. escape($_GET['edit_link']));
279 if (isset($_POST['returnurl'])) {
280 // Prevent loops over login screen.
281 if (strpos($_POST['returnurl'], 'do=login') === false) {
282 header('Location: ' . generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
286 header('Location: '. $userspace . '?'); exit;
288 $errorReason = $loginManager->handleFailedLogin($_SERVER);
289 $redir = '&username='. urlencode($_POST['login']);
290 if (isset($_GET['post'])) {
291 $redir .= '&post=' . urlencode($_GET['post']);
292 foreach (array('description', 'source', 'title', 'tags') as $param) {
293 if (!empty($_GET[$param])) {
294 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
298 // Redirect to login screen.
299 echo '<script>alert("'. t($errorReason) .'");document.location=\'?do=login'.$redir.'\';</script>';
304 // ------------------------------------------------------------------------------------------
305 // Token management for XSRF protection
306 // Token should be used in any form which acts on data (create,update,delete,import...).
307 if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
310 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
311 * Gives the last 7 days (which have links).
312 * This RSS feed cannot be filtered.
314 * @param ConfigManager $conf Configuration Manager instance
315 * @param LoginManager $loginManager LoginManager instance
317 function showDailyRSS($conf, $loginManager) {
319 $query = $_SERVER['QUERY_STRING'];
320 $cache = new CachedPage(
321 $conf->get('config.PAGE_CACHE'),
323 startsWith($query,'do=dailyrss') && !$loginManager->isLoggedIn()
325 $cached = $cache->cachedVersion();
326 if (!empty($cached)) {
331 // If cached was not found (or not usable), then read the database and build the response:
332 // Read links from database (and filter private links if used it not logged in).
333 $LINKSDB = new LinkDB(
334 $conf->get('resource.datastore'),
335 $loginManager->isLoggedIn(),
336 $conf->get('privacy.hide_public_links'),
337 $conf->get('redirector.url'),
338 $conf->get('redirector.encode_url')
341 /* Some Shaarlies may have very few links, so we need to look
342 back in time until we have enough days ($nb_of_days).
344 $nb_of_days = 7; // We take 7 days.
345 $today = date('Ymd');
348 foreach ($LINKSDB as $link) {
349 $day = $link['created']->format('Ymd'); // Extract day (without time)
350 if (strcmp($day, $today) < 0) {
351 if (empty($days[$day])) {
352 $days[$day] = array();
354 $days[$day][] = $link;
357 if (count($days) > $nb_of_days) {
358 break; // Have we collected enough days?
362 // Build the RSS feed.
363 header('Content-Type: application/rss+xml; charset=utf-8');
364 $pageaddr = escape(index_url($_SERVER));
365 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
367 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
368 echo '<link>'. $pageaddr .'</link>';
369 echo '<description>Daily shared links</description>';
370 echo '<language>en-en</language>';
371 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL
;
374 foreach ($days as $day => $links) {
375 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
376 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
378 // We pre-format some fields for proper output.
379 foreach ($links as &$link) {
380 $link['formatedDescription'] = format_description(
381 $link['description'],
382 $conf->get('redirector.url'),
383 $conf->get('redirector.encode_url')
385 $link['timestamp'] = $link['created']->getTimestamp();
386 if (startsWith($link['url'], '?')) {
387 $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
391 // Then build the HTML for this day:
393 $tpl->assign('title', $conf->get('general.title'));
394 $tpl->assign('daydate', $dayDate->getTimestamp());
395 $tpl->assign('absurl', $absurl);
396 $tpl->assign('links', $links);
397 $tpl->assign('rssdate', escape($dayDate->format(DateTime
::RSS
)));
398 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
399 $tpl->assign('index_url', $pageaddr);
400 $html = $tpl->draw('dailyrss', true);
402 echo $html . PHP_EOL
;
404 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
406 $cache->cache(ob_get_contents());
412 * Show the 'Daily' page.
414 * @param PageBuilder $pageBuilder Template engine wrapper.
415 * @param LinkDB $LINKSDB LinkDB instance.
416 * @param ConfigManager $conf Configuration Manager instance.
417 * @param PluginManager $pluginManager Plugin Manager instance.
418 * @param LoginManager $loginManager Login Manager instance
420 function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
422 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
423 if (isset($_GET['day'])) {
427 $days = $LINKSDB->days();
428 $i = array_search($day, $days);
429 if ($i === false && count($days)) {
430 // no links for day, but at least one day with links
431 $i = count($days) - 1;
439 $previousday=$days[$i - 1];
441 if ($i < count($days) - 1) {
442 $nextday = $days[$i +
1];
446 $linksToDisplay = $LINKSDB->filterDay($day);
447 } catch (Exception
$exc) {
449 $linksToDisplay = array();
452 // We pre-format some fields for proper output.
453 foreach($linksToDisplay as $key => $link) {
454 $taglist = explode(' ',$link['tags']);
455 uasort($taglist, 'strcasecmp');
456 $linksToDisplay[$key]['taglist']=$taglist;
457 $linksToDisplay[$key]['formatedDescription'] = format_description(
458 $link['description'],
459 $conf->get('redirector.url'),
460 $conf->get('redirector.encode_url')
462 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
465 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
467 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
468 'linksToDisplay' => $linksToDisplay,
469 'day' => $dayDate->getTimestamp(),
470 'dayDate' => $dayDate,
471 'previousday' => $previousday,
472 'nextday' => $nextday,
475 /* Hook is called before column construction so that plugins don't have
476 to deal with columns. */
477 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
479 /* We need to spread the articles on 3 columns.
480 I did not want to use a JavaScript lib like http://masonry.desandro.com/
481 so I manually spread entries with a simple method: I roughly evaluate the
482 height of a div according to title and description length.
484 $columns = array(array(), array(), array()); // Entries to display, for each column.
485 $fill = array(0, 0, 0); // Rough estimate of columns fill.
486 foreach($data['linksToDisplay'] as $key => $link) {
487 // Roughly estimate length of entry (by counting characters)
488 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
489 // Description: 836 characters gives roughly 342 pixel height.
490 // This is not perfect, but it's usually OK.
491 $length = strlen($link['title']) +
(342 * strlen($link['description'])) / 836;
492 if ($link['thumbnail']) {
493 $length +
= 100; // 1 thumbnails roughly takes 100 pixels height.
495 // Then put in column which is the less filled:
496 $smallest = min($fill); // find smallest value in array.
497 $index = array_search($smallest, $fill); // find index of this smallest value.
498 array_push($columns[$index], $link); // Put entry in this column.
499 $fill[$index] +
= $length;
502 $data['cols'] = $columns;
504 foreach ($data as $key => $value) {
505 $pageBuilder->assign($key, $value);
508 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
509 $pageBuilder->renderPage('daily');
514 * Renders the linklist
516 * @param pageBuilder $PAGE pageBuilder instance.
517 * @param LinkDB $LINKSDB LinkDB instance.
518 * @param ConfigManager $conf Configuration Manager instance.
519 * @param PluginManager $pluginManager Plugin Manager instance.
521 function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager) {
522 buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager, $loginManager);
523 $PAGE->renderPage('linklist');
527 * Render HTML page (according to URL parameters and user rights)
529 * @param ConfigManager $conf Configuration Manager instance.
530 * @param PluginManager $pluginManager Plugin Manager instance,
531 * @param LinkDB $LINKSDB
532 * @param History $history instance
533 * @param SessionManager $sessionManager SessionManager instance
534 * @param LoginManager $loginManager LoginManager instance
536 function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
538 $updater = new Updater(
539 read_updates_file($conf->get('resource.updates')),
542 $loginManager->isLoggedIn(),
546 $newUpdates = $updater->update();
547 if (! empty($newUpdates)) {
549 $conf->get('resource.updates'),
550 $updater->getDoneUpdates()
554 catch(Exception
$e) {
555 die($e->getMessage());
558 $PAGE = new PageBuilder($conf, $_SESSION, $LINKSDB, $sessionManager->generateToken(), $loginManager->isLoggedIn());
559 $PAGE->assign('linkcount', count($LINKSDB));
560 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
561 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
563 // Determine which page will be rendered.
564 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
565 $targetPage = Router
::findPage($query, $_GET, $loginManager->isLoggedIn());
568 // if the user isn't logged in
569 !$loginManager->isLoggedIn() &&
570 // and Shaarli doesn't have public content...
571 $conf->get('privacy.hide_public_links') &&
572 // and is configured to enforce the login
573 $conf->get('privacy.force_login') &&
574 // and the current page isn't already the login page
575 $targetPage !== Router
::$PAGE_LOGIN &&
576 // and the user is not requesting a feed (which would lead to a different content-type as expected)
577 $targetPage !== Router
::$PAGE_FEED_ATOM &&
578 $targetPage !== Router
::$PAGE_FEED_RSS
580 // force current page to be the login page
581 $targetPage = Router
::$PAGE_LOGIN;
584 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
585 // Then assign generated data to RainTPL.
586 $common_hooks = array(
592 foreach($common_hooks as $name) {
593 $plugin_data = array();
594 $pluginManager->executeHooks('render_' . $name, $plugin_data,
596 'target' => $targetPage,
597 'loggedin' => $loginManager->isLoggedIn()
600 $PAGE->assign('plugins_' . $name, $plugin_data);
603 // -------- Display login form.
604 if ($targetPage == Router
::$PAGE_LOGIN)
606 if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
607 if (isset($_GET['username'])) {
608 $PAGE->assign('username', escape($_GET['username']));
610 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
611 // add default state of the 'remember me' checkbox
612 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
613 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
614 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
615 $PAGE->renderPage('loginform');
618 // -------- User wants to logout.
619 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
621 invalidateCaches($conf->get('resource.page_cache'));
622 $sessionManager->logout();
623 setcookie(LoginManager
::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH
);
624 header('Location: ?');
628 // -------- Picture wall
629 if ($targetPage == Router
::$PAGE_PICWALL)
631 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
632 if (! $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
) === Thumbnailer
::MODE_NONE
) {
633 $PAGE->assign('linksToDisplay', []);
634 $PAGE->renderPage('picwall');
638 // Optionally filter the results:
639 $links = $LINKSDB->filterSearch($_GET);
640 $linksToDisplay = array();
642 // Get only links which have a thumbnail.
643 // Note: we do not retrieve thumbnails here, the request is too heavy.
644 foreach($links as $key => $link)
646 if (isset($link['thumbnail']) && $link['thumbnail'] !== false) {
647 $linksToDisplay[] = $link; // Add to array.
652 'linksToDisplay' => $linksToDisplay,
654 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => $loginManager->isLoggedIn()));
656 foreach ($data as $key => $value) {
657 $PAGE->assign($key, $value);
661 $PAGE->renderPage('picwall');
665 // -------- Tag cloud
666 if ($targetPage == Router
::$PAGE_TAGCLOUD)
668 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
669 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
670 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
672 // We sort tags alphabetically, then choose a font size according to count.
673 // First, find max value.
675 foreach ($tags as $value) {
676 $maxcount = max($maxcount, $value);
679 alphabetical_sort($tags, false, true);
682 foreach($tags as $key => $value) {
683 if (in_array($key, $filteringTags)) {
686 // Tag font size scaling:
687 // default 15 and 30 logarithm bases affect scaling,
688 // 22 and 6 are arbitrary font sizes for max and min sizes.
689 $size = log($value, 15) / log($maxcount, 30) * 2.2 +
0.8;
690 $tagList[$key] = array(
692 'size' => number_format($size, 2, '.', ''),
696 $searchTags = implode(' ', escape($filteringTags));
698 'search_tags' => $searchTags,
701 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
703 foreach ($data as $key => $value) {
704 $PAGE->assign($key, $value);
707 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
708 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
709 $PAGE->renderPage('tag.cloud');
714 if ($targetPage == Router
::$PAGE_TAGLIST)
716 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
717 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
718 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
719 foreach ($filteringTags as $tag) {
720 if (array_key_exists($tag, $tags)) {
725 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
726 alphabetical_sort($tags, false, true);
729 $searchTags = implode(' ', escape($filteringTags));
731 'search_tags' => $searchTags,
734 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
736 foreach ($data as $key => $value) {
737 $PAGE->assign($key, $value);
740 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
741 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
742 $PAGE->renderPage('tag.list');
747 if ($targetPage == Router
::$PAGE_DAILY) {
748 showDaily($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
751 // ATOM and RSS feed.
752 if ($targetPage == Router
::$PAGE_FEED_ATOM || $targetPage == Router
::$PAGE_FEED_RSS) {
753 $feedType = $targetPage == Router
::$PAGE_FEED_RSS ? FeedBuilder
::$FEED_RSS : FeedBuilder
::$FEED_ATOM;
754 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
757 $query = $_SERVER['QUERY_STRING'];
758 $cache = new CachedPage(
759 $conf->get('resource.page_cache'),
761 startsWith($query,'do='. $targetPage) && !$loginManager->isLoggedIn()
763 $cached = $cache->cachedVersion();
764 if (!empty($cached)) {
770 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, $loginManager->isLoggedIn());
771 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE
, 0)));
772 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
773 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
774 $data = $feedGenerator->buildData();
776 // Process plugin hook.
777 $pluginManager->executeHooks('render_feed', $data, array(
778 'loggedin' => $loginManager->isLoggedIn(),
779 'target' => $targetPage,
782 // Render the template.
783 $PAGE->assignAll($data);
784 $PAGE->renderPage('feed.'. $feedType);
785 $cache->cache(ob_get_contents());
790 // Display opensearch plugin (XML)
791 if ($targetPage == Router
::$PAGE_OPENSEARCH) {
792 header('Content-Type: application/xml; charset=utf-8');
793 $PAGE->assign('serverurl', index_url($_SERVER));
794 $PAGE->renderPage('opensearch');
798 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
799 if (isset($_GET['addtag']))
801 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
802 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET
['addtag'])); exit; } // In case browser does not send HTTP_REFERER
803 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY
), $params);
805 // Prevent redirection loop
806 if (isset($params['addtag'])) {
807 unset($params['addtag']);
810 // Check if this tag is already in the search query and ignore it if it is.
811 // Each tag is always separated by a space
812 if (isset($params['searchtags'])) {
813 $current_tags = explode(' ', $params['searchtags']);
815 $current_tags = array();
818 foreach ($current_tags as $value) {
819 if ($value === $_GET['addtag']) {
824 // Append the tag if necessary
825 if (empty($params['searchtags'])) {
826 $params['searchtags'] = trim($_GET['addtag']);
829 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
832 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
833 header('Location: ?'.http_build_query($params));
837 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
838 if (isset($_GET['removetag'])) {
839 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
840 if (empty($_SERVER['HTTP_REFERER'])) {
841 header('Location: ?');
845 // In case browser does not send HTTP_REFERER
846 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
848 // Prevent redirection loop
849 if (isset($params['removetag'])) {
850 unset($params['removetag']);
853 if (isset($params['searchtags'])) {
854 $tags = explode(' ', $params['searchtags']);
855 // Remove value from array $tags.
856 $tags = array_diff($tags, array($_GET['removetag']));
857 $params['searchtags'] = implode(' ',$tags);
859 if (empty($params['searchtags'])) {
860 unset($params['searchtags']);
863 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
865 header('Location: ?'.http_build_query($params));
869 // -------- User wants to change the number of links per page (linksperpage=...)
870 if (isset($_GET['linksperpage'])) {
871 if (is_numeric($_GET['linksperpage'])) {
872 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
875 if (! empty($_SERVER['HTTP_REFERER'])) {
876 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
880 header('Location: '. $location);
884 // -------- User wants to see only private links (toggle)
885 if (isset($_GET['visibility'])) {
886 if ($_GET['visibility'] === 'private') {
887 // Visibility not set or not already private, set private, otherwise reset it
888 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
889 // See only private links
890 $_SESSION['visibility'] = 'private';
892 unset($_SESSION['visibility']);
894 } elseif ($_GET['visibility'] === 'public') {
895 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
896 // See only public links
897 $_SESSION['visibility'] = 'public';
899 unset($_SESSION['visibility']);
903 if (! empty($_SERVER['HTTP_REFERER'])) {
904 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
908 header('Location: '. $location);
912 // -------- User wants to see only untagged links (toggle)
913 if (isset($_GET['untaggedonly'])) {
914 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
916 if (! empty($_SERVER['HTTP_REFERER'])) {
917 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
921 header('Location: '. $location);
925 // -------- Handle other actions allowed for non-logged in users:
926 if (!$loginManager->isLoggedIn())
928 // User tries to post new link but is not logged in:
929 // Show login screen, then redirect to ?post=...
930 if (isset($_GET['post']))
932 header( // Redirect to login page, then back to post link.
933 'Location: ?do=login&post='.urlencode($_GET['post']).
934 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
935 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
936 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
937 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
942 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
943 if (isset($_GET['edit_link'])) {
944 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
948 exit; // Never remove this one! All operations below are reserved for logged in user.
951 // -------- All other functions are reserved for the registered user:
953 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
954 if ($targetPage == Router
::$PAGE_TOOLS)
957 'pageabsaddr' => index_url($_SERVER),
958 'sslenabled' => is_https($_SERVER),
960 $pluginManager->executeHooks('render_tools', $data);
962 foreach ($data as $key => $value) {
963 $PAGE->assign($key, $value);
966 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
967 $PAGE->renderPage('tools');
971 // -------- User wants to change his/her password.
972 if ($targetPage == Router
::$PAGE_CHANGEPASSWORD)
974 if ($conf->get('security.open_shaarli')) {
975 die(t('You are not supposed to change a password on an Open Shaarli.'));
978 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
980 if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away!
982 // Make sure old password is correct.
983 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
984 if ($oldhash!= $conf->get('credentials.hash')) {
985 echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>';
989 // Salt renders rainbow-tables attacks useless.
990 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
991 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt')));
993 $conf->write($loginManager->isLoggedIn());
995 catch(Exception
$e) {
997 'ERROR while writing config file after changing password.' . PHP_EOL
.
1001 // TODO: do not handle exceptions/errors in JS.
1002 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
1005 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
1008 else // show the change password form.
1010 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
1011 $PAGE->renderPage('changepassword');
1016 // -------- User wants to change configuration
1017 if ($targetPage == Router
::$PAGE_CONFIGURE)
1019 if (!empty($_POST['title']) )
1021 if (!$sessionManager->checkToken($_POST['token'])) {
1022 die(t('Wrong token.')); // Go away!
1025 if (!empty($_POST['continent']) && !empty($_POST['city'])
1026 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1028 $tz = $_POST['continent'] . '/' . $_POST['city'];
1030 $conf->set('general.timezone', $tz);
1031 $conf->set('general.title', escape($_POST['title']));
1032 $conf->set('general.header_link', escape($_POST['titleLink']));
1033 $conf->set('resource.theme', escape($_POST['theme']));
1034 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
1035 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
1036 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1037 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1038 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
1039 $conf->set('api.enabled', !empty($_POST['enableApi']));
1040 $conf->set('api.secret', escape($_POST['apiSecret']));
1041 $conf->set('translation.language', escape($_POST['language']));
1043 $thumbnailsMode = extension_loaded('gd') ? $_POST['enableThumbnails'] : Thumbnailer
::MODE_NONE
;
1044 if ($thumbnailsMode !== Thumbnailer
::MODE_NONE
1045 && $thumbnailsMode !== $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
)
1047 $_SESSION['warnings'][] = t(
1048 'You have enabled or changed thumbnails mode. <a href="?do=thumbs_update">Please synchronize them</a>.'
1051 $conf->set('thumbnails.mode', $thumbnailsMode);
1054 $conf->write($loginManager->isLoggedIn());
1055 $history->updateSettings();
1056 invalidateCaches($conf->get('resource.page_cache'));
1058 catch(Exception
$e) {
1060 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1064 // TODO: do not handle exceptions/errors in JS.
1065 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1068 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1071 else // Show the configuration form.
1073 $PAGE->assign('title', $conf->get('general.title'));
1074 $PAGE->assign('theme', $conf->get('resource.theme'));
1075 $PAGE->assign('theme_available', ThemeUtils
::getThemes($conf->get('resource.raintpl_tpl')));
1076 list($continents, $cities) = generateTimeZoneData(
1077 timezone_identifiers_list(),
1078 $conf->get('general.timezone')
1080 $PAGE->assign('continents', $continents);
1081 $PAGE->assign('cities', $cities);
1082 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
1083 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1084 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1085 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1086 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1087 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1088 $PAGE->assign('api_secret', $conf->get('api.secret'));
1089 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1090 $PAGE->assign('language', $conf->get('translation.language'));
1091 $PAGE->assign('gd_enabled', extension_loaded('gd'));
1092 $PAGE->assign('thumbnails_mode', $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
));
1093 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
1094 $PAGE->renderPage('configure');
1099 // -------- User wants to rename a tag or delete it
1100 if ($targetPage == Router
::$PAGE_CHANGETAG)
1102 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1103 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1104 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
1105 $PAGE->renderPage('changetag');
1109 if (!$sessionManager->checkToken($_POST['token'])) {
1110 die(t('Wrong token.'));
1113 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), escape($_POST['totag']));
1114 $LINKSDB->save($conf->get('resource.page_cache'));
1115 foreach ($alteredLinks as $link) {
1116 $history->updateLink($link);
1118 $delete = empty($_POST['totag']);
1119 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1120 $count = count($alteredLinks);
1122 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d links.', $count), $count)
1123 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d links.', $count), $count);
1124 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1128 // -------- User wants to add a link without using the bookmarklet: Show form.
1129 if ($targetPage == Router
::$PAGE_ADDLINK)
1131 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1132 $PAGE->renderPage('addlink');
1136 // -------- User clicked the "Save" button when editing a link: Save link to database.
1137 if (isset($_POST['save_edit']))
1140 if (! $sessionManager->checkToken($_POST['token'])) {
1141 die(t('Wrong token.'));
1144 // lf_id should only be present if the link exists.
1145 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
1146 // Linkdate is kept here to:
1147 // - use the same permalink for notes as they're displayed when creating them
1148 // - let users hack creation date of their posts
1149 // See: https://shaarli.readthedocs.io/en/master/guides/various-hacks/#changing-the-timestamp-for-a-shaare
1150 $linkdate = escape($_POST['lf_linkdate']);
1151 if (isset($LINKSDB[$id])) {
1153 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1154 $updated = new DateTime();
1155 $shortUrl = $LINKSDB[$id]['shorturl'];
1159 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1161 $shortUrl = link_small_hash($created, $id);
1165 // Remove multiple spaces.
1166 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
1167 // Remove first '-' char in tags.
1168 $tags = preg_replace('/(^| )\-/', '$1', $tags);
1169 // Remove duplicates.
1170 $tags = implode(' ', array_unique(explode(' ', $tags)));
1172 if (empty(trim($_POST['lf_url
']))) {
1173 $_POST['lf_url
'] = '?' . smallHash($linkdate . $id);
1175 $url = whitelist_protocols(trim($_POST['lf_url
']), $conf->get('security
.allowed_protocols
'));
1179 'title
' => trim($_POST['lf_title
']),
1181 'description
' => $_POST['lf_description
'],
1182 'private' => (isset($_POST['lf_private
']) ? 1 : 0),
1183 'created
' => $created,
1184 'updated
' => $updated,
1185 'tags
' => str_replace(',', ' ', $tags),
1186 'shorturl
' => $shortUrl,
1189 // If title is empty, use the URL as title.
1190 if ($link['title
'] == '') {
1191 $link['title
'] = $link['url
'];
1194 if ($conf->get('thumbnails
.mode
', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE) {
1195 $thumbnailer = new Thumbnailer($conf);
1196 $link['thumbnail
'] = $thumbnailer->get($url);
1199 $pluginManager->executeHooks('save_link
', $link);
1201 $LINKSDB[$id] = $link;
1202 $LINKSDB->save($conf->get('resource.page_cache
'));
1204 $history->addLink($link);
1206 $history->updateLink($link);
1209 // If we are called from the bookmarklet, we must close the popup:
1210 if (isset($_GET['source
']) && ($_GET['source
']=='bookmarklet
' || $_GET['source
']=='firefoxsocialapi
')) {
1211 echo '<script
>self
.close();</script
>';
1215 $returnurl = !empty($_POST['returnurl
']) ? $_POST['returnurl
'] : '?';
1216 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST
'], array('addlink
', 'post
', 'edit_link
'));
1217 // Scroll to the link which has been edited.
1218 $location .= '#' . $link['shorturl'];
1219 // After saving the link, redirect to the page the user was on.
1220 header('Location: '. $location);
1224 // -------- User clicked the "Cancel" button when editing a link.
1225 if (isset($_POST['cancel_edit']))
1227 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1228 if (! isset($LINKSDB[$id])) {
1229 header('Location: ?');
1231 // If we are called from the bookmarklet, we must close the popup:
1232 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1233 $link = $LINKSDB[$id];
1234 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1235 // Scroll to the link which has been edited.
1236 $returnurl .= '#'. $link['shorturl'];
1237 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1238 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1242 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1243 if ($targetPage == Router
::$PAGE_DELETELINK)
1245 if (! $sessionManager->checkToken($_GET['token'])) {
1246 die(t('Wrong token.'));
1249 $ids = trim($_GET['lf_linkdate']);
1250 if (strpos($ids, ' ') !== false) {
1251 // multiple, space-separated ids provided
1252 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1254 // only a single id provided
1257 // assert at least one id is given
1259 die('no id provided');
1261 foreach ($ids as $id) {
1262 $id = (int) escape($id);
1263 $link = $LINKSDB[$id];
1264 $pluginManager->executeHooks('delete_link', $link);
1265 unset($LINKSDB[$id]);
1267 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1268 $history->deleteLink($link);
1270 // If we are called from the bookmarklet, we must close the popup:
1271 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1274 if (isset($_SERVER['HTTP_REFERER'])) {
1275 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1276 $location = generateLocation(
1277 $_SERVER['HTTP_REFERER'],
1278 $_SERVER['HTTP_HOST'],
1279 ['delete_link', 'edit_link', $link['shorturl']]
1283 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1287 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1288 if (isset($_GET['edit_link']))
1290 $id = (int) escape($_GET['edit_link']);
1291 $link = $LINKSDB[$id]; // Read database
1292 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
1293 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1296 'link_is_new' => false,
1297 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1298 'tags' => $LINKSDB->linksCountPerTag(),
1300 $pluginManager->executeHooks('render_editlink', $data);
1302 foreach ($data as $key => $value) {
1303 $PAGE->assign($key, $value);
1306 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1307 $PAGE->renderPage('editlink');
1311 // -------- User want to post a new link: Display link edit form.
1312 if (isset($_GET['post'])) {
1313 $url = cleanup_url($_GET['post']);
1315 $link_is_new = false;
1316 // Check if URL is not already in database (in this case, we will edit the existing link)
1317 $link = $LINKSDB->getLinkFromUrl($url);
1320 $link_is_new = true;
1321 $linkdate = strval(date(LinkDB
::LINK_DATE_FORMAT
));
1322 // Get title if it was provided in URL (by the bookmarklet).
1323 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1324 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1325 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1326 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1327 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1328 // If this is an HTTP(S) link, we try go get the page to extract the title (otherwise we will to straight to the edit form.)
1329 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1330 // Short timeout to keep the application responsive
1331 // The callback will fill $charset and $title with data from the downloaded page.
1334 $conf->get('general.download_timeout', 30),
1335 $conf->get('general.download_max_size', 4194304),
1336 get_curl_download_callback($charset, $title)
1338 if (! empty($title) && strtolower($charset) != 'utf-8') {
1339 $title = mb_convert_encoding($title, 'utf-8', $charset);
1344 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1345 $title = $conf->get('general.default_note_title', t('Note: '));
1347 $url = escape($url);
1348 $title = escape($title);
1351 'linkdate' => $linkdate,
1354 'description' => $description,
1356 'private' => $private,
1359 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1364 'link_is_new' => $link_is_new,
1365 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1366 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1367 'tags' => $LINKSDB->linksCountPerTag(),
1368 'default_private_links' => $conf->get('privacy.default_private_links', false),
1370 $pluginManager->executeHooks('render_editlink', $data);
1372 foreach ($data as $key => $value) {
1373 $PAGE->assign($key, $value);
1376 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1377 $PAGE->renderPage('editlink');
1381 if ($targetPage == Router
::$PAGE_EXPORT) {
1382 // Export links as a Netscape Bookmarks file
1384 if (empty($_GET['selection'])) {
1385 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1386 $PAGE->renderPage('export');
1390 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1391 $selection = $_GET['selection'];
1392 if (isset($_GET['prepend_note_url'])) {
1393 $prependNoteUrl = $_GET['prepend_note_url'];
1395 $prependNoteUrl = false;
1401 NetscapeBookmarkUtils
::filterAndFormat(
1408 } catch (Exception
$exc) {
1409 header('Content-Type: text/plain; charset=utf-8');
1410 echo $exc->getMessage();
1413 $now = new DateTime();
1414 header('Content-Type: text/html; charset=utf-8');
1416 'Content-disposition: attachment; filename=bookmarks_'
1417 .$selection.'_'.$now->format(LinkDB
::LINK_DATE_FORMAT
).'.html'
1419 $PAGE->assign('date', $now->format(DateTime
::RFC822
));
1420 $PAGE->assign('eol', PHP_EOL
);
1421 $PAGE->assign('selection', $selection);
1422 $PAGE->renderPage('export.bookmarks');
1426 if ($targetPage == Router
::$PAGE_IMPORT) {
1427 // Upload a Netscape bookmark dump to import its contents
1429 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1430 // Show import dialog
1433 get_max_upload_size(
1434 ini_get('post_max_size'),
1435 ini_get('upload_max_filesize'),
1441 get_max_upload_size(
1442 ini_get('post_max_size'),
1443 ini_get('upload_max_filesize'),
1447 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1448 $PAGE->renderPage('import');
1452 // Import bookmarks from an uploaded file
1453 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1454 // The file is too big or some form field may be missing.
1457 'The file you are trying to upload is probably bigger than what this webserver can accept'
1458 .' (%s). Please upload in smaller chunks.'
1460 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1462 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router
::$PAGE_IMPORT .'\';</script>';
1465 if (! $sessionManager->checkToken($_POST['token'])) {
1466 die('Wrong token.');
1468 $status = NetscapeBookmarkUtils
::import(
1475 echo '<script>alert("'.$status.'");document.location=\'?do='
1476 .Router
::$PAGE_IMPORT .'\';</script>';
1480 // Plugin administration page
1481 if ($targetPage == Router
::$PAGE_PLUGINSADMIN) {
1482 $pluginMeta = $pluginManager->getPluginsMeta();
1484 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1485 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v
['order'] !== false; });
1487 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1490 function($a, $b) { return $a
['order'] - $b
['order']; }
1492 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v
['order'] === false; });
1494 $PAGE->assign('enabledPlugins', $enabledPlugins);
1495 $PAGE->assign('disabledPlugins', $disabledPlugins);
1496 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
1497 $PAGE->renderPage('pluginsadmin');
1501 // Plugin administration form action
1502 if ($targetPage == Router
::$PAGE_SAVE_PLUGINSADMIN) {
1504 if (isset($_POST['parameters_form'])) {
1505 unset($_POST['parameters_form']);
1506 foreach ($_POST as $param => $value) {
1507 $conf->set('plugins.'. $param, escape($value));
1511 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1513 $conf->write($loginManager->isLoggedIn());
1514 $history->updateSettings();
1516 catch (Exception
$e) {
1518 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1522 // TODO: do not handle exceptions/errors in JS.
1523 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router
::$PAGE_PLUGINSADMIN .'\';</script>';
1526 header('Location: ?do='. Router
::$PAGE_PLUGINSADMIN);
1530 // Get a fresh token
1531 if ($targetPage == Router
::$GET_TOKEN) {
1532 header('Content-Type:text/plain');
1533 echo $sessionManager->generateToken($conf);
1537 // -------- Thumbnails Update
1538 if ($targetPage == Router
::$PAGE_THUMBS_UPDATE) {
1540 foreach ($LINKSDB as $link) {
1541 // A note or not HTTP(S)
1542 if ($link['url'][0] === '?' || ! startsWith(strtolower($link['url']), 'http')) {
1545 $ids[] = $link['id'];
1547 $PAGE->assign('ids', $ids);
1548 $PAGE->assign('pagetitle', t('Thumbnails update') .' - '. $conf->get('general.title', 'Shaarli'));
1549 $PAGE->renderPage('thumbnails');
1553 // -------- Single Thumbnail Update
1554 if ($targetPage == Router
::$AJAX_THUMB_UPDATE) {
1555 if (! isset($_POST['id']) || ! ctype_digit($_POST['id'])) {
1556 http_response_code(400);
1559 $id = (int) $_POST['id'];
1560 if (empty($LINKSDB[$id])) {
1561 http_response_code(404);
1564 $thumbnailer = new Thumbnailer($conf);
1565 $link = $LINKSDB[$id];
1566 $link['thumbnail'] = $thumbnailer->get($link['url']);
1567 $LINKSDB[$id] = $link;
1568 $LINKSDB->save($conf->get('resource.page_cache'));
1570 echo json_encode($link);
1574 // -------- Otherwise, simply display search form and links:
1575 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
1580 * Template for the list of links (<div id="linklist">)
1581 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1583 * @param pageBuilder $PAGE pageBuilder instance.
1584 * @param LinkDB $LINKSDB LinkDB instance.
1585 * @param ConfigManager $conf Configuration Manager instance.
1586 * @param PluginManager $pluginManager Plugin Manager instance.
1587 * @param LoginManager $loginManager LoginManager instance
1589 function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1591 // Used in templates
1592 if (isset($_GET['searchtags'])) {
1593 if (! empty($_GET['searchtags'])) {
1594 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1596 $searchtags = false;
1601 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1604 if (! empty($_SERVER['QUERY_STRING'])
1605 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1607 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1608 } catch (LinkNotFoundException
$e) {
1609 $PAGE->render404($e->getMessage());
1613 // Filter links according search parameters.
1614 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
1616 'searchtags' => $searchtags,
1617 'searchterm' => $searchterm,
1619 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
1622 // ---- Handle paging.
1624 foreach ($linksToDisplay as $key => $value) {
1628 // Select articles according to paging.
1629 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1630 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1631 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1632 $page = $page < 1 ? 1 : $page;
1633 $page = $page > $pagecount ? $pagecount : $page;
1635 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1636 $end = $i +
$_SESSION['LINKS_PER_PAGE'];
1638 $thumbnailsEnabled = $conf->get('thumbnails.mode', Thumbnailer
::MODE_NONE
) !== Thumbnailer
::MODE_NONE
;
1639 if ($thumbnailsEnabled) {
1640 $thumbnailer = new Thumbnailer($conf);
1643 $linkDisp = array();
1644 while ($i<$end && $i<count($keys))
1646 $link = $linksToDisplay[$keys[$i]];
1647 $link['description'] = format_description(
1648 $link['description'],
1649 $conf->get('redirector.url'),
1650 $conf->get('redirector.encode_url')
1652 $classLi = ($i %
2) != 0 ? '' : 'publicLinkHightLight';
1653 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
1654 $link['timestamp'] = $link['created']->getTimestamp();
1655 if (! empty($link['updated'])) {
1656 $link['updated_timestamp'] = $link['updated']->getTimestamp();
1658 $link['updated_timestamp'] = '';
1660 $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY
);
1661 uasort($taglist, 'strcasecmp');
1662 $link['taglist'] = $taglist;
1664 // Logged in, thumbnails enabled, not a note,
1665 // and (never retrieved yet or no valid cache file)
1666 if ($loginManager->isLoggedIn() && $thumbnailsEnabled && $link['url'][0] != '?'
1667 && (! isset($link['thumbnail']) || ($link['thumbnail'] !== false && ! is_file($link['thumbnail'])))
1669 $elem = $LINKSDB[$keys[$i]];
1670 $elem['thumbnail'] = $thumbnailer->get($link['url']);
1671 $LINKSDB[$keys[$i]] = $elem;
1673 $link['thumbnail'] = $elem['thumbnail'];
1676 // Check for both signs of a note: starting with ? and 7 chars long.
1677 if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
1678 $link['url'] = index_url($_SERVER) . $link['url'];
1681 $linkDisp[$keys[$i]] = $link;
1685 // If we retrieved new thumbnails, we update the database.
1686 if (!empty($updateDB)) {
1687 $LINKSDB->save($conf->get('resource.page_cache'));
1690 // Compute paging navigation
1691 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
1692 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1693 $previous_page_url = '';
1694 if ($i != count($keys)) {
1695 $previous_page_url = '?page=' . ($page+
1) . $searchtermUrl . $searchtagsUrl;
1699 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1702 // Fill all template fields.
1704 'previous_page_url' => $previous_page_url,
1705 'next_page_url' => $next_page_url,
1706 'page_current' => $page,
1707 'page_max' => $pagecount,
1708 'result_count' => count($linksToDisplay),
1709 'search_term' => $searchterm,
1710 'search_tags' => $searchtags,
1711 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
1712 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
1713 'links' => $linkDisp,
1716 // If there is only a single link, we change on-the-fly the title of the page.
1717 if (count($linksToDisplay) == 1) {
1718 $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
1719 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1720 $data['pagetitle'] = t('Search: ');
1721 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1722 $bracketWrap = function ($tag) {
1723 return '['. $tag .']';
1725 $data['pagetitle'] .= ! empty($searchtags)
1726 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1728 $data['pagetitle'] .= '- '. $conf->get('general.title');
1731 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
1733 foreach ($data as $key => $value) {
1734 $PAGE->assign($key, $value);
1742 * This function should NEVER be called if the file data/config.php exists.
1744 * @param ConfigManager $conf Configuration Manager instance.
1745 * @param SessionManager $sessionManager SessionManager instance
1746 * @param LoginManager $loginManager LoginManager instance
1748 function install($conf, $sessionManager, $loginManager, $userspace) {
1749 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1750 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1753 // This part makes sure sessions works correctly.
1754 // (Because on some hosts, session.save_path may not be set correctly,
1755 // or we may not have write access to it.)
1756 if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working'))
1758 // Step 2: Check if data in session is correct.
1760 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1761 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1762 'and that you have write access to it.<br>'.
1763 'It currently points to %s.<br>'.
1764 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1765 'or any custom hostname without a dot causes cookie storage to fail. '.
1766 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1768 $msg = sprintf($msg, session_save_path());
1770 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1773 if (!isset($_SESSION['session_tested']))
1774 { // Step 1 : Try to store data in session and reload page.
1775 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1776 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1778 if (isset($_GET['test_session']))
1779 { // Step 3: Sessions are OK. Remove test parameter from URL.
1780 header('Location: '.index_url($_SERVER));
1787 if (!empty($_POST['continent']) && !empty($_POST['city'])
1788 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1790 $tz = $_POST['continent'].'/'.$_POST['city'];
1792 $conf->set('general.timezone', $tz);
1793 $conf->set('credentials.login', $userspace);
1794 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1795 $conf->set('credentials.salt', $salt);
1796 $hash = sha1(uniqid('', true) .'_'. mt_rand());
1797 $conf->set('credentials.hash', $hash);
1798 if (!empty($_POST['title'])) {
1799 $conf->set('general.title', escape($_POST['title']));
1801 $conf->set('general.title', ucwords(str_replace("_", " ", $userspace)));
1803 $conf->set('translation.language', escape($_POST['language']));
1804 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1805 $conf->set('api.enabled', !empty($_POST['enableApi']));
1808 generate_api_secret(
1809 $conf->get('credentials.login'),
1810 $conf->get('credentials.salt')
1814 // Everything is ok, let's create config file.
1815 $conf->write($loginManager->isLoggedIn());
1817 catch(Exception
$e) {
1819 'ERROR while writing config file after installation.' . PHP_EOL
.
1823 // TODO: do not handle exceptions/errors in JS.
1824 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1827 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
1831 $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
1832 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1833 $PAGE->assign('continents', $continents);
1834 $PAGE->assign('cities', $cities);
1835 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1836 $PAGE->renderPage('install');
1840 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) {
1841 showDailyRSS($conf, $loginManager);
1845 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
1846 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
1850 $history = new History($conf->get('resource.history'));
1851 } catch(Exception
$e) {
1852 die($e->getMessage());
1855 $linkDb = new LinkDB(
1856 $conf->get('resource.datastore'),
1857 $loginManager->isLoggedIn(),
1858 $conf->get('privacy.hide_public_links'),
1859 $conf->get('redirector.url'),
1860 $conf->get('redirector.encode_url')
1863 $container = new \Slim\
Container();
1864 $container['conf'] = $conf;
1865 $container['plugins'] = $pluginManager;
1866 $container['history'] = $history;
1867 $app = new \Slim\
App($container);
1870 if (isset($userspace)) {
1871 $mountpoint = '/' . $userspace . '/api/v1';
1873 $mountpoint = '/api/v1';
1875 $app->group($mountpoint, function() {
1876 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
1877 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
1878 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
1879 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
1880 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
1881 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
1883 $this->get('/tags', '\Shaarli\Api\Controllers\Tags:getTags')->setName('getTags');
1884 $this->get('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:getTag')->setName('getTag');
1885 $this->put('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:putTag')->setName('putTag');
1886 $this->delete('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:deleteTag')->setName('deleteTag');
1888 $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
1889 })->add('\Shaarli\Api\ApiMiddleware');
1891 $response = $app->run(true);
1892 // Hack to make Slim and Shaarli router work together:
1893 // If a Slim route isn't found and NOT API call, we call renderPage().
1894 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], $mountpoint) === false) {
1895 // We use UTF-8 for proper international characters handling.
1896 header('Content-Type: text/html; charset=utf-8');
1897 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
1899 $app->respond($response);