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\Languages
;
79 use \Shaarli\ThemeUtils
;
80 use \Shaarli\Config\ConfigManager
;
81 use \Shaarli\Security\LoginManager
;
82 use \Shaarli\Security\SessionManager
;
84 // Ensure the PHP version is supported
86 ApplicationUtils
::checkPHPVersion('5.5', PHP_VERSION
);
87 } catch(Exception
$exc) {
88 header('Content-Type: text/plain; charset=utf-8');
89 echo $exc->getMessage();
93 define('SHAARLI_VERSION', ApplicationUtils
::getVersion(__DIR__
.'/'. ApplicationUtils
::$VERSION_FILE));
95 // Force cookie path (but do not change lifetime)
96 $cookie = session_get_cookie_params();
98 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
99 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
101 // Set default cookie expiration and path.
102 session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
103 // Set session parameters on server side.
104 // Use cookies to store session.
105 ini_set('session.use_cookies', 1);
106 // Force cookies for session (phpsessionID forbidden in URL).
107 ini_set('session.use_only_cookies', 1);
108 // Prevent PHP form using sessionID in URL if cookies are disabled.
109 ini_set('session.use_trans_sid', false);
111 session_name('shaarli');
112 // Start session if needed (Some server auto-start sessions).
113 if (session_id() == '') {
117 // Regenerate session ID if invalid or not defined in cookie.
118 if (isset($_COOKIE['shaarli']) && !SessionManager
::checkId($_COOKIE['shaarli'])) {
119 session_regenerate_id(true);
120 $_COOKIE['shaarli'] = session_id();
123 $conf = new ConfigManager();
124 $sessionManager = new SessionManager($_SESSION, $conf);
125 $loginManager = new LoginManager($GLOBALS, $conf, $sessionManager);
126 $loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
127 $clientIpId = client_ip_id($_SERVER);
129 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
130 if (! defined('LC_MESSAGES')) {
131 define('LC_MESSAGES', LC_COLLATE
);
134 // Sniff browser language and set date format accordingly.
135 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
136 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
139 new Languages(setlocale(LC_MESSAGES
, 0), $conf);
141 $conf->setEmpty('general.timezone', date_default_timezone_get());
142 $conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
143 RainTPL
::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
144 RainTPL
::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
146 $pluginManager = new PluginManager($conf);
147 $pluginManager->load($conf->get('general.enabled_plugins'));
149 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
151 ob_start(); // Output buffering for the page cache.
153 // Prevent caching on client side or proxy: (yes, it's ugly)
154 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
155 header("Cache-Control: no-store, no-cache, must-revalidate");
156 header("Cache-Control: post-check=0, pre-check=0", false);
157 header("Pragma: no-cache");
159 if (! is_file($conf->getConfigFileExt())) {
160 // Ensure Shaarli has proper access to its resources
161 $errors = ApplicationUtils
::checkResourcePermissions($conf);
163 if ($errors != array()) {
164 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
166 foreach ($errors as $error) {
167 $message .= '<li>'.$error.'</li>';
171 header('Content-Type: text/html; charset=utf-8');
176 // Display the installation form if no existing config is found
177 install($conf, $sessionManager, $loginManager);
180 $loginManager->checkLoginState($_COOKIE, $clientIpId);
183 * Adapter function to ensure compatibility with third-party templates
185 * @see https://github.com/shaarli/Shaarli/pull/1086
187 * @return bool true when the user is logged in, false otherwise
189 function isLoggedIn()
191 global $loginManager;
192 return $loginManager->isLoggedIn();
196 // ------------------------------------------------------------------------------------------
197 // Process login form: Check if login/password is correct.
198 if (isset($_POST['login'])) {
199 if (! $loginManager->canLogin($_SERVER)) {
200 die(t('I said: NO. You are banned for the moment. Go away.'));
202 if (isset($_POST['password'])
203 && $sessionManager->checkToken($_POST['token'])
204 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
206 $loginManager->handleSuccessfulLogin($_SERVER);
209 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
210 // Note: Never forget the trailing slash on the cookie path!
211 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
214 if (!empty($_POST['longlastingsession'])) {
215 // Keep the session cookie even after the browser closes
216 $sessionManager->setStaySignedIn(true);
217 $expirationTime = $sessionManager->extendSession();
220 $loginManager::$STAY_SIGNED_IN_COOKIE,
221 $loginManager->getStaySignedInToken(),
227 // Standard session expiration (=when browser closes)
231 // Send cookie with the new expiration date to the browser
232 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
233 session_regenerate_id(true);
235 // Optional redirect after login:
236 if (isset($_GET['post'])) {
237 $uri = '?post='. urlencode($_GET['post']);
238 foreach (array('description', 'source', 'title', 'tags') as $param) {
239 if (!empty($_GET[$param])) {
240 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
243 header('Location: '. $uri);
247 if (isset($_GET['edit_link'])) {
248 header('Location: ?edit_link='. escape($_GET['edit_link']));
252 if (isset($_POST['returnurl'])) {
253 // Prevent loops over login screen.
254 if (strpos($_POST['returnurl'], 'do=login') === false) {
255 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
259 header('Location: ?'); exit;
261 $loginManager->handleFailedLogin($_SERVER);
262 $redir = '&username='. urlencode($_POST['login']);
263 if (isset($_GET['post'])) {
264 $redir .= '&post=' . urlencode($_GET['post']);
265 foreach (array('description', 'source', 'title', 'tags') as $param) {
266 if (!empty($_GET[$param])) {
267 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
271 // Redirect to login screen.
272 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
277 // ------------------------------------------------------------------------------------------
278 // Token management for XSRF protection
279 // Token should be used in any form which acts on data (create,update,delete,import...).
280 if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
283 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
284 * Gives the last 7 days (which have links).
285 * This RSS feed cannot be filtered.
287 * @param ConfigManager $conf Configuration Manager instance
288 * @param LoginManager $loginManager LoginManager instance
290 function showDailyRSS($conf, $loginManager) {
292 $query = $_SERVER['QUERY_STRING'];
293 $cache = new CachedPage(
294 $conf->get('config.PAGE_CACHE'),
296 startsWith($query,'do=dailyrss') && !$loginManager->isLoggedIn()
298 $cached = $cache->cachedVersion();
299 if (!empty($cached)) {
304 // If cached was not found (or not usable), then read the database and build the response:
305 // Read links from database (and filter private links if used it not logged in).
306 $LINKSDB = new LinkDB(
307 $conf->get('resource.datastore'),
308 $loginManager->isLoggedIn(),
309 $conf->get('privacy.hide_public_links'),
310 $conf->get('redirector.url'),
311 $conf->get('redirector.encode_url')
314 /* Some Shaarlies may have very few links, so we need to look
315 back in time until we have enough days ($nb_of_days).
317 $nb_of_days = 7; // We take 7 days.
318 $today = date('Ymd');
321 foreach ($LINKSDB as $link) {
322 $day = $link['created']->format('Ymd'); // Extract day (without time)
323 if (strcmp($day, $today) < 0) {
324 if (empty($days[$day])) {
325 $days[$day] = array();
327 $days[$day][] = $link;
330 if (count($days) > $nb_of_days) {
331 break; // Have we collected enough days?
335 // Build the RSS feed.
336 header('Content-Type: application/rss+xml; charset=utf-8');
337 $pageaddr = escape(index_url($_SERVER));
338 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
340 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
341 echo '<link>'. $pageaddr .'</link>';
342 echo '<description>Daily shared links</description>';
343 echo '<language>en-en</language>';
344 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL
;
347 foreach ($days as $day => $links) {
348 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
349 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
351 // We pre-format some fields for proper output.
352 foreach ($links as &$link) {
353 $link['formatedDescription'] = format_description(
354 $link['description'],
355 $conf->get('redirector.url'),
356 $conf->get('redirector.encode_url')
358 $link['thumbnail'] = thumbnail($conf, $link['url']);
359 $link['timestamp'] = $link['created']->getTimestamp();
360 if (startsWith($link['url'], '?')) {
361 $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
365 // Then build the HTML for this day:
367 $tpl->assign('title', $conf->get('general.title'));
368 $tpl->assign('daydate', $dayDate->getTimestamp());
369 $tpl->assign('absurl', $absurl);
370 $tpl->assign('links', $links);
371 $tpl->assign('rssdate', escape($dayDate->format(DateTime
::RSS
)));
372 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
373 $html = $tpl->draw('dailyrss', true);
375 echo $html . PHP_EOL
;
377 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
379 $cache->cache(ob_get_contents());
385 * Show the 'Daily' page.
387 * @param PageBuilder $pageBuilder Template engine wrapper.
388 * @param LinkDB $LINKSDB LinkDB instance.
389 * @param ConfigManager $conf Configuration Manager instance.
390 * @param PluginManager $pluginManager Plugin Manager instance.
391 * @param LoginManager $loginManager Login Manager instance
393 function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
395 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
396 if (isset($_GET['day'])) {
400 $days = $LINKSDB->days();
401 $i = array_search($day, $days);
402 if ($i === false && count($days)) {
403 // no links for day, but at least one day with links
404 $i = count($days) - 1;
412 $previousday=$days[$i - 1];
414 if ($i < count($days) - 1) {
415 $nextday = $days[$i +
1];
419 $linksToDisplay = $LINKSDB->filterDay($day);
420 } catch (Exception
$exc) {
422 $linksToDisplay = array();
425 // We pre-format some fields for proper output.
426 foreach($linksToDisplay as $key => $link) {
427 $taglist = explode(' ',$link['tags']);
428 uasort($taglist, 'strcasecmp');
429 $linksToDisplay[$key]['taglist']=$taglist;
430 $linksToDisplay[$key]['formatedDescription'] = format_description(
431 $link['description'],
432 $conf->get('redirector.url'),
433 $conf->get('redirector.encode_url')
435 $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
436 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
439 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
441 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
442 'linksToDisplay' => $linksToDisplay,
443 'day' => $dayDate->getTimestamp(),
444 'dayDate' => $dayDate,
445 'previousday' => $previousday,
446 'nextday' => $nextday,
449 /* Hook is called before column construction so that plugins don't have
450 to deal with columns. */
451 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
453 /* We need to spread the articles on 3 columns.
454 I did not want to use a JavaScript lib like http://masonry.desandro.com/
455 so I manually spread entries with a simple method: I roughly evaluate the
456 height of a div according to title and description length.
458 $columns = array(array(), array(), array()); // Entries to display, for each column.
459 $fill = array(0, 0, 0); // Rough estimate of columns fill.
460 foreach($data['linksToDisplay'] as $key => $link) {
461 // Roughly estimate length of entry (by counting characters)
462 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
463 // Description: 836 characters gives roughly 342 pixel height.
464 // This is not perfect, but it's usually OK.
465 $length = strlen($link['title']) +
(342 * strlen($link['description'])) / 836;
466 if ($link['thumbnail']) {
467 $length +
= 100; // 1 thumbnails roughly takes 100 pixels height.
469 // Then put in column which is the less filled:
470 $smallest = min($fill); // find smallest value in array.
471 $index = array_search($smallest, $fill); // find index of this smallest value.
472 array_push($columns[$index], $link); // Put entry in this column.
473 $fill[$index] +
= $length;
476 $data['cols'] = $columns;
478 foreach ($data as $key => $value) {
479 $pageBuilder->assign($key, $value);
482 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
483 $pageBuilder->renderPage('daily');
488 * Renders the linklist
490 * @param pageBuilder $PAGE pageBuilder instance.
491 * @param LinkDB $LINKSDB LinkDB instance.
492 * @param ConfigManager $conf Configuration Manager instance.
493 * @param PluginManager $pluginManager Plugin Manager instance.
495 function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager) {
496 buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager, $loginManager);
497 $PAGE->renderPage('linklist');
501 * Render HTML page (according to URL parameters and user rights)
503 * @param ConfigManager $conf Configuration Manager instance.
504 * @param PluginManager $pluginManager Plugin Manager instance,
505 * @param LinkDB $LINKSDB
506 * @param History $history instance
507 * @param SessionManager $sessionManager SessionManager instance
508 * @param LoginManager $loginManager LoginManager instance
510 function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
512 $updater = new Updater(
513 read_updates_file($conf->get('resource.updates')),
516 $loginManager->isLoggedIn()
519 $newUpdates = $updater->update();
520 if (! empty($newUpdates)) {
522 $conf->get('resource.updates'),
523 $updater->getDoneUpdates()
527 catch(Exception
$e) {
528 die($e->getMessage());
531 $PAGE = new PageBuilder($conf, $LINKSDB, $sessionManager->generateToken(), $loginManager->isLoggedIn());
532 $PAGE->assign('linkcount', count($LINKSDB));
533 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
534 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
536 // Determine which page will be rendered.
537 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
538 $targetPage = Router
::findPage($query, $_GET, $loginManager->isLoggedIn());
541 // if the user isn't logged in
542 !$loginManager->isLoggedIn() &&
543 // and Shaarli doesn't have public content...
544 $conf->get('privacy.hide_public_links') &&
545 // and is configured to enforce the login
546 $conf->get('privacy.force_login') &&
547 // and the current page isn't already the login page
548 $targetPage !== Router
::$PAGE_LOGIN &&
549 // and the user is not requesting a feed (which would lead to a different content-type as expected)
550 $targetPage !== Router
::$PAGE_FEED_ATOM &&
551 $targetPage !== Router
::$PAGE_FEED_RSS
553 // force current page to be the login page
554 $targetPage = Router
::$PAGE_LOGIN;
557 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
558 // Then assign generated data to RainTPL.
559 $common_hooks = array(
565 foreach($common_hooks as $name) {
566 $plugin_data = array();
567 $pluginManager->executeHooks('render_' . $name, $plugin_data,
569 'target' => $targetPage,
570 'loggedin' => $loginManager->isLoggedIn()
573 $PAGE->assign('plugins_' . $name, $plugin_data);
576 // -------- Display login form.
577 if ($targetPage == Router
::$PAGE_LOGIN)
579 if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
580 if (isset($_GET['username'])) {
581 $PAGE->assign('username', escape($_GET['username']));
583 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
584 // add default state of the 'remember me' checkbox
585 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
586 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
587 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
588 $PAGE->renderPage('loginform');
591 // -------- User wants to logout.
592 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
594 invalidateCaches($conf->get('resource.page_cache'));
595 $sessionManager->logout();
596 setcookie(LoginManager
::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH
);
597 header('Location: ?');
601 // -------- Picture wall
602 if ($targetPage == Router
::$PAGE_PICWALL)
604 // Optionally filter the results:
605 $links = $LINKSDB->filterSearch($_GET);
606 $linksToDisplay = array();
608 // Get only links which have a thumbnail.
609 foreach($links as $link)
611 $permalink='?'.$link['shorturl'];
612 $thumb=lazyThumbnail($conf, $link['url'],$permalink);
613 if ($thumb!='') // Only output links which have a thumbnail.
615 $link['thumbnail']=$thumb; // Thumbnail HTML code.
616 $linksToDisplay[]=$link; // Add to array.
621 'linksToDisplay' => $linksToDisplay,
623 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => $loginManager->isLoggedIn()));
625 foreach ($data as $key => $value) {
626 $PAGE->assign($key, $value);
629 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
630 $PAGE->renderPage('picwall');
634 // -------- Tag cloud
635 if ($targetPage == Router
::$PAGE_TAGCLOUD)
637 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
638 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
639 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
641 // We sort tags alphabetically, then choose a font size according to count.
642 // First, find max value.
644 foreach ($tags as $value) {
645 $maxcount = max($maxcount, $value);
648 alphabetical_sort($tags, false, true);
651 foreach($tags as $key => $value) {
652 if (in_array($key, $filteringTags)) {
655 // Tag font size scaling:
656 // default 15 and 30 logarithm bases affect scaling,
657 // 22 and 6 are arbitrary font sizes for max and min sizes.
658 $size = log($value, 15) / log($maxcount, 30) * 2.2 +
0.8;
659 $tagList[$key] = array(
661 'size' => number_format($size, 2, '.', ''),
665 $searchTags = implode(' ', escape($filteringTags));
667 'search_tags' => $searchTags,
670 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
672 foreach ($data as $key => $value) {
673 $PAGE->assign($key, $value);
676 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
677 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
678 $PAGE->renderPage('tag.cloud');
683 if ($targetPage == Router
::$PAGE_TAGLIST)
685 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
686 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
687 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
688 foreach ($filteringTags as $tag) {
689 if (array_key_exists($tag, $tags)) {
694 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
695 alphabetical_sort($tags, false, true);
698 $searchTags = implode(' ', escape($filteringTags));
700 'search_tags' => $searchTags,
703 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
705 foreach ($data as $key => $value) {
706 $PAGE->assign($key, $value);
709 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
710 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
711 $PAGE->renderPage('tag.list');
716 if ($targetPage == Router
::$PAGE_DAILY) {
717 showDaily($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
720 // ATOM and RSS feed.
721 if ($targetPage == Router
::$PAGE_FEED_ATOM || $targetPage == Router
::$PAGE_FEED_RSS) {
722 $feedType = $targetPage == Router
::$PAGE_FEED_RSS ? FeedBuilder
::$FEED_RSS : FeedBuilder
::$FEED_ATOM;
723 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
726 $query = $_SERVER['QUERY_STRING'];
727 $cache = new CachedPage(
728 $conf->get('resource.page_cache'),
730 startsWith($query,'do='. $targetPage) && !$loginManager->isLoggedIn()
732 $cached = $cache->cachedVersion();
733 if (!empty($cached)) {
739 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, $loginManager->isLoggedIn());
740 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE
, 0)));
741 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
742 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
743 $data = $feedGenerator->buildData();
745 // Process plugin hook.
746 $pluginManager->executeHooks('render_feed', $data, array(
747 'loggedin' => $loginManager->isLoggedIn(),
748 'target' => $targetPage,
751 // Render the template.
752 $PAGE->assignAll($data);
753 $PAGE->renderPage('feed.'. $feedType);
754 $cache->cache(ob_get_contents());
759 // Display opensearch plugin (XML)
760 if ($targetPage == Router
::$PAGE_OPENSEARCH) {
761 header('Content-Type: application/xml; charset=utf-8');
762 $PAGE->assign('serverurl', index_url($_SERVER));
763 $PAGE->renderPage('opensearch');
767 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
768 if (isset($_GET['addtag']))
770 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
771 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET
['addtag'])); exit; } // In case browser does not send HTTP_REFERER
772 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY
), $params);
774 // Prevent redirection loop
775 if (isset($params['addtag'])) {
776 unset($params['addtag']);
779 // Check if this tag is already in the search query and ignore it if it is.
780 // Each tag is always separated by a space
781 if (isset($params['searchtags'])) {
782 $current_tags = explode(' ', $params['searchtags']);
784 $current_tags = array();
787 foreach ($current_tags as $value) {
788 if ($value === $_GET['addtag']) {
793 // Append the tag if necessary
794 if (empty($params['searchtags'])) {
795 $params['searchtags'] = trim($_GET['addtag']);
798 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
801 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
802 header('Location: ?'.http_build_query($params));
806 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
807 if (isset($_GET['removetag'])) {
808 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
809 if (empty($_SERVER['HTTP_REFERER'])) {
810 header('Location: ?');
814 // In case browser does not send HTTP_REFERER
815 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
817 // Prevent redirection loop
818 if (isset($params['removetag'])) {
819 unset($params['removetag']);
822 if (isset($params['searchtags'])) {
823 $tags = explode(' ', $params['searchtags']);
824 // Remove value from array $tags.
825 $tags = array_diff($tags, array($_GET['removetag']));
826 $params['searchtags'] = implode(' ',$tags);
828 if (empty($params['searchtags'])) {
829 unset($params['searchtags']);
832 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
834 header('Location: ?'.http_build_query($params));
838 // -------- User wants to change the number of links per page (linksperpage=...)
839 if (isset($_GET['linksperpage'])) {
840 if (is_numeric($_GET['linksperpage'])) {
841 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
844 if (! empty($_SERVER['HTTP_REFERER'])) {
845 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
849 header('Location: '. $location);
853 // -------- User wants to see only private links (toggle)
854 if (isset($_GET['visibility'])) {
855 if ($_GET['visibility'] === 'private') {
856 // Visibility not set or not already private, set private, otherwise reset it
857 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
858 // See only private links
859 $_SESSION['visibility'] = 'private';
861 unset($_SESSION['visibility']);
863 } elseif ($_GET['visibility'] === 'public') {
864 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
865 // See only public links
866 $_SESSION['visibility'] = 'public';
868 unset($_SESSION['visibility']);
872 if (! empty($_SERVER['HTTP_REFERER'])) {
873 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
877 header('Location: '. $location);
881 // -------- User wants to see only untagged links (toggle)
882 if (isset($_GET['untaggedonly'])) {
883 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
885 if (! empty($_SERVER['HTTP_REFERER'])) {
886 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
890 header('Location: '. $location);
894 // -------- Handle other actions allowed for non-logged in users:
895 if (!$loginManager->isLoggedIn())
897 // User tries to post new link but is not logged in:
898 // Show login screen, then redirect to ?post=...
899 if (isset($_GET['post']))
901 header( // Redirect to login page, then back to post link.
902 'Location: ?do=login&post='.urlencode($_GET['post']).
903 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
904 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
905 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
906 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
911 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
912 if (isset($_GET['edit_link'])) {
913 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
917 exit; // Never remove this one! All operations below are reserved for logged in user.
920 // -------- All other functions are reserved for the registered user:
922 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
923 if ($targetPage == Router
::$PAGE_TOOLS)
926 'pageabsaddr' => index_url($_SERVER),
927 'sslenabled' => is_https($_SERVER),
929 $pluginManager->executeHooks('render_tools', $data);
931 foreach ($data as $key => $value) {
932 $PAGE->assign($key, $value);
935 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
936 $PAGE->renderPage('tools');
940 // -------- User wants to change his/her password.
941 if ($targetPage == Router
::$PAGE_CHANGEPASSWORD)
943 if ($conf->get('security.open_shaarli')) {
944 die(t('You are not supposed to change a password on an Open Shaarli.'));
947 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
949 if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away!
951 // Make sure old password is correct.
952 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
953 if ($oldhash!= $conf->get('credentials.hash')) {
954 echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>';
958 // Salt renders rainbow-tables attacks useless.
959 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
960 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt')));
962 $conf->write($loginManager->isLoggedIn());
964 catch(Exception
$e) {
966 'ERROR while writing config file after changing password.' . PHP_EOL
.
970 // TODO: do not handle exceptions/errors in JS.
971 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
974 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
977 else // show the change password form.
979 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
980 $PAGE->renderPage('changepassword');
985 // -------- User wants to change configuration
986 if ($targetPage == Router
::$PAGE_CONFIGURE)
988 if (!empty($_POST['title']) )
990 if (!$sessionManager->checkToken($_POST['token'])) {
991 die(t('Wrong token.')); // Go away!
994 if (!empty($_POST['continent']) && !empty($_POST['city'])
995 && isTimeZoneValid($_POST['continent'], $_POST['city'])
997 $tz = $_POST['continent'] . '/' . $_POST['city'];
999 $conf->set('general.timezone', $tz);
1000 $conf->set('general.title', escape($_POST['title']));
1001 $conf->set('general.header_link', escape($_POST['titleLink']));
1002 $conf->set('resource.theme', escape($_POST['theme']));
1003 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
1004 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
1005 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1006 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1007 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
1008 $conf->set('api.enabled', !empty($_POST['enableApi']));
1009 $conf->set('api.secret', escape($_POST['apiSecret']));
1010 $conf->set('translation.language', escape($_POST['language']));
1013 $conf->write($loginManager->isLoggedIn());
1014 $history->updateSettings();
1015 invalidateCaches($conf->get('resource.page_cache'));
1017 catch(Exception
$e) {
1019 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1023 // TODO: do not handle exceptions/errors in JS.
1024 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1027 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1030 else // Show the configuration form.
1032 $PAGE->assign('title', $conf->get('general.title'));
1033 $PAGE->assign('theme', $conf->get('resource.theme'));
1034 $PAGE->assign('theme_available', ThemeUtils
::getThemes($conf->get('resource.raintpl_tpl')));
1035 list($continents, $cities) = generateTimeZoneData(
1036 timezone_identifiers_list(),
1037 $conf->get('general.timezone')
1039 $PAGE->assign('continents', $continents);
1040 $PAGE->assign('cities', $cities);
1041 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
1042 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1043 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1044 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1045 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1046 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1047 $PAGE->assign('api_secret', $conf->get('api.secret'));
1048 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1049 $PAGE->assign('language', $conf->get('translation.language'));
1050 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
1051 $PAGE->renderPage('configure');
1056 // -------- User wants to rename a tag or delete it
1057 if ($targetPage == Router
::$PAGE_CHANGETAG)
1059 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1060 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1061 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
1062 $PAGE->renderPage('changetag');
1066 if (!$sessionManager->checkToken($_POST['token'])) {
1067 die(t('Wrong token.'));
1070 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), escape($_POST['totag']));
1071 $LINKSDB->save($conf->get('resource.page_cache'));
1072 foreach ($alteredLinks as $link) {
1073 $history->updateLink($link);
1075 $delete = empty($_POST['totag']);
1076 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1077 $count = count($alteredLinks);
1079 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d links.', $count), $count)
1080 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d links.', $count), $count);
1081 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1085 // -------- User wants to add a link without using the bookmarklet: Show form.
1086 if ($targetPage == Router
::$PAGE_ADDLINK)
1088 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1089 $PAGE->renderPage('addlink');
1093 // -------- User clicked the "Save" button when editing a link: Save link to database.
1094 if (isset($_POST['save_edit']))
1097 if (! $sessionManager->checkToken($_POST['token'])) {
1098 die(t('Wrong token.'));
1101 // lf_id should only be present if the link exists.
1102 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
1103 // Linkdate is kept here to:
1104 // - use the same permalink for notes as they're displayed when creating them
1105 // - let users hack creation date of their posts
1106 // See: https://shaarli.readthedocs.io/en/master/Various-hacks/#changing-the-timestamp-for-a-shaare
1107 $linkdate = escape($_POST['lf_linkdate']);
1108 if (isset($LINKSDB[$id])) {
1110 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1111 $updated = new DateTime();
1112 $shortUrl = $LINKSDB[$id]['shorturl'];
1116 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1118 $shortUrl = link_small_hash($created, $id);
1122 // Remove multiple spaces.
1123 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
1124 // Remove first '-' char in tags.
1125 $tags = preg_replace('/(^| )\-/', '$1', $tags);
1126 // Remove duplicates.
1127 $tags = implode(' ', array_unique(explode(' ', $tags)));
1129 if (empty(trim($_POST['lf_url
']))) {
1130 $_POST['lf_url
'] = '?' . smallHash($linkdate . $id);
1132 $url = whitelist_protocols(trim($_POST['lf_url
']), $conf->get('security
.allowed_protocols
'));
1136 'title
' => trim($_POST['lf_title
']),
1138 'description
' => $_POST['lf_description
'],
1139 'private' => (isset($_POST['lf_private
']) ? 1 : 0),
1140 'created
' => $created,
1141 'updated
' => $updated,
1142 'tags
' => str_replace(',', ' ', $tags),
1143 'shorturl
' => $shortUrl,
1146 // If title is empty, use the URL as title.
1147 if ($link['title
'] == '') {
1148 $link['title
'] = $link['url
'];
1151 $pluginManager->executeHooks('save_link
', $link);
1153 $LINKSDB[$id] = $link;
1154 $LINKSDB->save($conf->get('resource.page_cache
'));
1156 $history->addLink($link);
1158 $history->updateLink($link);
1161 // If we are called from the bookmarklet, we must close the popup:
1162 if (isset($_GET['source
']) && ($_GET['source
']=='bookmarklet
' || $_GET['source
']=='firefoxsocialapi
')) {
1163 echo '<script
>self
.close();</script
>';
1167 $returnurl = !empty($_POST['returnurl
']) ? $_POST['returnurl
'] : '?';
1168 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST
'], array('addlink
', 'post
', 'edit_link
'));
1169 // Scroll to the link which has been edited.
1170 $location .= '#' . $link['shorturl'];
1171 // After saving the link, redirect to the page the user was on.
1172 header('Location: '. $location);
1176 // -------- User clicked the "Cancel" button when editing a link.
1177 if (isset($_POST['cancel_edit']))
1179 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1180 if (! isset($LINKSDB[$id])) {
1181 header('Location: ?');
1183 // If we are called from the bookmarklet, we must close the popup:
1184 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1185 $link = $LINKSDB[$id];
1186 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1187 // Scroll to the link which has been edited.
1188 $returnurl .= '#'. $link['shorturl'];
1189 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1190 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1194 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1195 if ($targetPage == Router
::$PAGE_DELETELINK)
1197 if (! $sessionManager->checkToken($_GET['token'])) {
1198 die(t('Wrong token.'));
1201 $ids = trim($_GET['lf_linkdate']);
1202 if (strpos($ids, ' ') !== false) {
1203 // multiple, space-separated ids provided
1204 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1206 // only a single id provided
1209 // assert at least one id is given
1211 die('no id provided');
1213 foreach ($ids as $id) {
1214 $id = (int) escape($id);
1215 $link = $LINKSDB[$id];
1216 $pluginManager->executeHooks('delete_link', $link);
1217 unset($LINKSDB[$id]);
1219 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1220 $history->deleteLink($link);
1222 // If we are called from the bookmarklet, we must close the popup:
1223 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1226 if (isset($_SERVER['HTTP_REFERER'])) {
1227 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1228 $location = generateLocation(
1229 $_SERVER['HTTP_REFERER'],
1230 $_SERVER['HTTP_HOST'],
1231 ['delete_link', 'edit_link', $link['shorturl']]
1235 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1239 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1240 if (isset($_GET['edit_link']))
1242 $id = (int) escape($_GET['edit_link']);
1243 $link = $LINKSDB[$id]; // Read database
1244 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
1245 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1248 'link_is_new' => false,
1249 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1250 'tags' => $LINKSDB->linksCountPerTag(),
1252 $pluginManager->executeHooks('render_editlink', $data);
1254 foreach ($data as $key => $value) {
1255 $PAGE->assign($key, $value);
1258 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1259 $PAGE->renderPage('editlink');
1263 // -------- User want to post a new link: Display link edit form.
1264 if (isset($_GET['post'])) {
1265 $url = cleanup_url($_GET['post']);
1267 $link_is_new = false;
1268 // Check if URL is not already in database (in this case, we will edit the existing link)
1269 $link = $LINKSDB->getLinkFromUrl($url);
1272 $link_is_new = true;
1273 $linkdate = strval(date(LinkDB
::LINK_DATE_FORMAT
));
1274 // Get title if it was provided in URL (by the bookmarklet).
1275 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1276 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1277 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1278 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1279 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1280 // 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.)
1281 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1282 // Short timeout to keep the application responsive
1283 // The callback will fill $charset and $title with data from the downloaded page.
1286 $conf->get('general.download_timeout', 30),
1287 $conf->get('general.download_max_size', 4194304),
1288 get_curl_download_callback($charset, $title)
1290 if (! empty($title) && strtolower($charset) != 'utf-8') {
1291 $title = mb_convert_encoding($title, 'utf-8', $charset);
1296 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1297 $title = $conf->get('general.default_note_title', t('Note: '));
1299 $url = escape($url);
1300 $title = escape($title);
1303 'linkdate' => $linkdate,
1306 'description' => $description,
1308 'private' => $private,
1311 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1316 'link_is_new' => $link_is_new,
1317 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1318 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1319 'tags' => $LINKSDB->linksCountPerTag(),
1320 'default_private_links' => $conf->get('privacy.default_private_links', false),
1322 $pluginManager->executeHooks('render_editlink', $data);
1324 foreach ($data as $key => $value) {
1325 $PAGE->assign($key, $value);
1328 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1329 $PAGE->renderPage('editlink');
1333 if ($targetPage == Router
::$PAGE_EXPORT) {
1334 // Export links as a Netscape Bookmarks file
1336 if (empty($_GET['selection'])) {
1337 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1338 $PAGE->renderPage('export');
1342 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1343 $selection = $_GET['selection'];
1344 if (isset($_GET['prepend_note_url'])) {
1345 $prependNoteUrl = $_GET['prepend_note_url'];
1347 $prependNoteUrl = false;
1353 NetscapeBookmarkUtils
::filterAndFormat(
1360 } catch (Exception
$exc) {
1361 header('Content-Type: text/plain; charset=utf-8');
1362 echo $exc->getMessage();
1365 $now = new DateTime();
1366 header('Content-Type: text/html; charset=utf-8');
1368 'Content-disposition: attachment; filename=bookmarks_'
1369 .$selection.'_'.$now->format(LinkDB
::LINK_DATE_FORMAT
).'.html'
1371 $PAGE->assign('date', $now->format(DateTime
::RFC822
));
1372 $PAGE->assign('eol', PHP_EOL
);
1373 $PAGE->assign('selection', $selection);
1374 $PAGE->renderPage('export.bookmarks');
1378 if ($targetPage == Router
::$PAGE_IMPORT) {
1379 // Upload a Netscape bookmark dump to import its contents
1381 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1382 // Show import dialog
1385 get_max_upload_size(
1386 ini_get('post_max_size'),
1387 ini_get('upload_max_filesize'),
1393 get_max_upload_size(
1394 ini_get('post_max_size'),
1395 ini_get('upload_max_filesize'),
1399 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1400 $PAGE->renderPage('import');
1404 // Import bookmarks from an uploaded file
1405 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1406 // The file is too big or some form field may be missing.
1409 'The file you are trying to upload is probably bigger than what this webserver can accept'
1410 .' (%s). Please upload in smaller chunks.'
1412 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1414 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router
::$PAGE_IMPORT .'\';</script>';
1417 if (! $sessionManager->checkToken($_POST['token'])) {
1418 die('Wrong token.');
1420 $status = NetscapeBookmarkUtils
::import(
1427 echo '<script>alert("'.$status.'");document.location=\'?do='
1428 .Router
::$PAGE_IMPORT .'\';</script>';
1432 // Plugin administration page
1433 if ($targetPage == Router
::$PAGE_PLUGINSADMIN) {
1434 $pluginMeta = $pluginManager->getPluginsMeta();
1436 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1437 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v
['order'] !== false; });
1439 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1442 function($a, $b) { return $a
['order'] - $b
['order']; }
1444 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v
['order'] === false; });
1446 $PAGE->assign('enabledPlugins', $enabledPlugins);
1447 $PAGE->assign('disabledPlugins', $disabledPlugins);
1448 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
1449 $PAGE->renderPage('pluginsadmin');
1453 // Plugin administration form action
1454 if ($targetPage == Router
::$PAGE_SAVE_PLUGINSADMIN) {
1456 if (isset($_POST['parameters_form'])) {
1457 unset($_POST['parameters_form']);
1458 foreach ($_POST as $param => $value) {
1459 $conf->set('plugins.'. $param, escape($value));
1463 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1465 $conf->write($loginManager->isLoggedIn());
1466 $history->updateSettings();
1468 catch (Exception
$e) {
1470 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1474 // TODO: do not handle exceptions/errors in JS.
1475 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router
::$PAGE_PLUGINSADMIN .'\';</script>';
1478 header('Location: ?do='. Router
::$PAGE_PLUGINSADMIN);
1482 // Get a fresh token
1483 if ($targetPage == Router
::$GET_TOKEN) {
1484 header('Content-Type:text/plain');
1485 echo $sessionManager->generateToken($conf);
1489 // -------- Otherwise, simply display search form and links:
1490 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
1495 * Template for the list of links (<div id="linklist">)
1496 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1498 * @param pageBuilder $PAGE pageBuilder instance.
1499 * @param LinkDB $LINKSDB LinkDB instance.
1500 * @param ConfigManager $conf Configuration Manager instance.
1501 * @param PluginManager $pluginManager Plugin Manager instance.
1502 * @param LoginManager $loginManager LoginManager instance
1504 function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1506 // Used in templates
1507 if (isset($_GET['searchtags'])) {
1508 if (! empty($_GET['searchtags'])) {
1509 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1511 $searchtags = false;
1516 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1519 if (! empty($_SERVER['QUERY_STRING'])
1520 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1522 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1523 } catch (LinkNotFoundException
$e) {
1524 $PAGE->render404($e->getMessage());
1528 // Filter links according search parameters.
1529 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
1531 'searchtags' => $searchtags,
1532 'searchterm' => $searchterm,
1534 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
1537 // ---- Handle paging.
1539 foreach ($linksToDisplay as $key => $value) {
1543 // Select articles according to paging.
1544 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1545 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1546 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1547 $page = $page < 1 ? 1 : $page;
1548 $page = $page > $pagecount ? $pagecount : $page;
1550 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1551 $end = $i +
$_SESSION['LINKS_PER_PAGE'];
1552 $linkDisp = array();
1553 while ($i<$end && $i<count($keys))
1555 $link = $linksToDisplay[$keys[$i]];
1556 $link['description'] = format_description(
1557 $link['description'],
1558 $conf->get('redirector.url'),
1559 $conf->get('redirector.encode_url')
1561 $classLi = ($i %
2) != 0 ? '' : 'publicLinkHightLight';
1562 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
1563 $link['timestamp'] = $link['created']->getTimestamp();
1564 if (! empty($link['updated'])) {
1565 $link['updated_timestamp'] = $link['updated']->getTimestamp();
1567 $link['updated_timestamp'] = '';
1569 $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY
);
1570 uasort($taglist, 'strcasecmp');
1571 $link['taglist'] = $taglist;
1572 // Check for both signs of a note: starting with ? and 7 chars long.
1573 if ($link['url'][0] === '?' &&
1574 strlen($link['url']) === 7) {
1575 $link['url'] = index_url($_SERVER) . $link['url'];
1578 $linkDisp[$keys[$i]] = $link;
1582 // Compute paging navigation
1583 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
1584 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1585 $previous_page_url = '';
1586 if ($i != count($keys)) {
1587 $previous_page_url = '?page=' . ($page+
1) . $searchtermUrl . $searchtagsUrl;
1591 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1594 // Fill all template fields.
1596 'previous_page_url' => $previous_page_url,
1597 'next_page_url' => $next_page_url,
1598 'page_current' => $page,
1599 'page_max' => $pagecount,
1600 'result_count' => count($linksToDisplay),
1601 'search_term' => $searchterm,
1602 'search_tags' => $searchtags,
1603 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
1604 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
1605 'links' => $linkDisp,
1608 // If there is only a single link, we change on-the-fly the title of the page.
1609 if (count($linksToDisplay) == 1) {
1610 $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
1611 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1612 $data['pagetitle'] = t('Search: ');
1613 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1614 $bracketWrap = function ($tag) {
1615 return '['. $tag .']';
1617 $data['pagetitle'] .= ! empty($searchtags)
1618 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1620 $data['pagetitle'] .= '- '. $conf->get('general.title');
1623 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
1625 foreach ($data as $key => $value) {
1626 $PAGE->assign($key, $value);
1633 * Compute the thumbnail for a link.
1635 * With a link to the original URL.
1636 * Understands various services (youtube.com...)
1637 * Input: $url = URL for which the thumbnail must be found.
1638 * $href = if provided, this URL will be followed instead of $url
1639 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1640 * Some of them may be missing.
1641 * Return an empty array if no thumbnail available.
1643 * @param ConfigManager $conf Configuration Manager instance.
1644 * @param string $url
1645 * @param string|bool $href
1649 function computeThumbnail($conf, $url, $href = false)
1651 if (!$conf->get('thumbnail.enable_thumbnails')) return array();
1652 if ($href==false) $href=$url;
1654 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1655 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1656 // ^^^^^^^^^^^ ^^^^^^^^^^^
1657 $domain = parse_url($url,PHP_URL_HOST
);
1658 if ($domain=='youtube.com' || $domain=='www.youtube.com')
1660 parse_str(parse_url($url,PHP_URL_QUERY
), $params); // Extract video ID and get thumbnail
1661 if (!empty($params['v'])) return array('src'=>'https://img.youtube.com/vi/'.$params['v'].'/default.jpg',
1662 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1664 if ($domain=='youtu.be') // Youtube short links
1666 $path = parse_url($url,PHP_URL_PATH
);
1667 return array('src'=>'https://img.youtube.com/vi'.$path.'/default.jpg',
1668 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1670 if ($domain=='pix.toile-libre.org') // pix.toile-libre.org image hosting
1672 parse_str(parse_url($url,PHP_URL_QUERY
), $params); // Extract image filename.
1673 if (!empty($params) && !empty($params['img'])) return array('src'=>'http://pix.toile-libre.org/upload/thumb/'.urlencode($params['img']),
1674 'href'=>$href,'style'=>'max-width:120px; max-height:150px','alt'=>'pix.toile-libre.org thumbnail');
1677 if ($domain=='imgur.com')
1679 $path = parse_url($url,PHP_URL_PATH
);
1680 if (startsWith($path,'/a/')) return array(); // Thumbnails for albums are not available.
1681 if (startsWith($path,'/r/')) return array('src'=>'https://i.imgur.com/'.basename($path).'s.jpg',
1682 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1683 if (startsWith($path,'/gallery/')) return array('src'=>'https://i.imgur.com'.substr($path,8).'s.jpg',
1684 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1686 if (substr_count($path,'/')==1) return array('src'=>'https://i.imgur.com/'.substr($path,1).'s.jpg',
1687 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1689 if ($domain=='i.imgur.com')
1691 $pi = pathinfo(parse_url($url,PHP_URL_PATH
));
1692 if (!empty($pi['filename'])) return array('src'=>'https://i.imgur.com/'.$pi['filename'].'s.jpg',
1693 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1695 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
1697 if (strpos($url,'dailymotion.com/video/')!==false)
1699 $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
1700 return array('src'=>$thumburl,
1701 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'DailyMotion thumbnail');
1704 if (endsWith($domain,'.imageshack.us'))
1706 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION
));
1707 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1709 $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
1710 return array('src'=>$thumburl,
1711 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'imageshack.us thumbnail');
1715 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1716 // So we deport the thumbnail generation in order not to slow down page generation
1717 // (and we also cache the thumbnail)
1719 if (! $conf->get('thumbnail.enable_localcache')) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1721 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
1722 || $domain=='vimeo.com'
1723 || $domain=='ted.com' || endsWith($domain,'.ted.com')
1724 || $domain=='xkcd.com' || endsWith($domain,'.xkcd.com')
1727 if ($domain=='vimeo.com')
1728 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1729 $path = parse_url($url,PHP_URL_PATH
);
1730 if (!preg_match('!/\d+.+?!',$path)) return array(); // This is not a single video URL.
1732 if ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
1733 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1734 $path = parse_url($url,PHP_URL_PATH
);
1735 if (!preg_match('!/\d+.+?!',$path)) return array();
1737 if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
1738 { // Make sure this TED URL points to a video (/talks/...)
1739 $path = parse_url($url,PHP_URL_PATH
);
1740 if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
1742 $sign = hash_hmac('sha256', $url, $conf->get('credentials.salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
1743 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1744 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1747 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1748 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1749 // But using the extension will do.
1750 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION
));
1751 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1753 $sign = hash_hmac('sha256', $url, $conf->get('credentials.salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
1754 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1755 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1757 return array(); // No thumbnail.
1762 // Returns the HTML code to display a thumbnail for a link
1763 // with a link to the original URL.
1764 // Understands various services (youtube.com...)
1765 // Input: $url = URL for which the thumbnail must be found.
1766 // $href = if provided, this URL will be followed instead of $url
1767 // Returns '' if no thumbnail available.
1768 function thumbnail($url,$href=false)
1772 $t = computeThumbnail($conf, $url,$href);
1773 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1775 $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"';
1776 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1777 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1778 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1779 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1784 // Returns the HTML code to display a thumbnail for a link
1785 // for the picture wall (using lazy image loading)
1786 // Understands various services (youtube.com...)
1787 // Input: $url = URL for which the thumbnail must be found.
1788 // $href = if provided, this URL will be followed instead of $url
1789 // Returns '' if no thumbnail available.
1790 function lazyThumbnail($conf, $url,$href=false)
1794 $t = computeThumbnail($conf, $url,$href);
1795 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1797 $html='<a href="'.escape($t['href']).'">';
1800 $html.='<img class="b-lazy" src="#" data-src="'.escape($t['src']).'"';
1802 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1803 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1804 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1805 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1808 // No-JavaScript fallback.
1809 $html.='<noscript><img src="'.escape($t['src']).'"';
1810 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1811 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1812 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1813 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1814 $html.='></noscript></a>';
1822 * This function should NEVER be called if the file data/config.php exists.
1824 * @param ConfigManager $conf Configuration Manager instance.
1825 * @param SessionManager $sessionManager SessionManager instance
1826 * @param LoginManager $loginManager LoginManager instance
1828 function install($conf, $sessionManager, $loginManager) {
1829 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1830 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1833 // This part makes sure sessions works correctly.
1834 // (Because on some hosts, session.save_path may not be set correctly,
1835 // or we may not have write access to it.)
1836 if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working'))
1838 // Step 2: Check if data in session is correct.
1840 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1841 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1842 'and that you have write access to it.<br>'.
1843 'It currently points to %s.<br>'.
1844 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1845 'or any custom hostname without a dot causes cookie storage to fail. '.
1846 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1848 $msg = sprintf($msg, session_save_path());
1850 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1853 if (!isset($_SESSION['session_tested']))
1854 { // Step 1 : Try to store data in session and reload page.
1855 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1856 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1858 if (isset($_GET['test_session']))
1859 { // Step 3: Sessions are OK. Remove test parameter from URL.
1860 header('Location: '.index_url($_SERVER));
1864 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1867 if (!empty($_POST['continent']) && !empty($_POST['city'])
1868 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1870 $tz = $_POST['continent'].'/'.$_POST['city'];
1872 $conf->set('general.timezone', $tz);
1873 $login = $_POST['setlogin'];
1874 $conf->set('credentials.login', $login);
1875 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1876 $conf->set('credentials.salt', $salt);
1877 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
1878 if (!empty($_POST['title'])) {
1879 $conf->set('general.title', escape($_POST['title']));
1881 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
1883 $conf->set('translation.language', escape($_POST['language']));
1884 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1885 $conf->set('api.enabled', !empty($_POST['enableApi']));
1888 generate_api_secret(
1889 $conf->get('credentials.login'),
1890 $conf->get('credentials.salt')
1894 // Everything is ok, let's create config file.
1895 $conf->write($loginManager->isLoggedIn());
1897 catch(Exception
$e) {
1899 'ERROR while writing config file after installation.' . PHP_EOL
.
1903 // TODO: do not handle exceptions/errors in JS.
1904 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1907 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
1911 $PAGE = new PageBuilder($conf, null, $sessionManager->generateToken());
1912 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1913 $PAGE->assign('continents', $continents);
1914 $PAGE->assign('cities', $cities);
1915 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1916 $PAGE->renderPage('install');
1921 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
1922 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1923 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
1924 * This function is called by passing the URL:
1925 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1926 * [URL] is the URL of the link (e.g. a flickr page)
1927 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1928 * The function below will fetch the image from the webservice and store it in the cache.
1930 * @param ConfigManager $conf Configuration Manager instance,
1932 function genThumbnail($conf)
1934 // Make sure the parameters in the URL were generated by us.
1935 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt'));
1936 if ($sign!=$_GET['hmac']) die('Naughty boy!');
1938 $cacheDir = $conf->get('resource.thumbnails_cache', 'cache');
1939 // Let's see if we don't already have the image for this URL in the cache.
1940 $thumbname=hash('sha1',$_GET['url']).'.jpg';
1941 if (is_file($cacheDir .'/'. $thumbname))
1942 { // We have the thumbnail, just serve it:
1943 header('Content-Type: image/jpeg');
1944 echo file_get_contents($cacheDir .'/'. $thumbname);
1947 // We may also serve a blank image (if service did not respond)
1948 $blankname=hash('sha1',$_GET['url']).'.gif';
1949 if (is_file($cacheDir .'/'. $blankname))
1951 header('Content-Type: image/gif');
1952 echo file_get_contents($cacheDir .'/'. $blankname);
1956 // Otherwise, generate the thumbnail.
1957 $url = $_GET['url'];
1958 $domain = parse_url($url,PHP_URL_HOST
);
1960 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
1962 // Crude replacement to handle new flickr domain policy (They prefer www. now)
1963 $url = str_replace('http://flickr.com/','http://www.flickr.com/',$url);
1965 // Is this a link to an image, or to a flickr page ?
1967 if (endsWith(parse_url($url, PHP_URL_PATH
), '.jpg'))
1968 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
1969 preg_match('!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
1970 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
1972 else // This is a flickr page (html)
1974 // Get the flickr html page.
1975 list($headers, $content) = get_http_response($url, 20);
1976 if (strpos($headers[0], '200 OK') !== false)
1978 // flickr now nicely provides the URL of the thumbnail in each flickr page.
1979 preg_match('!<link rel=\"image_src\" href=\"(.+?)\"!', $content, $matches);
1980 if (!empty($matches[1])) $imageurl=$matches[1];
1982 // In albums (and some other pages), the link rel="image_src" is not provided,
1983 // but flickr provides:
1984 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
1987 preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!', $content, $matches);
1988 if (!empty($matches[1])) $imageurl=$matches[1];
1994 { // Let's download the image.
1995 // Image is 240x120, so 10 seconds to download should be enough.
1996 list($headers, $content) = get_http_response($imageurl, 10);
1997 if (strpos($headers[0], '200 OK') !== false) {
1998 // Save image to cache.
1999 file_put_contents($cacheDir .'/'. $thumbname, $content);
2000 header('Content-Type: image/jpeg');
2007 elseif ($domain=='vimeo.com' )
2009 // This is more complex: we have to perform a HTTP request, then parse the result.
2010 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2011 $vid = substr(parse_url($url,PHP_URL_PATH
),1);
2012 list($headers, $content) = get_http_response('https://vimeo.com/api/v2/video/'.escape($vid).'.php', 5);
2013 if (strpos($headers[0], '200 OK') !== false) {
2014 $t = unserialize($content);
2015 $imageurl = $t[0]['thumbnail_medium'];
2016 // Then we download the image and serve it to our client.
2017 list($headers, $content) = get_http_response($imageurl, 10);
2018 if (strpos($headers[0], '200 OK') !== false) {
2019 // Save image to cache.
2020 file_put_contents($cacheDir .'/'. $thumbname, $content);
2021 header('Content-Type: image/jpeg');
2028 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
2030 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2031 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2032 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2033 list($headers, $content) = get_http_response($url, 5);
2034 if (strpos($headers[0], '200 OK') !== false) {
2035 // Extract the link to the thumbnail
2036 preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!', $content, $matches);
2037 if (!empty($matches[1]))
2038 { // Let's download the image.
2039 $imageurl=$matches[1];
2040 // No control on image size, so wait long enough
2041 list($headers, $content) = get_http_response($imageurl, 20);
2042 if (strpos($headers[0], '200 OK') !== false) {
2043 $filepath = $cacheDir .'/'. $thumbname;
2044 file_put_contents($filepath, $content); // Save image to cache.
2045 if (resizeImage($filepath))
2047 header('Content-Type: image/jpeg');
2048 echo file_get_contents($filepath);
2056 elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
2058 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2059 // http://xkcd.com/327/
2060 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2061 list($headers, $content) = get_http_response($url, 5);
2062 if (strpos($headers[0], '200 OK') !== false) {
2063 // Extract the link to the thumbnail
2064 preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!', $content, $matches);
2065 if (!empty($matches[1]))
2066 { // Let's download the image.
2067 $imageurl=$matches[1];
2068 // No control on image size, so wait long enough
2069 list($headers, $content) = get_http_response($imageurl, 20);
2070 if (strpos($headers[0], '200 OK') !== false) {
2071 $filepath = $cacheDir.'/'.$thumbname;
2072 // Save image to cache.
2073 file_put_contents($filepath, $content);
2074 if (resizeImage($filepath))
2076 header('Content-Type: image/jpeg');
2077 echo file_get_contents($filepath);
2087 // For all other domains, we try to download the image and make a thumbnail.
2088 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2089 list($headers, $content) = get_http_response($url, 30);
2090 if (strpos($headers[0], '200 OK') !== false) {
2091 $filepath = $cacheDir .'/'.$thumbname;
2092 // Save image to cache.
2093 file_put_contents($filepath, $content);
2094 if (resizeImage($filepath))
2096 header('Content-Type: image/jpeg');
2097 echo file_get_contents($filepath);
2104 // Otherwise, return an empty image (8x8 transparent gif)
2105 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
2106 // Also put something in cache so that this URL is not requested twice.
2107 file_put_contents($cacheDir .'/'. $blankname, $blankgif);
2108 header('Content-Type: image/gif');
2112 // Make a thumbnail of the image (to width: 120 pixels)
2113 // Returns true if success, false otherwise.
2114 function resizeImage($filepath)
2116 if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
2118 // Trick: some stupid people rename GIF as JPEG... or else.
2119 // So we really try to open each image type whatever the extension is.
2120 $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
2122 $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
2123 $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
2124 $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
2125 if (!$im) return false; // Unable to open image (corrupted or not an image)
2128 $ystart = 0; $yheight=$h;
2129 if ($h>$w) { $ystart
= ($h
/2)-($w
/2); $yheight
=$w
/2; }
2130 $nw = 120; // Desired width
2131 $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
2133 $im2 = imagecreatetruecolor($nw,$nh);
2134 imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
2135 imageinterlace($im2,true); // For progressive JPEG.
2136 $tempname=$filepath.'_TEMP.jpg';
2137 imagejpeg($im2, $tempname, 90);
2141 rename($tempname,$filepath); // Overwrite original picture with thumbnail.
2145 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf
); exit; } // Thumbnail generation/cache does not need the link database.
2146 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf
); exit; }
2147 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
2148 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
2152 $history = new History($conf->get('resource.history'));
2153 } catch(Exception
$e) {
2154 die($e->getMessage());
2157 $linkDb = new LinkDB(
2158 $conf->get('resource.datastore'),
2159 $loginManager->isLoggedIn(),
2160 $conf->get('privacy.hide_public_links'),
2161 $conf->get('redirector.url'),
2162 $conf->get('redirector.encode_url')
2165 $container = new \Slim\
Container();
2166 $container['conf'] = $conf;
2167 $container['plugins'] = $pluginManager;
2168 $container['history'] = $history;
2169 $app = new \Slim\
App($container);
2172 $app->group('/api/v1', function() {
2173 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
2174 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
2175 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
2176 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
2177 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
2178 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
2179 $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
2180 })->add('\Shaarli\Api\ApiMiddleware');
2182 $response = $app->run(true);
2183 // Hack to make Slim and Shaarli router work together:
2184 // If a Slim route isn't found and NOT API call, we call renderPage().
2185 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
2186 // We use UTF-8 for proper international characters handling.
2187 header('Content-Type: text/html; charset=utf-8');
2188 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
2190 $app->respond($response);