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-requirements/\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 $clientIpId = client_ip_id($_SERVER);
128 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
129 if (! defined('LC_MESSAGES')) {
130 define('LC_MESSAGES', LC_COLLATE
);
133 // Sniff browser language and set date format accordingly.
134 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
135 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
138 new Languages(setlocale(LC_MESSAGES
, 0), $conf);
140 $conf->setEmpty('general.timezone', date_default_timezone_get());
141 $conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
142 RainTPL
::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
143 RainTPL
::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
145 $pluginManager = new PluginManager($conf);
146 $pluginManager->load($conf->get('general.enabled_plugins'));
148 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
150 ob_start(); // Output buffering for the page cache.
152 // Prevent caching on client side or proxy: (yes, it's ugly)
153 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
154 header("Cache-Control: no-store, no-cache, must-revalidate");
155 header("Cache-Control: post-check=0, pre-check=0", false);
156 header("Pragma: no-cache");
158 if (! is_file($conf->getConfigFileExt())) {
159 // Ensure Shaarli has proper access to its resources
160 $errors = ApplicationUtils
::checkResourcePermissions($conf);
162 if ($errors != array()) {
163 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
165 foreach ($errors as $error) {
166 $message .= '<li>'.$error.'</li>';
170 header('Content-Type: text/html; charset=utf-8');
175 // Display the installation form if no existing config is found
176 install($conf, $sessionManager);
179 // a token depending of deployment salt, user password, and the current ip
180 define('STAY_SIGNED_IN_TOKEN', sha1($conf->get('credentials.hash') . $_SERVER['REMOTE_ADDR'] . $conf->get('credentials.salt')));
182 $loginManager->checkLoginState($_COOKIE, $clientIpId, STAY_SIGNED_IN_TOKEN
);
185 * Adapter function to ensure compatibility with third-party templates
187 * @see https://github.com/shaarli/Shaarli/pull/1086
189 * @return bool true when the user is logged in, false otherwise
191 function isLoggedIn()
193 global $loginManager;
194 return $loginManager->isLoggedIn();
198 // ------------------------------------------------------------------------------------------
199 // Process login form: Check if login/password is correct.
200 if (isset($_POST['login'])) {
201 if (! $loginManager->canLogin($_SERVER)) {
202 die(t('I said: NO. You are banned for the moment. Go away.'));
204 if (isset($_POST['password'])
205 && $sessionManager->checkToken($_POST['token'])
206 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
208 $loginManager->handleSuccessfulLogin($_SERVER);
211 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
212 // Note: Never forget the trailing slash on the cookie path!
213 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
216 if (!empty($_POST['longlastingsession'])) {
217 // Keep the session cookie even after the browser closes
218 $sessionManager->setStaySignedIn(true);
219 $expirationTime = $sessionManager->extendSession();
222 $sessionManager::$LOGGED_IN_COOKIE,
223 STAY_SIGNED_IN_TOKEN
,
229 // Standard session expiration (=when browser closes)
233 // Send cookie with the new expiration date to the browser
234 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
235 session_regenerate_id(true);
237 // Optional redirect after login:
238 if (isset($_GET['post'])) {
239 $uri = '?post='. urlencode($_GET['post']);
240 foreach (array('description', 'source', 'title', 'tags') as $param) {
241 if (!empty($_GET[$param])) {
242 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
245 header('Location: '. $uri);
249 if (isset($_GET['edit_link'])) {
250 header('Location: ?edit_link='. escape($_GET['edit_link']));
254 if (isset($_POST['returnurl'])) {
255 // Prevent loops over login screen.
256 if (strpos($_POST['returnurl'], 'do=login') === false) {
257 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
261 header('Location: ?'); exit;
263 $loginManager->handleFailedLogin($_SERVER);
264 $redir = '&username='. urlencode($_POST['login']);
265 if (isset($_GET['post'])) {
266 $redir .= '&post=' . urlencode($_GET['post']);
267 foreach (array('description', 'source', 'title', 'tags') as $param) {
268 if (!empty($_GET[$param])) {
269 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
273 // Redirect to login screen.
274 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
279 // ------------------------------------------------------------------------------------------
280 // Token management for XSRF protection
281 // Token should be used in any form which acts on data (create,update,delete,import...).
282 if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
285 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
286 * Gives the last 7 days (which have links).
287 * This RSS feed cannot be filtered.
289 * @param ConfigManager $conf Configuration Manager instance
290 * @param LoginManager $loginManager LoginManager instance
292 function showDailyRSS($conf, $loginManager) {
294 $query = $_SERVER['QUERY_STRING'];
295 $cache = new CachedPage(
296 $conf->get('config.PAGE_CACHE'),
298 startsWith($query,'do=dailyrss') && !$loginManager->isLoggedIn()
300 $cached = $cache->cachedVersion();
301 if (!empty($cached)) {
306 // If cached was not found (or not usable), then read the database and build the response:
307 // Read links from database (and filter private links if used it not logged in).
308 $LINKSDB = new LinkDB(
309 $conf->get('resource.datastore'),
310 $loginManager->isLoggedIn(),
311 $conf->get('privacy.hide_public_links'),
312 $conf->get('redirector.url'),
313 $conf->get('redirector.encode_url')
316 /* Some Shaarlies may have very few links, so we need to look
317 back in time until we have enough days ($nb_of_days).
319 $nb_of_days = 7; // We take 7 days.
320 $today = date('Ymd');
323 foreach ($LINKSDB as $link) {
324 $day = $link['created']->format('Ymd'); // Extract day (without time)
325 if (strcmp($day, $today) < 0) {
326 if (empty($days[$day])) {
327 $days[$day] = array();
329 $days[$day][] = $link;
332 if (count($days) > $nb_of_days) {
333 break; // Have we collected enough days?
337 // Build the RSS feed.
338 header('Content-Type: application/rss+xml; charset=utf-8');
339 $pageaddr = escape(index_url($_SERVER));
340 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
342 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
343 echo '<link>'. $pageaddr .'</link>';
344 echo '<description>Daily shared links</description>';
345 echo '<language>en-en</language>';
346 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL
;
349 foreach ($days as $day => $links) {
350 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
351 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
353 // We pre-format some fields for proper output.
354 foreach ($links as &$link) {
355 $link['formatedDescription'] = format_description(
356 $link['description'],
357 $conf->get('redirector.url'),
358 $conf->get('redirector.encode_url')
360 $link['thumbnail'] = thumbnail($conf, $link['url']);
361 $link['timestamp'] = $link['created']->getTimestamp();
362 if (startsWith($link['url'], '?')) {
363 $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
367 // Then build the HTML for this day:
369 $tpl->assign('title', $conf->get('general.title'));
370 $tpl->assign('daydate', $dayDate->getTimestamp());
371 $tpl->assign('absurl', $absurl);
372 $tpl->assign('links', $links);
373 $tpl->assign('rssdate', escape($dayDate->format(DateTime
::RSS
)));
374 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
375 $html = $tpl->draw('dailyrss', true);
377 echo $html . PHP_EOL
;
379 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
381 $cache->cache(ob_get_contents());
387 * Show the 'Daily' page.
389 * @param PageBuilder $pageBuilder Template engine wrapper.
390 * @param LinkDB $LINKSDB LinkDB instance.
391 * @param ConfigManager $conf Configuration Manager instance.
392 * @param PluginManager $pluginManager Plugin Manager instance.
393 * @param LoginManager $loginManager Login Manager instance
395 function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
397 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
398 if (isset($_GET['day'])) {
402 $days = $LINKSDB->days();
403 $i = array_search($day, $days);
404 if ($i === false && count($days)) {
405 // no links for day, but at least one day with links
406 $i = count($days) - 1;
414 $previousday=$days[$i - 1];
416 if ($i < count($days) - 1) {
417 $nextday = $days[$i +
1];
421 $linksToDisplay = $LINKSDB->filterDay($day);
422 } catch (Exception
$exc) {
424 $linksToDisplay = array();
427 // We pre-format some fields for proper output.
428 foreach($linksToDisplay as $key => $link) {
429 $taglist = explode(' ',$link['tags']);
430 uasort($taglist, 'strcasecmp');
431 $linksToDisplay[$key]['taglist']=$taglist;
432 $linksToDisplay[$key]['formatedDescription'] = format_description(
433 $link['description'],
434 $conf->get('redirector.url'),
435 $conf->get('redirector.encode_url')
437 $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
438 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
441 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
443 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
444 'linksToDisplay' => $linksToDisplay,
445 'day' => $dayDate->getTimestamp(),
446 'dayDate' => $dayDate,
447 'previousday' => $previousday,
448 'nextday' => $nextday,
451 /* Hook is called before column construction so that plugins don't have
452 to deal with columns. */
453 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
455 /* We need to spread the articles on 3 columns.
456 I did not want to use a JavaScript lib like http://masonry.desandro.com/
457 so I manually spread entries with a simple method: I roughly evaluate the
458 height of a div according to title and description length.
460 $columns = array(array(), array(), array()); // Entries to display, for each column.
461 $fill = array(0, 0, 0); // Rough estimate of columns fill.
462 foreach($data['linksToDisplay'] as $key => $link) {
463 // Roughly estimate length of entry (by counting characters)
464 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
465 // Description: 836 characters gives roughly 342 pixel height.
466 // This is not perfect, but it's usually OK.
467 $length = strlen($link['title']) +
(342 * strlen($link['description'])) / 836;
468 if ($link['thumbnail']) {
469 $length +
= 100; // 1 thumbnails roughly takes 100 pixels height.
471 // Then put in column which is the less filled:
472 $smallest = min($fill); // find smallest value in array.
473 $index = array_search($smallest, $fill); // find index of this smallest value.
474 array_push($columns[$index], $link); // Put entry in this column.
475 $fill[$index] +
= $length;
478 $data['cols'] = $columns;
480 foreach ($data as $key => $value) {
481 $pageBuilder->assign($key, $value);
484 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
485 $pageBuilder->renderPage('daily');
490 * Renders the linklist
492 * @param pageBuilder $PAGE pageBuilder instance.
493 * @param LinkDB $LINKSDB LinkDB instance.
494 * @param ConfigManager $conf Configuration Manager instance.
495 * @param PluginManager $pluginManager Plugin Manager instance.
497 function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager) {
498 buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager, $loginManager);
499 $PAGE->renderPage('linklist');
503 * Render HTML page (according to URL parameters and user rights)
505 * @param ConfigManager $conf Configuration Manager instance.
506 * @param PluginManager $pluginManager Plugin Manager instance,
507 * @param LinkDB $LINKSDB
508 * @param History $history instance
509 * @param SessionManager $sessionManager SessionManager instance
510 * @param LoginManager $loginManager LoginManager instance
512 function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
514 $updater = new Updater(
515 read_updates_file($conf->get('resource.updates')),
518 $loginManager->isLoggedIn()
521 $newUpdates = $updater->update();
522 if (! empty($newUpdates)) {
524 $conf->get('resource.updates'),
525 $updater->getDoneUpdates()
529 catch(Exception
$e) {
530 die($e->getMessage());
533 $PAGE = new PageBuilder($conf, $LINKSDB, $sessionManager->generateToken(), $loginManager->isLoggedIn());
534 $PAGE->assign('linkcount', count($LINKSDB));
535 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
536 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
538 // Determine which page will be rendered.
539 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
540 $targetPage = Router
::findPage($query, $_GET, $loginManager->isLoggedIn());
543 // if the user isn't logged in
544 !$loginManager->isLoggedIn() &&
545 // and Shaarli doesn't have public content...
546 $conf->get('privacy.hide_public_links') &&
547 // and is configured to enforce the login
548 $conf->get('privacy.force_login') &&
549 // and the current page isn't already the login page
550 $targetPage !== Router
::$PAGE_LOGIN &&
551 // and the user is not requesting a feed (which would lead to a different content-type as expected)
552 $targetPage !== Router
::$PAGE_FEED_ATOM &&
553 $targetPage !== Router
::$PAGE_FEED_RSS
555 // force current page to be the login page
556 $targetPage = Router
::$PAGE_LOGIN;
559 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
560 // Then assign generated data to RainTPL.
561 $common_hooks = array(
567 foreach($common_hooks as $name) {
568 $plugin_data = array();
569 $pluginManager->executeHooks('render_' . $name, $plugin_data,
571 'target' => $targetPage,
572 'loggedin' => $loginManager->isLoggedIn()
575 $PAGE->assign('plugins_' . $name, $plugin_data);
578 // -------- Display login form.
579 if ($targetPage == Router
::$PAGE_LOGIN)
581 if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
582 if (isset($_GET['username'])) {
583 $PAGE->assign('username', escape($_GET['username']));
585 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
586 // add default state of the 'remember me' checkbox
587 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
588 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
589 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
590 $PAGE->renderPage('loginform');
593 // -------- User wants to logout.
594 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
596 invalidateCaches($conf->get('resource.page_cache'));
597 $sessionManager->logout();
598 setcookie(SessionManager
::$LOGGED_IN_COOKIE, 'false', 0, WEB_PATH
);
599 header('Location: ?');
603 // -------- Picture wall
604 if ($targetPage == Router
::$PAGE_PICWALL)
606 // Optionally filter the results:
607 $links = $LINKSDB->filterSearch($_GET);
608 $linksToDisplay = array();
610 // Get only links which have a thumbnail.
611 foreach($links as $link)
613 $permalink='?'.$link['shorturl'];
614 $thumb=lazyThumbnail($conf, $link['url'],$permalink);
615 if ($thumb!='') // Only output links which have a thumbnail.
617 $link['thumbnail']=$thumb; // Thumbnail HTML code.
618 $linksToDisplay[]=$link; // Add to array.
623 'linksToDisplay' => $linksToDisplay,
625 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => $loginManager->isLoggedIn()));
627 foreach ($data as $key => $value) {
628 $PAGE->assign($key, $value);
631 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
632 $PAGE->renderPage('picwall');
636 // -------- Tag cloud
637 if ($targetPage == Router
::$PAGE_TAGCLOUD)
639 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
640 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
641 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
643 // We sort tags alphabetically, then choose a font size according to count.
644 // First, find max value.
646 foreach ($tags as $value) {
647 $maxcount = max($maxcount, $value);
650 alphabetical_sort($tags, false, true);
653 foreach($tags as $key => $value) {
654 if (in_array($key, $filteringTags)) {
657 // Tag font size scaling:
658 // default 15 and 30 logarithm bases affect scaling,
659 // 22 and 6 are arbitrary font sizes for max and min sizes.
660 $size = log($value, 15) / log($maxcount, 30) * 2.2 +
0.8;
661 $tagList[$key] = array(
663 'size' => number_format($size, 2, '.', ''),
667 $searchTags = implode(' ', escape($filteringTags));
669 'search_tags' => $searchTags,
672 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
674 foreach ($data as $key => $value) {
675 $PAGE->assign($key, $value);
678 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
679 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
680 $PAGE->renderPage('tag.cloud');
685 if ($targetPage == Router
::$PAGE_TAGLIST)
687 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
688 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
689 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
690 foreach ($filteringTags as $tag) {
691 if (array_key_exists($tag, $tags)) {
696 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
697 alphabetical_sort($tags, false, true);
700 $searchTags = implode(' ', escape($filteringTags));
702 'search_tags' => $searchTags,
705 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
707 foreach ($data as $key => $value) {
708 $PAGE->assign($key, $value);
711 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
712 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
713 $PAGE->renderPage('tag.list');
718 if ($targetPage == Router
::$PAGE_DAILY) {
719 showDaily($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
722 // ATOM and RSS feed.
723 if ($targetPage == Router
::$PAGE_FEED_ATOM || $targetPage == Router
::$PAGE_FEED_RSS) {
724 $feedType = $targetPage == Router
::$PAGE_FEED_RSS ? FeedBuilder
::$FEED_RSS : FeedBuilder
::$FEED_ATOM;
725 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
728 $query = $_SERVER['QUERY_STRING'];
729 $cache = new CachedPage(
730 $conf->get('resource.page_cache'),
732 startsWith($query,'do='. $targetPage) && !$loginManager->isLoggedIn()
734 $cached = $cache->cachedVersion();
735 if (!empty($cached)) {
741 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, $loginManager->isLoggedIn());
742 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE
, 0)));
743 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
744 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
745 $data = $feedGenerator->buildData();
747 // Process plugin hook.
748 $pluginManager->executeHooks('render_feed', $data, array(
749 'loggedin' => $loginManager->isLoggedIn(),
750 'target' => $targetPage,
753 // Render the template.
754 $PAGE->assignAll($data);
755 $PAGE->renderPage('feed.'. $feedType);
756 $cache->cache(ob_get_contents());
761 // Display opensearch plugin (XML)
762 if ($targetPage == Router
::$PAGE_OPENSEARCH) {
763 header('Content-Type: application/xml; charset=utf-8');
764 $PAGE->assign('serverurl', index_url($_SERVER));
765 $PAGE->renderPage('opensearch');
769 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
770 if (isset($_GET['addtag']))
772 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
773 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET
['addtag'])); exit; } // In case browser does not send HTTP_REFERER
774 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY
), $params);
776 // Prevent redirection loop
777 if (isset($params['addtag'])) {
778 unset($params['addtag']);
781 // Check if this tag is already in the search query and ignore it if it is.
782 // Each tag is always separated by a space
783 if (isset($params['searchtags'])) {
784 $current_tags = explode(' ', $params['searchtags']);
786 $current_tags = array();
789 foreach ($current_tags as $value) {
790 if ($value === $_GET['addtag']) {
795 // Append the tag if necessary
796 if (empty($params['searchtags'])) {
797 $params['searchtags'] = trim($_GET['addtag']);
800 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
803 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
804 header('Location: ?'.http_build_query($params));
808 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
809 if (isset($_GET['removetag'])) {
810 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
811 if (empty($_SERVER['HTTP_REFERER'])) {
812 header('Location: ?');
816 // In case browser does not send HTTP_REFERER
817 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
819 // Prevent redirection loop
820 if (isset($params['removetag'])) {
821 unset($params['removetag']);
824 if (isset($params['searchtags'])) {
825 $tags = explode(' ', $params['searchtags']);
826 // Remove value from array $tags.
827 $tags = array_diff($tags, array($_GET['removetag']));
828 $params['searchtags'] = implode(' ',$tags);
830 if (empty($params['searchtags'])) {
831 unset($params['searchtags']);
834 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
836 header('Location: ?'.http_build_query($params));
840 // -------- User wants to change the number of links per page (linksperpage=...)
841 if (isset($_GET['linksperpage'])) {
842 if (is_numeric($_GET['linksperpage'])) {
843 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
846 if (! empty($_SERVER['HTTP_REFERER'])) {
847 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
851 header('Location: '. $location);
855 // -------- User wants to see only private links (toggle)
856 if (isset($_GET['visibility'])) {
857 if ($_GET['visibility'] === 'private') {
858 // Visibility not set or not already private, set private, otherwise reset it
859 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
860 // See only private links
861 $_SESSION['visibility'] = 'private';
863 unset($_SESSION['visibility']);
865 } elseif ($_GET['visibility'] === 'public') {
866 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
867 // See only public links
868 $_SESSION['visibility'] = 'public';
870 unset($_SESSION['visibility']);
874 if (! empty($_SERVER['HTTP_REFERER'])) {
875 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
879 header('Location: '. $location);
883 // -------- User wants to see only untagged links (toggle)
884 if (isset($_GET['untaggedonly'])) {
885 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
887 if (! empty($_SERVER['HTTP_REFERER'])) {
888 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
892 header('Location: '. $location);
896 // -------- Handle other actions allowed for non-logged in users:
897 if (!$loginManager->isLoggedIn())
899 // User tries to post new link but is not logged in:
900 // Show login screen, then redirect to ?post=...
901 if (isset($_GET['post']))
903 header( // Redirect to login page, then back to post link.
904 'Location: ?do=login&post='.urlencode($_GET['post']).
905 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
906 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
907 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
908 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
913 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
914 if (isset($_GET['edit_link'])) {
915 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
919 exit; // Never remove this one! All operations below are reserved for logged in user.
922 // -------- All other functions are reserved for the registered user:
924 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
925 if ($targetPage == Router
::$PAGE_TOOLS)
928 'pageabsaddr' => index_url($_SERVER),
929 'sslenabled' => is_https($_SERVER),
931 $pluginManager->executeHooks('render_tools', $data);
933 foreach ($data as $key => $value) {
934 $PAGE->assign($key, $value);
937 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
938 $PAGE->renderPage('tools');
942 // -------- User wants to change his/her password.
943 if ($targetPage == Router
::$PAGE_CHANGEPASSWORD)
945 if ($conf->get('security.open_shaarli')) {
946 die(t('You are not supposed to change a password on an Open Shaarli.'));
949 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
951 if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away!
953 // Make sure old password is correct.
954 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
955 if ($oldhash!= $conf->get('credentials.hash')) {
956 echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>';
960 // Salt renders rainbow-tables attacks useless.
961 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
962 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt')));
964 $conf->write($loginManager->isLoggedIn());
966 catch(Exception
$e) {
968 'ERROR while writing config file after changing password.' . PHP_EOL
.
972 // TODO: do not handle exceptions/errors in JS.
973 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
976 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
979 else // show the change password form.
981 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
982 $PAGE->renderPage('changepassword');
987 // -------- User wants to change configuration
988 if ($targetPage == Router
::$PAGE_CONFIGURE)
990 if (!empty($_POST['title']) )
992 if (!$sessionManager->checkToken($_POST['token'])) {
993 die(t('Wrong token.')); // Go away!
996 if (!empty($_POST['continent']) && !empty($_POST['city'])
997 && isTimeZoneValid($_POST['continent'], $_POST['city'])
999 $tz = $_POST['continent'] . '/' . $_POST['city'];
1001 $conf->set('general.timezone', $tz);
1002 $conf->set('general.title', escape($_POST['title']));
1003 $conf->set('general.header_link', escape($_POST['titleLink']));
1004 $conf->set('resource.theme', escape($_POST['theme']));
1005 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
1006 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
1007 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1008 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1009 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
1010 $conf->set('api.enabled', !empty($_POST['enableApi']));
1011 $conf->set('api.secret', escape($_POST['apiSecret']));
1012 $conf->set('translation.language', escape($_POST['language']));
1015 $conf->write($loginManager->isLoggedIn());
1016 $history->updateSettings();
1017 invalidateCaches($conf->get('resource.page_cache'));
1019 catch(Exception
$e) {
1021 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1025 // TODO: do not handle exceptions/errors in JS.
1026 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1029 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1032 else // Show the configuration form.
1034 $PAGE->assign('title', $conf->get('general.title'));
1035 $PAGE->assign('theme', $conf->get('resource.theme'));
1036 $PAGE->assign('theme_available', ThemeUtils
::getThemes($conf->get('resource.raintpl_tpl')));
1037 list($continents, $cities) = generateTimeZoneData(
1038 timezone_identifiers_list(),
1039 $conf->get('general.timezone')
1041 $PAGE->assign('continents', $continents);
1042 $PAGE->assign('cities', $cities);
1043 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
1044 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1045 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1046 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1047 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1048 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1049 $PAGE->assign('api_secret', $conf->get('api.secret'));
1050 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1051 $PAGE->assign('language', $conf->get('translation.language'));
1052 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
1053 $PAGE->renderPage('configure');
1058 // -------- User wants to rename a tag or delete it
1059 if ($targetPage == Router
::$PAGE_CHANGETAG)
1061 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1062 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1063 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
1064 $PAGE->renderPage('changetag');
1068 if (!$sessionManager->checkToken($_POST['token'])) {
1069 die(t('Wrong token.'));
1072 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), escape($_POST['totag']));
1073 $LINKSDB->save($conf->get('resource.page_cache'));
1074 foreach ($alteredLinks as $link) {
1075 $history->updateLink($link);
1077 $delete = empty($_POST['totag']);
1078 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1079 $count = count($alteredLinks);
1081 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d links.', $count), $count)
1082 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d links.', $count), $count);
1083 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1087 // -------- User wants to add a link without using the bookmarklet: Show form.
1088 if ($targetPage == Router
::$PAGE_ADDLINK)
1090 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1091 $PAGE->renderPage('addlink');
1095 // -------- User clicked the "Save" button when editing a link: Save link to database.
1096 if (isset($_POST['save_edit']))
1099 if (! $sessionManager->checkToken($_POST['token'])) {
1100 die(t('Wrong token.'));
1103 // lf_id should only be present if the link exists.
1104 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
1105 // Linkdate is kept here to:
1106 // - use the same permalink for notes as they're displayed when creating them
1107 // - let users hack creation date of their posts
1108 // See: https://shaarli.readthedocs.io/en/master/Various-hacks/#changing-the-timestamp-for-a-shaare
1109 $linkdate = escape($_POST['lf_linkdate']);
1110 if (isset($LINKSDB[$id])) {
1112 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1113 $updated = new DateTime();
1114 $shortUrl = $LINKSDB[$id]['shorturl'];
1118 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1120 $shortUrl = link_small_hash($created, $id);
1124 // Remove multiple spaces.
1125 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
1126 // Remove first '-' char in tags.
1127 $tags = preg_replace('/(^| )\-/', '$1', $tags);
1128 // Remove duplicates.
1129 $tags = implode(' ', array_unique(explode(' ', $tags)));
1131 if (empty(trim($_POST['lf_url
']))) {
1132 $_POST['lf_url
'] = '?' . smallHash($linkdate . $id);
1134 $url = whitelist_protocols(trim($_POST['lf_url
']), $conf->get('security
.allowed_protocols
'));
1138 'title
' => trim($_POST['lf_title
']),
1140 'description
' => $_POST['lf_description
'],
1141 'private' => (isset($_POST['lf_private
']) ? 1 : 0),
1142 'created
' => $created,
1143 'updated
' => $updated,
1144 'tags
' => str_replace(',', ' ', $tags),
1145 'shorturl
' => $shortUrl,
1148 // If title is empty, use the URL as title.
1149 if ($link['title
'] == '') {
1150 $link['title
'] = $link['url
'];
1153 $pluginManager->executeHooks('save_link
', $link);
1155 $LINKSDB[$id] = $link;
1156 $LINKSDB->save($conf->get('resource.page_cache
'));
1158 $history->addLink($link);
1160 $history->updateLink($link);
1163 // If we are called from the bookmarklet, we must close the popup:
1164 if (isset($_GET['source
']) && ($_GET['source
']=='bookmarklet
' || $_GET['source
']=='firefoxsocialapi
')) {
1165 echo '<script
>self
.close();</script
>';
1169 $returnurl = !empty($_POST['returnurl
']) ? $_POST['returnurl
'] : '?';
1170 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST
'], array('addlink
', 'post
', 'edit_link
'));
1171 // Scroll to the link which has been edited.
1172 $location .= '#' . $link['shorturl'];
1173 // After saving the link, redirect to the page the user was on.
1174 header('Location: '. $location);
1178 // -------- User clicked the "Cancel" button when editing a link.
1179 if (isset($_POST['cancel_edit']))
1181 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1182 if (! isset($LINKSDB[$id])) {
1183 header('Location: ?');
1185 // If we are called from the bookmarklet, we must close the popup:
1186 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1187 $link = $LINKSDB[$id];
1188 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1189 // Scroll to the link which has been edited.
1190 $returnurl .= '#'. $link['shorturl'];
1191 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1192 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1196 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1197 if ($targetPage == Router
::$PAGE_DELETELINK)
1199 if (! $sessionManager->checkToken($_GET['token'])) {
1200 die(t('Wrong token.'));
1203 $ids = trim($_GET['lf_linkdate']);
1204 if (strpos($ids, ' ') !== false) {
1205 // multiple, space-separated ids provided
1206 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1208 // only a single id provided
1211 // assert at least one id is given
1213 die('no id provided');
1215 foreach ($ids as $id) {
1216 $id = (int) escape($id);
1217 $link = $LINKSDB[$id];
1218 $pluginManager->executeHooks('delete_link', $link);
1219 unset($LINKSDB[$id]);
1221 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1222 $history->deleteLink($link);
1224 // If we are called from the bookmarklet, we must close the popup:
1225 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1228 if (isset($_SERVER['HTTP_REFERER'])) {
1229 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1230 $location = generateLocation(
1231 $_SERVER['HTTP_REFERER'],
1232 $_SERVER['HTTP_HOST'],
1233 ['delete_link', 'edit_link', $link['shorturl']]
1237 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1241 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1242 if (isset($_GET['edit_link']))
1244 $id = (int) escape($_GET['edit_link']);
1245 $link = $LINKSDB[$id]; // Read database
1246 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
1247 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1250 'link_is_new' => false,
1251 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1252 'tags' => $LINKSDB->linksCountPerTag(),
1254 $pluginManager->executeHooks('render_editlink', $data);
1256 foreach ($data as $key => $value) {
1257 $PAGE->assign($key, $value);
1260 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1261 $PAGE->renderPage('editlink');
1265 // -------- User want to post a new link: Display link edit form.
1266 if (isset($_GET['post'])) {
1267 $url = cleanup_url($_GET['post']);
1269 $link_is_new = false;
1270 // Check if URL is not already in database (in this case, we will edit the existing link)
1271 $link = $LINKSDB->getLinkFromUrl($url);
1274 $link_is_new = true;
1275 $linkdate = strval(date(LinkDB
::LINK_DATE_FORMAT
));
1276 // Get title if it was provided in URL (by the bookmarklet).
1277 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1278 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1279 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1280 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1281 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1282 // 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.)
1283 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1284 // Short timeout to keep the application responsive
1285 // The callback will fill $charset and $title with data from the downloaded page.
1288 $conf->get('general.download_timeout', 30),
1289 $conf->get('general.download_max_size', 4194304),
1290 get_curl_download_callback($charset, $title)
1292 if (! empty($title) && strtolower($charset) != 'utf-8') {
1293 $title = mb_convert_encoding($title, 'utf-8', $charset);
1298 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1299 $title = $conf->get('general.default_note_title', t('Note: '));
1301 $url = escape($url);
1302 $title = escape($title);
1305 'linkdate' => $linkdate,
1308 'description' => $description,
1310 'private' => $private,
1313 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1318 'link_is_new' => $link_is_new,
1319 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1320 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1321 'tags' => $LINKSDB->linksCountPerTag(),
1322 'default_private_links' => $conf->get('privacy.default_private_links', false),
1324 $pluginManager->executeHooks('render_editlink', $data);
1326 foreach ($data as $key => $value) {
1327 $PAGE->assign($key, $value);
1330 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1331 $PAGE->renderPage('editlink');
1335 if ($targetPage == Router
::$PAGE_EXPORT) {
1336 // Export links as a Netscape Bookmarks file
1338 if (empty($_GET['selection'])) {
1339 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1340 $PAGE->renderPage('export');
1344 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1345 $selection = $_GET['selection'];
1346 if (isset($_GET['prepend_note_url'])) {
1347 $prependNoteUrl = $_GET['prepend_note_url'];
1349 $prependNoteUrl = false;
1355 NetscapeBookmarkUtils
::filterAndFormat(
1362 } catch (Exception
$exc) {
1363 header('Content-Type: text/plain; charset=utf-8');
1364 echo $exc->getMessage();
1367 $now = new DateTime();
1368 header('Content-Type: text/html; charset=utf-8');
1370 'Content-disposition: attachment; filename=bookmarks_'
1371 .$selection.'_'.$now->format(LinkDB
::LINK_DATE_FORMAT
).'.html'
1373 $PAGE->assign('date', $now->format(DateTime
::RFC822
));
1374 $PAGE->assign('eol', PHP_EOL
);
1375 $PAGE->assign('selection', $selection);
1376 $PAGE->renderPage('export.bookmarks');
1380 if ($targetPage == Router
::$PAGE_IMPORT) {
1381 // Upload a Netscape bookmark dump to import its contents
1383 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1384 // Show import dialog
1387 get_max_upload_size(
1388 ini_get('post_max_size'),
1389 ini_get('upload_max_filesize'),
1395 get_max_upload_size(
1396 ini_get('post_max_size'),
1397 ini_get('upload_max_filesize'),
1401 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1402 $PAGE->renderPage('import');
1406 // Import bookmarks from an uploaded file
1407 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1408 // The file is too big or some form field may be missing.
1411 'The file you are trying to upload is probably bigger than what this webserver can accept'
1412 .' (%s). Please upload in smaller chunks.'
1414 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1416 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router
::$PAGE_IMPORT .'\';</script>';
1419 if (! $sessionManager->checkToken($_POST['token'])) {
1420 die('Wrong token.');
1422 $status = NetscapeBookmarkUtils
::import(
1429 echo '<script>alert("'.$status.'");document.location=\'?do='
1430 .Router
::$PAGE_IMPORT .'\';</script>';
1434 // Plugin administration page
1435 if ($targetPage == Router
::$PAGE_PLUGINSADMIN) {
1436 $pluginMeta = $pluginManager->getPluginsMeta();
1438 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1439 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v
['order'] !== false; });
1441 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1444 function($a, $b) { return $a
['order'] - $b
['order']; }
1446 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v
['order'] === false; });
1448 $PAGE->assign('enabledPlugins', $enabledPlugins);
1449 $PAGE->assign('disabledPlugins', $disabledPlugins);
1450 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
1451 $PAGE->renderPage('pluginsadmin');
1455 // Plugin administration form action
1456 if ($targetPage == Router
::$PAGE_SAVE_PLUGINSADMIN) {
1458 if (isset($_POST['parameters_form'])) {
1459 unset($_POST['parameters_form']);
1460 foreach ($_POST as $param => $value) {
1461 $conf->set('plugins.'. $param, escape($value));
1465 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1467 $conf->write($loginManager->isLoggedIn());
1468 $history->updateSettings();
1470 catch (Exception
$e) {
1472 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1476 // TODO: do not handle exceptions/errors in JS.
1477 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router
::$PAGE_PLUGINSADMIN .'\';</script>';
1480 header('Location: ?do='. Router
::$PAGE_PLUGINSADMIN);
1484 // Get a fresh token
1485 if ($targetPage == Router
::$GET_TOKEN) {
1486 header('Content-Type:text/plain');
1487 echo $sessionManager->generateToken($conf);
1491 // -------- Otherwise, simply display search form and links:
1492 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
1497 * Template for the list of links (<div id="linklist">)
1498 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1500 * @param pageBuilder $PAGE pageBuilder instance.
1501 * @param LinkDB $LINKSDB LinkDB instance.
1502 * @param ConfigManager $conf Configuration Manager instance.
1503 * @param PluginManager $pluginManager Plugin Manager instance.
1504 * @param LoginManager $loginManager LoginManager instance
1506 function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1508 // Used in templates
1509 if (isset($_GET['searchtags'])) {
1510 if (! empty($_GET['searchtags'])) {
1511 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1513 $searchtags = false;
1518 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1521 if (! empty($_SERVER['QUERY_STRING'])
1522 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1524 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1525 } catch (LinkNotFoundException
$e) {
1526 $PAGE->render404($e->getMessage());
1530 // Filter links according search parameters.
1531 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
1533 'searchtags' => $searchtags,
1534 'searchterm' => $searchterm,
1536 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
1539 // ---- Handle paging.
1541 foreach ($linksToDisplay as $key => $value) {
1545 // Select articles according to paging.
1546 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1547 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1548 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1549 $page = $page < 1 ? 1 : $page;
1550 $page = $page > $pagecount ? $pagecount : $page;
1552 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1553 $end = $i +
$_SESSION['LINKS_PER_PAGE'];
1554 $linkDisp = array();
1555 while ($i<$end && $i<count($keys))
1557 $link = $linksToDisplay[$keys[$i]];
1558 $link['description'] = format_description(
1559 $link['description'],
1560 $conf->get('redirector.url'),
1561 $conf->get('redirector.encode_url')
1563 $classLi = ($i %
2) != 0 ? '' : 'publicLinkHightLight';
1564 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
1565 $link['timestamp'] = $link['created']->getTimestamp();
1566 if (! empty($link['updated'])) {
1567 $link['updated_timestamp'] = $link['updated']->getTimestamp();
1569 $link['updated_timestamp'] = '';
1571 $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY
);
1572 uasort($taglist, 'strcasecmp');
1573 $link['taglist'] = $taglist;
1574 // Check for both signs of a note: starting with ? and 7 chars long.
1575 if ($link['url'][0] === '?' &&
1576 strlen($link['url']) === 7) {
1577 $link['url'] = index_url($_SERVER) . $link['url'];
1580 $linkDisp[$keys[$i]] = $link;
1584 // Compute paging navigation
1585 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
1586 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1587 $previous_page_url = '';
1588 if ($i != count($keys)) {
1589 $previous_page_url = '?page=' . ($page+
1) . $searchtermUrl . $searchtagsUrl;
1593 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1596 // Fill all template fields.
1598 'previous_page_url' => $previous_page_url,
1599 'next_page_url' => $next_page_url,
1600 'page_current' => $page,
1601 'page_max' => $pagecount,
1602 'result_count' => count($linksToDisplay),
1603 'search_term' => $searchterm,
1604 'search_tags' => $searchtags,
1605 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
1606 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
1607 'links' => $linkDisp,
1610 // If there is only a single link, we change on-the-fly the title of the page.
1611 if (count($linksToDisplay) == 1) {
1612 $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
1613 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1614 $data['pagetitle'] = t('Search: ');
1615 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1616 $bracketWrap = function ($tag) {
1617 return '['. $tag .']';
1619 $data['pagetitle'] .= ! empty($searchtags)
1620 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1622 $data['pagetitle'] .= '- '. $conf->get('general.title');
1625 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
1627 foreach ($data as $key => $value) {
1628 $PAGE->assign($key, $value);
1635 * Compute the thumbnail for a link.
1637 * With a link to the original URL.
1638 * Understands various services (youtube.com...)
1639 * Input: $url = URL for which the thumbnail must be found.
1640 * $href = if provided, this URL will be followed instead of $url
1641 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1642 * Some of them may be missing.
1643 * Return an empty array if no thumbnail available.
1645 * @param ConfigManager $conf Configuration Manager instance.
1646 * @param string $url
1647 * @param string|bool $href
1651 function computeThumbnail($conf, $url, $href = false)
1653 if (!$conf->get('thumbnail.enable_thumbnails')) return array();
1654 if ($href==false) $href=$url;
1656 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1657 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1658 // ^^^^^^^^^^^ ^^^^^^^^^^^
1659 $domain = parse_url($url,PHP_URL_HOST
);
1660 if ($domain=='youtube.com' || $domain=='www.youtube.com')
1662 parse_str(parse_url($url,PHP_URL_QUERY
), $params); // Extract video ID and get thumbnail
1663 if (!empty($params['v'])) return array('src'=>'https://img.youtube.com/vi/'.$params['v'].'/default.jpg',
1664 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1666 if ($domain=='youtu.be') // Youtube short links
1668 $path = parse_url($url,PHP_URL_PATH
);
1669 return array('src'=>'https://img.youtube.com/vi'.$path.'/default.jpg',
1670 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1672 if ($domain=='pix.toile-libre.org') // pix.toile-libre.org image hosting
1674 parse_str(parse_url($url,PHP_URL_QUERY
), $params); // Extract image filename.
1675 if (!empty($params) && !empty($params['img'])) return array('src'=>'http://pix.toile-libre.org/upload/thumb/'.urlencode($params['img']),
1676 'href'=>$href,'style'=>'max-width:120px; max-height:150px','alt'=>'pix.toile-libre.org thumbnail');
1679 if ($domain=='imgur.com')
1681 $path = parse_url($url,PHP_URL_PATH
);
1682 if (startsWith($path,'/a/')) return array(); // Thumbnails for albums are not available.
1683 if (startsWith($path,'/r/')) return array('src'=>'https://i.imgur.com/'.basename($path).'s.jpg',
1684 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1685 if (startsWith($path,'/gallery/')) return array('src'=>'https://i.imgur.com'.substr($path,8).'s.jpg',
1686 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1688 if (substr_count($path,'/')==1) return array('src'=>'https://i.imgur.com/'.substr($path,1).'s.jpg',
1689 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1691 if ($domain=='i.imgur.com')
1693 $pi = pathinfo(parse_url($url,PHP_URL_PATH
));
1694 if (!empty($pi['filename'])) return array('src'=>'https://i.imgur.com/'.$pi['filename'].'s.jpg',
1695 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1697 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
1699 if (strpos($url,'dailymotion.com/video/')!==false)
1701 $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
1702 return array('src'=>$thumburl,
1703 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'DailyMotion thumbnail');
1706 if (endsWith($domain,'.imageshack.us'))
1708 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION
));
1709 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1711 $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
1712 return array('src'=>$thumburl,
1713 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'imageshack.us thumbnail');
1717 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1718 // So we deport the thumbnail generation in order not to slow down page generation
1719 // (and we also cache the thumbnail)
1721 if (! $conf->get('thumbnail.enable_localcache')) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1723 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
1724 || $domain=='vimeo.com'
1725 || $domain=='ted.com' || endsWith($domain,'.ted.com')
1726 || $domain=='xkcd.com' || endsWith($domain,'.xkcd.com')
1729 if ($domain=='vimeo.com')
1730 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1731 $path = parse_url($url,PHP_URL_PATH
);
1732 if (!preg_match('!/\d+.+?!',$path)) return array(); // This is not a single video URL.
1734 if ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
1735 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1736 $path = parse_url($url,PHP_URL_PATH
);
1737 if (!preg_match('!/\d+.+?!',$path)) return array();
1739 if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
1740 { // Make sure this TED URL points to a video (/talks/...)
1741 $path = parse_url($url,PHP_URL_PATH
);
1742 if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
1744 $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)
1745 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1746 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1749 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1750 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1751 // But using the extension will do.
1752 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION
));
1753 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1755 $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)
1756 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1757 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1759 return array(); // No thumbnail.
1764 // Returns the HTML code to display a thumbnail for a link
1765 // with a link to the original URL.
1766 // Understands various services (youtube.com...)
1767 // Input: $url = URL for which the thumbnail must be found.
1768 // $href = if provided, this URL will be followed instead of $url
1769 // Returns '' if no thumbnail available.
1770 function thumbnail($url,$href=false)
1774 $t = computeThumbnail($conf, $url,$href);
1775 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1777 $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"';
1778 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1779 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1780 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1781 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1786 // Returns the HTML code to display a thumbnail for a link
1787 // for the picture wall (using lazy image loading)
1788 // Understands various services (youtube.com...)
1789 // Input: $url = URL for which the thumbnail must be found.
1790 // $href = if provided, this URL will be followed instead of $url
1791 // Returns '' if no thumbnail available.
1792 function lazyThumbnail($conf, $url,$href=false)
1796 $t = computeThumbnail($conf, $url,$href);
1797 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1799 $html='<a href="'.escape($t['href']).'">';
1802 $html.='<img class="b-lazy" src="#" data-src="'.escape($t['src']).'"';
1804 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1805 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1806 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1807 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1810 // No-JavaScript fallback.
1811 $html.='<noscript><img src="'.escape($t['src']).'"';
1812 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1813 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1814 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1815 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1816 $html.='></noscript></a>';
1824 * This function should NEVER be called if the file data/config.php exists.
1826 * @param ConfigManager $conf Configuration Manager instance.
1827 * @param SessionManager $sessionManager SessionManager instance
1829 function install($conf, $sessionManager) {
1830 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1831 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1834 // This part makes sure sessions works correctly.
1835 // (Because on some hosts, session.save_path may not be set correctly,
1836 // or we may not have write access to it.)
1837 if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working'))
1839 // Step 2: Check if data in session is correct.
1841 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1842 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1843 'and that you have write access to it.<br>'.
1844 'It currently points to %s.<br>'.
1845 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1846 'or any custom hostname without a dot causes cookie storage to fail. '.
1847 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1849 $msg = sprintf($msg, session_save_path());
1851 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1854 if (!isset($_SESSION['session_tested']))
1855 { // Step 1 : Try to store data in session and reload page.
1856 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1857 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1859 if (isset($_GET['test_session']))
1860 { // Step 3: Sessions are OK. Remove test parameter from URL.
1861 header('Location: '.index_url($_SERVER));
1865 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1868 if (!empty($_POST['continent']) && !empty($_POST['city'])
1869 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1871 $tz = $_POST['continent'].'/'.$_POST['city'];
1873 $conf->set('general.timezone', $tz);
1874 $login = $_POST['setlogin'];
1875 $conf->set('credentials.login', $login);
1876 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1877 $conf->set('credentials.salt', $salt);
1878 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
1879 if (!empty($_POST['title'])) {
1880 $conf->set('general.title', escape($_POST['title']));
1882 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
1884 $conf->set('translation.language', escape($_POST['language']));
1885 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1886 $conf->set('api.enabled', !empty($_POST['enableApi']));
1889 generate_api_secret(
1890 $conf->get('credentials.login'),
1891 $conf->get('credentials.salt')
1895 // Everything is ok, let's create config file.
1896 $conf->write($loginManager->isLoggedIn());
1898 catch(Exception
$e) {
1900 'ERROR while writing config file after installation.' . PHP_EOL
.
1904 // TODO: do not handle exceptions/errors in JS.
1905 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1908 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
1912 $PAGE = new PageBuilder($conf, null, $sessionManager->generateToken());
1913 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1914 $PAGE->assign('continents', $continents);
1915 $PAGE->assign('cities', $cities);
1916 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1917 $PAGE->renderPage('install');
1922 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
1923 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1924 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
1925 * This function is called by passing the URL:
1926 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1927 * [URL] is the URL of the link (e.g. a flickr page)
1928 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1929 * The function below will fetch the image from the webservice and store it in the cache.
1931 * @param ConfigManager $conf Configuration Manager instance,
1933 function genThumbnail($conf)
1935 // Make sure the parameters in the URL were generated by us.
1936 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt'));
1937 if ($sign!=$_GET['hmac']) die('Naughty boy!');
1939 $cacheDir = $conf->get('resource.thumbnails_cache', 'cache');
1940 // Let's see if we don't already have the image for this URL in the cache.
1941 $thumbname=hash('sha1',$_GET['url']).'.jpg';
1942 if (is_file($cacheDir .'/'. $thumbname))
1943 { // We have the thumbnail, just serve it:
1944 header('Content-Type: image/jpeg');
1945 echo file_get_contents($cacheDir .'/'. $thumbname);
1948 // We may also serve a blank image (if service did not respond)
1949 $blankname=hash('sha1',$_GET['url']).'.gif';
1950 if (is_file($cacheDir .'/'. $blankname))
1952 header('Content-Type: image/gif');
1953 echo file_get_contents($cacheDir .'/'. $blankname);
1957 // Otherwise, generate the thumbnail.
1958 $url = $_GET['url'];
1959 $domain = parse_url($url,PHP_URL_HOST
);
1961 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
1963 // Crude replacement to handle new flickr domain policy (They prefer www. now)
1964 $url = str_replace('http://flickr.com/','http://www.flickr.com/',$url);
1966 // Is this a link to an image, or to a flickr page ?
1968 if (endsWith(parse_url($url, PHP_URL_PATH
), '.jpg'))
1969 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
1970 preg_match('!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
1971 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
1973 else // This is a flickr page (html)
1975 // Get the flickr html page.
1976 list($headers, $content) = get_http_response($url, 20);
1977 if (strpos($headers[0], '200 OK') !== false)
1979 // flickr now nicely provides the URL of the thumbnail in each flickr page.
1980 preg_match('!<link rel=\"image_src\" href=\"(.+?)\"!', $content, $matches);
1981 if (!empty($matches[1])) $imageurl=$matches[1];
1983 // In albums (and some other pages), the link rel="image_src" is not provided,
1984 // but flickr provides:
1985 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
1988 preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!', $content, $matches);
1989 if (!empty($matches[1])) $imageurl=$matches[1];
1995 { // Let's download the image.
1996 // Image is 240x120, so 10 seconds to download should be enough.
1997 list($headers, $content) = get_http_response($imageurl, 10);
1998 if (strpos($headers[0], '200 OK') !== false) {
1999 // Save image to cache.
2000 file_put_contents($cacheDir .'/'. $thumbname, $content);
2001 header('Content-Type: image/jpeg');
2008 elseif ($domain=='vimeo.com' )
2010 // This is more complex: we have to perform a HTTP request, then parse the result.
2011 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2012 $vid = substr(parse_url($url,PHP_URL_PATH
),1);
2013 list($headers, $content) = get_http_response('https://vimeo.com/api/v2/video/'.escape($vid).'.php', 5);
2014 if (strpos($headers[0], '200 OK') !== false) {
2015 $t = unserialize($content);
2016 $imageurl = $t[0]['thumbnail_medium'];
2017 // Then we download the image and serve it to our client.
2018 list($headers, $content) = get_http_response($imageurl, 10);
2019 if (strpos($headers[0], '200 OK') !== false) {
2020 // Save image to cache.
2021 file_put_contents($cacheDir .'/'. $thumbname, $content);
2022 header('Content-Type: image/jpeg');
2029 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
2031 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2032 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2033 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2034 list($headers, $content) = get_http_response($url, 5);
2035 if (strpos($headers[0], '200 OK') !== false) {
2036 // Extract the link to the thumbnail
2037 preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!', $content, $matches);
2038 if (!empty($matches[1]))
2039 { // Let's download the image.
2040 $imageurl=$matches[1];
2041 // No control on image size, so wait long enough
2042 list($headers, $content) = get_http_response($imageurl, 20);
2043 if (strpos($headers[0], '200 OK') !== false) {
2044 $filepath = $cacheDir .'/'. $thumbname;
2045 file_put_contents($filepath, $content); // Save image to cache.
2046 if (resizeImage($filepath))
2048 header('Content-Type: image/jpeg');
2049 echo file_get_contents($filepath);
2057 elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
2059 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2060 // http://xkcd.com/327/
2061 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2062 list($headers, $content) = get_http_response($url, 5);
2063 if (strpos($headers[0], '200 OK') !== false) {
2064 // Extract the link to the thumbnail
2065 preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!', $content, $matches);
2066 if (!empty($matches[1]))
2067 { // Let's download the image.
2068 $imageurl=$matches[1];
2069 // No control on image size, so wait long enough
2070 list($headers, $content) = get_http_response($imageurl, 20);
2071 if (strpos($headers[0], '200 OK') !== false) {
2072 $filepath = $cacheDir.'/'.$thumbname;
2073 // Save image to cache.
2074 file_put_contents($filepath, $content);
2075 if (resizeImage($filepath))
2077 header('Content-Type: image/jpeg');
2078 echo file_get_contents($filepath);
2088 // For all other domains, we try to download the image and make a thumbnail.
2089 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2090 list($headers, $content) = get_http_response($url, 30);
2091 if (strpos($headers[0], '200 OK') !== false) {
2092 $filepath = $cacheDir .'/'.$thumbname;
2093 // Save image to cache.
2094 file_put_contents($filepath, $content);
2095 if (resizeImage($filepath))
2097 header('Content-Type: image/jpeg');
2098 echo file_get_contents($filepath);
2105 // Otherwise, return an empty image (8x8 transparent gif)
2106 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
2107 // Also put something in cache so that this URL is not requested twice.
2108 file_put_contents($cacheDir .'/'. $blankname, $blankgif);
2109 header('Content-Type: image/gif');
2113 // Make a thumbnail of the image (to width: 120 pixels)
2114 // Returns true if success, false otherwise.
2115 function resizeImage($filepath)
2117 if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
2119 // Trick: some stupid people rename GIF as JPEG... or else.
2120 // So we really try to open each image type whatever the extension is.
2121 $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
2123 $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
2124 $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
2125 $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
2126 if (!$im) return false; // Unable to open image (corrupted or not an image)
2129 $ystart = 0; $yheight=$h;
2130 if ($h>$w) { $ystart
= ($h
/2)-($w
/2); $yheight
=$w
/2; }
2131 $nw = 120; // Desired width
2132 $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
2134 $im2 = imagecreatetruecolor($nw,$nh);
2135 imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
2136 imageinterlace($im2,true); // For progressive JPEG.
2137 $tempname=$filepath.'_TEMP.jpg';
2138 imagejpeg($im2, $tempname, 90);
2142 rename($tempname,$filepath); // Overwrite original picture with thumbnail.
2146 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf
); exit; } // Thumbnail generation/cache does not need the link database.
2147 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf
); exit; }
2148 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
2149 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
2153 $history = new History($conf->get('resource.history'));
2154 } catch(Exception
$e) {
2155 die($e->getMessage());
2158 $linkDb = new LinkDB(
2159 $conf->get('resource.datastore'),
2160 $loginManager->isLoggedIn(),
2161 $conf->get('privacy.hide_public_links'),
2162 $conf->get('redirector.url'),
2163 $conf->get('redirector.encode_url')
2166 $container = new \Slim\
Container();
2167 $container['conf'] = $conf;
2168 $container['plugins'] = $pluginManager;
2169 $container['history'] = $history;
2170 $app = new \Slim\
App($container);
2173 $app->group('/api/v1', function() {
2174 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
2175 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
2176 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
2177 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
2178 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
2179 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
2180 $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
2181 })->add('\Shaarli\Api\ApiMiddleware');
2183 $response = $app->run(true);
2184 // Hack to make Slim and Shaarli router work together:
2185 // If a Slim route isn't found and NOT API call, we call renderPage().
2186 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
2187 // We use UTF-8 for proper international characters handling.
2188 header('Content-Type: text/html; charset=utf-8');
2189 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
2191 $app->respond($response);