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\LoginManager
;
82 use \Shaarli\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($_SESSION, $_COOKIE, WEB_PATH
, $clientIpId, STAY_SIGNED_IN_TOKEN
);
185 * Adapter function for PageBuilder
187 * TODO: update PageBuilder and tests
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 // Login/password is OK.
207 $loginManager->handleSuccessfulLogin($_SERVER);
209 // If user wants to keep the session cookie even after the browser closes:
210 if (!empty($_POST['longlastingsession'])) {
211 $_SESSION['longlastingsession'] = 31536000; // (31536000 seconds = 1 year)
212 $expiration = time() +
$_SESSION['longlastingsession']; // calculate relative cookie expiration (1 year from now)
213 setcookie($sessionManager::$LOGGED_IN_COOKIE, STAY_SIGNED_IN_TOKEN
, $expiration, WEB_PATH
);
214 $_SESSION['expires_on'] = $expiration; // Set session expiration on server-side.
217 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
218 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
220 session_set_cookie_params($_SESSION['longlastingsession'],$cookiedir,$_SERVER['SERVER_NAME']); // Set session cookie expiration on client side
221 // Note: Never forget the trailing slash on the cookie path!
222 session_regenerate_id(true); // Send cookie with new expiration date to browser.
224 else // Standard session expiration (=when browser closes)
226 $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
227 session_set_cookie_params(0,$cookiedir,$_SERVER['SERVER_NAME']); // 0 means "When browser closes"
228 session_regenerate_id(true);
231 // Optional redirect after login:
232 if (isset($_GET['post'])) {
233 $uri = '?post='. urlencode($_GET['post']);
234 foreach (array('description', 'source', 'title', 'tags') as $param) {
235 if (!empty($_GET[$param])) {
236 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
239 header('Location: '. $uri);
243 if (isset($_GET['edit_link'])) {
244 header('Location: ?edit_link='. escape($_GET['edit_link']));
248 if (isset($_POST['returnurl'])) {
249 // Prevent loops over login screen.
250 if (strpos($_POST['returnurl'], 'do=login') === false) {
251 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
255 header('Location: ?'); exit;
257 $loginManager->handleFailedLogin($_SERVER);
258 $redir = '&username='. urlencode($_POST['login']);
259 if (isset($_GET['post'])) {
260 $redir .= '&post=' . urlencode($_GET['post']);
261 foreach (array('description', 'source', 'title', 'tags') as $param) {
262 if (!empty($_GET[$param])) {
263 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
267 // Redirect to login screen.
268 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
273 // ------------------------------------------------------------------------------------------
274 // Token management for XSRF protection
275 // Token should be used in any form which acts on data (create,update,delete,import...).
276 if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
279 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
280 * Gives the last 7 days (which have links).
281 * This RSS feed cannot be filtered.
283 * @param ConfigManager $conf Configuration Manager instance
284 * @param LoginManager $loginManager LoginManager instance
286 function showDailyRSS($conf, $loginManager) {
288 $query = $_SERVER['QUERY_STRING'];
289 $cache = new CachedPage(
290 $conf->get('config.PAGE_CACHE'),
292 startsWith($query,'do=dailyrss') && !$loginManager->isLoggedIn()
294 $cached = $cache->cachedVersion();
295 if (!empty($cached)) {
300 // If cached was not found (or not usable), then read the database and build the response:
301 // Read links from database (and filter private links if used it not logged in).
302 $LINKSDB = new LinkDB(
303 $conf->get('resource.datastore'),
304 $loginManager->isLoggedIn(),
305 $conf->get('privacy.hide_public_links'),
306 $conf->get('redirector.url'),
307 $conf->get('redirector.encode_url')
310 /* Some Shaarlies may have very few links, so we need to look
311 back in time until we have enough days ($nb_of_days).
313 $nb_of_days = 7; // We take 7 days.
314 $today = date('Ymd');
317 foreach ($LINKSDB as $link) {
318 $day = $link['created']->format('Ymd'); // Extract day (without time)
319 if (strcmp($day, $today) < 0) {
320 if (empty($days[$day])) {
321 $days[$day] = array();
323 $days[$day][] = $link;
326 if (count($days) > $nb_of_days) {
327 break; // Have we collected enough days?
331 // Build the RSS feed.
332 header('Content-Type: application/rss+xml; charset=utf-8');
333 $pageaddr = escape(index_url($_SERVER));
334 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
336 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
337 echo '<link>'. $pageaddr .'</link>';
338 echo '<description>Daily shared links</description>';
339 echo '<language>en-en</language>';
340 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL
;
343 foreach ($days as $day => $links) {
344 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
345 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
347 // We pre-format some fields for proper output.
348 foreach ($links as &$link) {
349 $link['formatedDescription'] = format_description(
350 $link['description'],
351 $conf->get('redirector.url'),
352 $conf->get('redirector.encode_url')
354 $link['thumbnail'] = thumbnail($conf, $link['url']);
355 $link['timestamp'] = $link['created']->getTimestamp();
356 if (startsWith($link['url'], '?')) {
357 $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
361 // Then build the HTML for this day:
363 $tpl->assign('title', $conf->get('general.title'));
364 $tpl->assign('daydate', $dayDate->getTimestamp());
365 $tpl->assign('absurl', $absurl);
366 $tpl->assign('links', $links);
367 $tpl->assign('rssdate', escape($dayDate->format(DateTime
::RSS
)));
368 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
369 $html = $tpl->draw('dailyrss', true);
371 echo $html . PHP_EOL
;
373 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
375 $cache->cache(ob_get_contents());
381 * Show the 'Daily' page.
383 * @param PageBuilder $pageBuilder Template engine wrapper.
384 * @param LinkDB $LINKSDB LinkDB instance.
385 * @param ConfigManager $conf Configuration Manager instance.
386 * @param PluginManager $pluginManager Plugin Manager instane.
388 function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager)
390 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
391 if (isset($_GET['day'])) {
395 $days = $LINKSDB->days();
396 $i = array_search($day, $days);
397 if ($i === false && count($days)) {
398 // no links for day, but at least one day with links
399 $i = count($days) - 1;
407 $previousday=$days[$i - 1];
409 if ($i < count($days) - 1) {
410 $nextday = $days[$i +
1];
414 $linksToDisplay = $LINKSDB->filterDay($day);
415 } catch (Exception
$exc) {
417 $linksToDisplay = array();
420 // We pre-format some fields for proper output.
421 foreach($linksToDisplay as $key => $link) {
422 $taglist = explode(' ',$link['tags']);
423 uasort($taglist, 'strcasecmp');
424 $linksToDisplay[$key]['taglist']=$taglist;
425 $linksToDisplay[$key]['formatedDescription'] = format_description(
426 $link['description'],
427 $conf->get('redirector.url'),
428 $conf->get('redirector.encode_url')
430 $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
431 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
434 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
436 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
437 'linksToDisplay' => $linksToDisplay,
438 'day' => $dayDate->getTimestamp(),
439 'dayDate' => $dayDate,
440 'previousday' => $previousday,
441 'nextday' => $nextday,
444 /* Hook is called before column construction so that plugins don't have
445 to deal with columns. */
446 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
448 /* We need to spread the articles on 3 columns.
449 I did not want to use a JavaScript lib like http://masonry.desandro.com/
450 so I manually spread entries with a simple method: I roughly evaluate the
451 height of a div according to title and description length.
453 $columns = array(array(), array(), array()); // Entries to display, for each column.
454 $fill = array(0, 0, 0); // Rough estimate of columns fill.
455 foreach($data['linksToDisplay'] as $key => $link) {
456 // Roughly estimate length of entry (by counting characters)
457 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
458 // Description: 836 characters gives roughly 342 pixel height.
459 // This is not perfect, but it's usually OK.
460 $length = strlen($link['title']) +
(342 * strlen($link['description'])) / 836;
461 if ($link['thumbnail']) {
462 $length +
= 100; // 1 thumbnails roughly takes 100 pixels height.
464 // Then put in column which is the less filled:
465 $smallest = min($fill); // find smallest value in array.
466 $index = array_search($smallest, $fill); // find index of this smallest value.
467 array_push($columns[$index], $link); // Put entry in this column.
468 $fill[$index] +
= $length;
471 $data['cols'] = $columns;
473 foreach ($data as $key => $value) {
474 $pageBuilder->assign($key, $value);
477 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
478 $pageBuilder->renderPage('daily');
483 * Renders the linklist
485 * @param pageBuilder $PAGE pageBuilder instance.
486 * @param LinkDB $LINKSDB LinkDB instance.
487 * @param ConfigManager $conf Configuration Manager instance.
488 * @param PluginManager $pluginManager Plugin Manager instance.
490 function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager) {
491 buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager, $loginManager);
492 $PAGE->renderPage('linklist');
496 * Render HTML page (according to URL parameters and user rights)
498 * @param ConfigManager $conf Configuration Manager instance.
499 * @param PluginManager $pluginManager Plugin Manager instance,
500 * @param LinkDB $LINKSDB
501 * @param History $history instance
502 * @param SessionManager $sessionManager SessionManager instance
503 * @param LoginManager $loginManager LoginManager instance
505 function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
507 $updater = new Updater(
508 read_updates_file($conf->get('resource.updates')),
511 $loginManager->isLoggedIn()
514 $newUpdates = $updater->update();
515 if (! empty($newUpdates)) {
517 $conf->get('resource.updates'),
518 $updater->getDoneUpdates()
522 catch(Exception
$e) {
523 die($e->getMessage());
526 $PAGE = new PageBuilder($conf, $LINKSDB, $sessionManager->generateToken());
527 $PAGE->assign('linkcount', count($LINKSDB));
528 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
529 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
531 // Determine which page will be rendered.
532 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
533 $targetPage = Router
::findPage($query, $_GET, $loginManager->isLoggedIn());
536 // if the user isn't logged in
537 !$loginManager->isLoggedIn() &&
538 // and Shaarli doesn't have public content...
539 $conf->get('privacy.hide_public_links') &&
540 // and is configured to enforce the login
541 $conf->get('privacy.force_login') &&
542 // and the current page isn't already the login page
543 $targetPage !== Router
::$PAGE_LOGIN &&
544 // and the user is not requesting a feed (which would lead to a different content-type as expected)
545 $targetPage !== Router
::$PAGE_FEED_ATOM &&
546 $targetPage !== Router
::$PAGE_FEED_RSS
548 // force current page to be the login page
549 $targetPage = Router
::$PAGE_LOGIN;
552 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
553 // Then assign generated data to RainTPL.
554 $common_hooks = array(
560 foreach($common_hooks as $name) {
561 $plugin_data = array();
562 $pluginManager->executeHooks('render_' . $name, $plugin_data,
564 'target' => $targetPage,
565 'loggedin' => $loginManager->isLoggedIn()
568 $PAGE->assign('plugins_' . $name, $plugin_data);
571 // -------- Display login form.
572 if ($targetPage == Router
::$PAGE_LOGIN)
574 if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
575 if (isset($_GET['username'])) {
576 $PAGE->assign('username', escape($_GET['username']));
578 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
579 // add default state of the 'remember me' checkbox
580 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
581 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
582 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
583 $PAGE->renderPage('loginform');
586 // -------- User wants to logout.
587 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
589 invalidateCaches($conf->get('resource.page_cache'));
590 $sessionManager->logout(WEB_PATH
);
591 header('Location: ?');
595 // -------- Picture wall
596 if ($targetPage == Router
::$PAGE_PICWALL)
598 // Optionally filter the results:
599 $links = $LINKSDB->filterSearch($_GET);
600 $linksToDisplay = array();
602 // Get only links which have a thumbnail.
603 foreach($links as $link)
605 $permalink='?'.$link['shorturl'];
606 $thumb=lazyThumbnail($conf, $link['url'],$permalink);
607 if ($thumb!='') // Only output links which have a thumbnail.
609 $link['thumbnail']=$thumb; // Thumbnail HTML code.
610 $linksToDisplay[]=$link; // Add to array.
615 'linksToDisplay' => $linksToDisplay,
617 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => $loginManager->isLoggedIn()));
619 foreach ($data as $key => $value) {
620 $PAGE->assign($key, $value);
623 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
624 $PAGE->renderPage('picwall');
628 // -------- Tag cloud
629 if ($targetPage == Router
::$PAGE_TAGCLOUD)
631 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
632 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
633 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
635 // We sort tags alphabetically, then choose a font size according to count.
636 // First, find max value.
638 foreach ($tags as $value) {
639 $maxcount = max($maxcount, $value);
642 alphabetical_sort($tags, false, true);
645 foreach($tags as $key => $value) {
646 if (in_array($key, $filteringTags)) {
649 // Tag font size scaling:
650 // default 15 and 30 logarithm bases affect scaling,
651 // 22 and 6 are arbitrary font sizes for max and min sizes.
652 $size = log($value, 15) / log($maxcount, 30) * 2.2 +
0.8;
653 $tagList[$key] = array(
655 'size' => number_format($size, 2, '.', ''),
659 $searchTags = implode(' ', escape($filteringTags));
661 'search_tags' => $searchTags,
664 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
666 foreach ($data as $key => $value) {
667 $PAGE->assign($key, $value);
670 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
671 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
672 $PAGE->renderPage('tag.cloud');
677 if ($targetPage == Router
::$PAGE_TAGLIST)
679 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
680 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
681 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
682 foreach ($filteringTags as $tag) {
683 if (array_key_exists($tag, $tags)) {
688 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
689 alphabetical_sort($tags, false, true);
692 $searchTags = implode(' ', escape($filteringTags));
694 'search_tags' => $searchTags,
697 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
699 foreach ($data as $key => $value) {
700 $PAGE->assign($key, $value);
703 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
704 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
705 $PAGE->renderPage('tag.list');
710 if ($targetPage == Router
::$PAGE_DAILY) {
711 showDaily($PAGE, $LINKSDB, $conf, $pluginManager);
714 // ATOM and RSS feed.
715 if ($targetPage == Router
::$PAGE_FEED_ATOM || $targetPage == Router
::$PAGE_FEED_RSS) {
716 $feedType = $targetPage == Router
::$PAGE_FEED_RSS ? FeedBuilder
::$FEED_RSS : FeedBuilder
::$FEED_ATOM;
717 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
720 $query = $_SERVER['QUERY_STRING'];
721 $cache = new CachedPage(
722 $conf->get('resource.page_cache'),
724 startsWith($query,'do='. $targetPage) && !$loginManager->isLoggedIn()
726 $cached = $cache->cachedVersion();
727 if (!empty($cached)) {
733 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, $loginManager->isLoggedIn());
734 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE
, 0)));
735 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
736 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
737 $data = $feedGenerator->buildData();
739 // Process plugin hook.
740 $pluginManager->executeHooks('render_feed', $data, array(
741 'loggedin' => $loginManager->isLoggedIn(),
742 'target' => $targetPage,
745 // Render the template.
746 $PAGE->assignAll($data);
747 $PAGE->renderPage('feed.'. $feedType);
748 $cache->cache(ob_get_contents());
753 // Display opensearch plugin (XML)
754 if ($targetPage == Router
::$PAGE_OPENSEARCH) {
755 header('Content-Type: application/xml; charset=utf-8');
756 $PAGE->assign('serverurl', index_url($_SERVER));
757 $PAGE->renderPage('opensearch');
761 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
762 if (isset($_GET['addtag']))
764 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
765 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET
['addtag'])); exit; } // In case browser does not send HTTP_REFERER
766 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY
), $params);
768 // Prevent redirection loop
769 if (isset($params['addtag'])) {
770 unset($params['addtag']);
773 // Check if this tag is already in the search query and ignore it if it is.
774 // Each tag is always separated by a space
775 if (isset($params['searchtags'])) {
776 $current_tags = explode(' ', $params['searchtags']);
778 $current_tags = array();
781 foreach ($current_tags as $value) {
782 if ($value === $_GET['addtag']) {
787 // Append the tag if necessary
788 if (empty($params['searchtags'])) {
789 $params['searchtags'] = trim($_GET['addtag']);
792 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
795 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
796 header('Location: ?'.http_build_query($params));
800 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
801 if (isset($_GET['removetag'])) {
802 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
803 if (empty($_SERVER['HTTP_REFERER'])) {
804 header('Location: ?');
808 // In case browser does not send HTTP_REFERER
809 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
811 // Prevent redirection loop
812 if (isset($params['removetag'])) {
813 unset($params['removetag']);
816 if (isset($params['searchtags'])) {
817 $tags = explode(' ', $params['searchtags']);
818 // Remove value from array $tags.
819 $tags = array_diff($tags, array($_GET['removetag']));
820 $params['searchtags'] = implode(' ',$tags);
822 if (empty($params['searchtags'])) {
823 unset($params['searchtags']);
826 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
828 header('Location: ?'.http_build_query($params));
832 // -------- User wants to change the number of links per page (linksperpage=...)
833 if (isset($_GET['linksperpage'])) {
834 if (is_numeric($_GET['linksperpage'])) {
835 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
838 if (! empty($_SERVER['HTTP_REFERER'])) {
839 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
843 header('Location: '. $location);
847 // -------- User wants to see only private links (toggle)
848 if (isset($_GET['visibility'])) {
849 if ($_GET['visibility'] === 'private') {
850 // Visibility not set or not already private, set private, otherwise reset it
851 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
852 // See only private links
853 $_SESSION['visibility'] = 'private';
855 unset($_SESSION['visibility']);
857 } elseif ($_GET['visibility'] === 'public') {
858 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
859 // See only public links
860 $_SESSION['visibility'] = 'public';
862 unset($_SESSION['visibility']);
866 if (! empty($_SERVER['HTTP_REFERER'])) {
867 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
871 header('Location: '. $location);
875 // -------- User wants to see only untagged links (toggle)
876 if (isset($_GET['untaggedonly'])) {
877 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
879 if (! empty($_SERVER['HTTP_REFERER'])) {
880 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
884 header('Location: '. $location);
888 // -------- Handle other actions allowed for non-logged in users:
889 if (!$loginManager->isLoggedIn())
891 // User tries to post new link but is not logged in:
892 // Show login screen, then redirect to ?post=...
893 if (isset($_GET['post']))
895 header( // Redirect to login page, then back to post link.
896 'Location: ?do=login&post='.urlencode($_GET['post']).
897 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
898 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
899 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
900 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
905 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
906 if (isset($_GET['edit_link'])) {
907 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
911 exit; // Never remove this one! All operations below are reserved for logged in user.
914 // -------- All other functions are reserved for the registered user:
916 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
917 if ($targetPage == Router
::$PAGE_TOOLS)
920 'pageabsaddr' => index_url($_SERVER),
921 'sslenabled' => is_https($_SERVER),
923 $pluginManager->executeHooks('render_tools', $data);
925 foreach ($data as $key => $value) {
926 $PAGE->assign($key, $value);
929 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
930 $PAGE->renderPage('tools');
934 // -------- User wants to change his/her password.
935 if ($targetPage == Router
::$PAGE_CHANGEPASSWORD)
937 if ($conf->get('security.open_shaarli')) {
938 die(t('You are not supposed to change a password on an Open Shaarli.'));
941 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
943 if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away!
945 // Make sure old password is correct.
946 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
947 if ($oldhash!= $conf->get('credentials.hash')) {
948 echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>';
952 // Salt renders rainbow-tables attacks useless.
953 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
954 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt')));
956 $conf->write($loginManager->isLoggedIn());
958 catch(Exception
$e) {
960 'ERROR while writing config file after changing password.' . PHP_EOL
.
964 // TODO: do not handle exceptions/errors in JS.
965 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
968 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
971 else // show the change password form.
973 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
974 $PAGE->renderPage('changepassword');
979 // -------- User wants to change configuration
980 if ($targetPage == Router
::$PAGE_CONFIGURE)
982 if (!empty($_POST['title']) )
984 if (!$sessionManager->checkToken($_POST['token'])) {
985 die(t('Wrong token.')); // Go away!
988 if (!empty($_POST['continent']) && !empty($_POST['city'])
989 && isTimeZoneValid($_POST['continent'], $_POST['city'])
991 $tz = $_POST['continent'] . '/' . $_POST['city'];
993 $conf->set('general.timezone', $tz);
994 $conf->set('general.title', escape($_POST['title']));
995 $conf->set('general.header_link', escape($_POST['titleLink']));
996 $conf->set('resource.theme', escape($_POST['theme']));
997 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
998 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
999 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1000 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1001 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
1002 $conf->set('api.enabled', !empty($_POST['enableApi']));
1003 $conf->set('api.secret', escape($_POST['apiSecret']));
1004 $conf->set('translation.language', escape($_POST['language']));
1007 $conf->write($loginManager->isLoggedIn());
1008 $history->updateSettings();
1009 invalidateCaches($conf->get('resource.page_cache'));
1011 catch(Exception
$e) {
1013 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1017 // TODO: do not handle exceptions/errors in JS.
1018 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1021 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1024 else // Show the configuration form.
1026 $PAGE->assign('title', $conf->get('general.title'));
1027 $PAGE->assign('theme', $conf->get('resource.theme'));
1028 $PAGE->assign('theme_available', ThemeUtils
::getThemes($conf->get('resource.raintpl_tpl')));
1029 list($continents, $cities) = generateTimeZoneData(
1030 timezone_identifiers_list(),
1031 $conf->get('general.timezone')
1033 $PAGE->assign('continents', $continents);
1034 $PAGE->assign('cities', $cities);
1035 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
1036 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1037 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1038 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1039 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1040 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1041 $PAGE->assign('api_secret', $conf->get('api.secret'));
1042 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1043 $PAGE->assign('language', $conf->get('translation.language'));
1044 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
1045 $PAGE->renderPage('configure');
1050 // -------- User wants to rename a tag or delete it
1051 if ($targetPage == Router
::$PAGE_CHANGETAG)
1053 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1054 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1055 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
1056 $PAGE->renderPage('changetag');
1060 if (!$sessionManager->checkToken($_POST['token'])) {
1061 die(t('Wrong token.'));
1064 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), escape($_POST['totag']));
1065 $LINKSDB->save($conf->get('resource.page_cache'));
1066 foreach ($alteredLinks as $link) {
1067 $history->updateLink($link);
1069 $delete = empty($_POST['totag']);
1070 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1071 $count = count($alteredLinks);
1073 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d links.', $count), $count)
1074 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d links.', $count), $count);
1075 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1079 // -------- User wants to add a link without using the bookmarklet: Show form.
1080 if ($targetPage == Router
::$PAGE_ADDLINK)
1082 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1083 $PAGE->renderPage('addlink');
1087 // -------- User clicked the "Save" button when editing a link: Save link to database.
1088 if (isset($_POST['save_edit']))
1091 if (! $sessionManager->checkToken($_POST['token'])) {
1092 die(t('Wrong token.'));
1095 // lf_id should only be present if the link exists.
1096 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
1097 // Linkdate is kept here to:
1098 // - use the same permalink for notes as they're displayed when creating them
1099 // - let users hack creation date of their posts
1100 // See: https://shaarli.readthedocs.io/en/master/Various-hacks/#changing-the-timestamp-for-a-shaare
1101 $linkdate = escape($_POST['lf_linkdate']);
1102 if (isset($LINKSDB[$id])) {
1104 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1105 $updated = new DateTime();
1106 $shortUrl = $LINKSDB[$id]['shorturl'];
1110 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1112 $shortUrl = link_small_hash($created, $id);
1116 // Remove multiple spaces.
1117 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
1118 // Remove first '-' char in tags.
1119 $tags = preg_replace('/(^| )\-/', '$1', $tags);
1120 // Remove duplicates.
1121 $tags = implode(' ', array_unique(explode(' ', $tags)));
1123 if (empty(trim($_POST['lf_url
']))) {
1124 $_POST['lf_url
'] = '?' . smallHash($linkdate . $id);
1126 $url = whitelist_protocols(trim($_POST['lf_url
']), $conf->get('security
.allowed_protocols
'));
1130 'title
' => trim($_POST['lf_title
']),
1132 'description
' => $_POST['lf_description
'],
1133 'private' => (isset($_POST['lf_private
']) ? 1 : 0),
1134 'created
' => $created,
1135 'updated
' => $updated,
1136 'tags
' => str_replace(',', ' ', $tags),
1137 'shorturl
' => $shortUrl,
1140 // If title is empty, use the URL as title.
1141 if ($link['title
'] == '') {
1142 $link['title
'] = $link['url
'];
1145 $pluginManager->executeHooks('save_link
', $link);
1147 $LINKSDB[$id] = $link;
1148 $LINKSDB->save($conf->get('resource.page_cache
'));
1150 $history->addLink($link);
1152 $history->updateLink($link);
1155 // If we are called from the bookmarklet, we must close the popup:
1156 if (isset($_GET['source
']) && ($_GET['source
']=='bookmarklet
' || $_GET['source
']=='firefoxsocialapi
')) {
1157 echo '<script
>self
.close();</script
>';
1161 $returnurl = !empty($_POST['returnurl
']) ? $_POST['returnurl
'] : '?';
1162 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST
'], array('addlink
', 'post
', 'edit_link
'));
1163 // Scroll to the link which has been edited.
1164 $location .= '#' . $link['shorturl'];
1165 // After saving the link, redirect to the page the user was on.
1166 header('Location: '. $location);
1170 // -------- User clicked the "Cancel" button when editing a link.
1171 if (isset($_POST['cancel_edit']))
1173 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1174 if (! isset($LINKSDB[$id])) {
1175 header('Location: ?');
1177 // If we are called from the bookmarklet, we must close the popup:
1178 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1179 $link = $LINKSDB[$id];
1180 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1181 // Scroll to the link which has been edited.
1182 $returnurl .= '#'. $link['shorturl'];
1183 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1184 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1188 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1189 if ($targetPage == Router
::$PAGE_DELETELINK)
1191 if (! $sessionManager->checkToken($_GET['token'])) {
1192 die(t('Wrong token.'));
1195 $ids = trim($_GET['lf_linkdate']);
1196 if (strpos($ids, ' ') !== false) {
1197 // multiple, space-separated ids provided
1198 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1200 // only a single id provided
1203 // assert at least one id is given
1205 die('no id provided');
1207 foreach ($ids as $id) {
1208 $id = (int) escape($id);
1209 $link = $LINKSDB[$id];
1210 $pluginManager->executeHooks('delete_link', $link);
1211 unset($LINKSDB[$id]);
1213 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1214 $history->deleteLink($link);
1216 // If we are called from the bookmarklet, we must close the popup:
1217 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1220 if (isset($_SERVER['HTTP_REFERER'])) {
1221 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1222 $location = generateLocation(
1223 $_SERVER['HTTP_REFERER'],
1224 $_SERVER['HTTP_HOST'],
1225 ['delete_link', 'edit_link', $link['shorturl']]
1229 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1233 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1234 if (isset($_GET['edit_link']))
1236 $id = (int) escape($_GET['edit_link']);
1237 $link = $LINKSDB[$id]; // Read database
1238 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
1239 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1242 'link_is_new' => false,
1243 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1244 'tags' => $LINKSDB->linksCountPerTag(),
1246 $pluginManager->executeHooks('render_editlink', $data);
1248 foreach ($data as $key => $value) {
1249 $PAGE->assign($key, $value);
1252 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1253 $PAGE->renderPage('editlink');
1257 // -------- User want to post a new link: Display link edit form.
1258 if (isset($_GET['post'])) {
1259 $url = cleanup_url($_GET['post']);
1261 $link_is_new = false;
1262 // Check if URL is not already in database (in this case, we will edit the existing link)
1263 $link = $LINKSDB->getLinkFromUrl($url);
1266 $link_is_new = true;
1267 $linkdate = strval(date(LinkDB
::LINK_DATE_FORMAT
));
1268 // Get title if it was provided in URL (by the bookmarklet).
1269 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1270 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1271 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1272 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1273 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1274 // 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.)
1275 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1276 // Short timeout to keep the application responsive
1277 // The callback will fill $charset and $title with data from the downloaded page.
1280 $conf->get('general.download_timeout', 30),
1281 $conf->get('general.download_max_size', 4194304),
1282 get_curl_download_callback($charset, $title)
1284 if (! empty($title) && strtolower($charset) != 'utf-8') {
1285 $title = mb_convert_encoding($title, 'utf-8', $charset);
1290 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1291 $title = $conf->get('general.default_note_title', t('Note: '));
1293 $url = escape($url);
1294 $title = escape($title);
1297 'linkdate' => $linkdate,
1300 'description' => $description,
1302 'private' => $private,
1305 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1310 'link_is_new' => $link_is_new,
1311 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1312 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1313 'tags' => $LINKSDB->linksCountPerTag(),
1314 'default_private_links' => $conf->get('privacy.default_private_links', false),
1316 $pluginManager->executeHooks('render_editlink', $data);
1318 foreach ($data as $key => $value) {
1319 $PAGE->assign($key, $value);
1322 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1323 $PAGE->renderPage('editlink');
1327 if ($targetPage == Router
::$PAGE_EXPORT) {
1328 // Export links as a Netscape Bookmarks file
1330 if (empty($_GET['selection'])) {
1331 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1332 $PAGE->renderPage('export');
1336 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1337 $selection = $_GET['selection'];
1338 if (isset($_GET['prepend_note_url'])) {
1339 $prependNoteUrl = $_GET['prepend_note_url'];
1341 $prependNoteUrl = false;
1347 NetscapeBookmarkUtils
::filterAndFormat(
1354 } catch (Exception
$exc) {
1355 header('Content-Type: text/plain; charset=utf-8');
1356 echo $exc->getMessage();
1359 $now = new DateTime();
1360 header('Content-Type: text/html; charset=utf-8');
1362 'Content-disposition: attachment; filename=bookmarks_'
1363 .$selection.'_'.$now->format(LinkDB
::LINK_DATE_FORMAT
).'.html'
1365 $PAGE->assign('date', $now->format(DateTime
::RFC822
));
1366 $PAGE->assign('eol', PHP_EOL
);
1367 $PAGE->assign('selection', $selection);
1368 $PAGE->renderPage('export.bookmarks');
1372 if ($targetPage == Router
::$PAGE_IMPORT) {
1373 // Upload a Netscape bookmark dump to import its contents
1375 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1376 // Show import dialog
1379 get_max_upload_size(
1380 ini_get('post_max_size'),
1381 ini_get('upload_max_filesize'),
1387 get_max_upload_size(
1388 ini_get('post_max_size'),
1389 ini_get('upload_max_filesize'),
1393 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1394 $PAGE->renderPage('import');
1398 // Import bookmarks from an uploaded file
1399 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1400 // The file is too big or some form field may be missing.
1403 'The file you are trying to upload is probably bigger than what this webserver can accept'
1404 .' (%s). Please upload in smaller chunks.'
1406 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1408 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router
::$PAGE_IMPORT .'\';</script>';
1411 if (! $sessionManager->checkToken($_POST['token'])) {
1412 die('Wrong token.');
1414 $status = NetscapeBookmarkUtils
::import(
1421 echo '<script>alert("'.$status.'");document.location=\'?do='
1422 .Router
::$PAGE_IMPORT .'\';</script>';
1426 // Plugin administration page
1427 if ($targetPage == Router
::$PAGE_PLUGINSADMIN) {
1428 $pluginMeta = $pluginManager->getPluginsMeta();
1430 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1431 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v
['order'] !== false; });
1433 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1436 function($a, $b) { return $a
['order'] - $b
['order']; }
1438 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v
['order'] === false; });
1440 $PAGE->assign('enabledPlugins', $enabledPlugins);
1441 $PAGE->assign('disabledPlugins', $disabledPlugins);
1442 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
1443 $PAGE->renderPage('pluginsadmin');
1447 // Plugin administration form action
1448 if ($targetPage == Router
::$PAGE_SAVE_PLUGINSADMIN) {
1450 if (isset($_POST['parameters_form'])) {
1451 unset($_POST['parameters_form']);
1452 foreach ($_POST as $param => $value) {
1453 $conf->set('plugins.'. $param, escape($value));
1457 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1459 $conf->write($loginManager->isLoggedIn());
1460 $history->updateSettings();
1462 catch (Exception
$e) {
1464 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1468 // TODO: do not handle exceptions/errors in JS.
1469 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router
::$PAGE_PLUGINSADMIN .'\';</script>';
1472 header('Location: ?do='. Router
::$PAGE_PLUGINSADMIN);
1476 // Get a fresh token
1477 if ($targetPage == Router
::$GET_TOKEN) {
1478 header('Content-Type:text/plain');
1479 echo $sessionManager->generateToken($conf);
1483 // -------- Otherwise, simply display search form and links:
1484 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
1489 * Template for the list of links (<div id="linklist">)
1490 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1492 * @param pageBuilder $PAGE pageBuilder instance.
1493 * @param LinkDB $LINKSDB LinkDB instance.
1494 * @param ConfigManager $conf Configuration Manager instance.
1495 * @param PluginManager $pluginManager Plugin Manager instance.
1496 * @param LoginManager $loginManager LoginManager instance
1498 function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1500 // Used in templates
1501 if (isset($_GET['searchtags'])) {
1502 if (! empty($_GET['searchtags'])) {
1503 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1505 $searchtags = false;
1510 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1513 if (! empty($_SERVER['QUERY_STRING'])
1514 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1516 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1517 } catch (LinkNotFoundException
$e) {
1518 $PAGE->render404($e->getMessage());
1522 // Filter links according search parameters.
1523 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
1525 'searchtags' => $searchtags,
1526 'searchterm' => $searchterm,
1528 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
1531 // ---- Handle paging.
1533 foreach ($linksToDisplay as $key => $value) {
1537 // Select articles according to paging.
1538 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1539 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1540 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1541 $page = $page < 1 ? 1 : $page;
1542 $page = $page > $pagecount ? $pagecount : $page;
1544 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1545 $end = $i +
$_SESSION['LINKS_PER_PAGE'];
1546 $linkDisp = array();
1547 while ($i<$end && $i<count($keys))
1549 $link = $linksToDisplay[$keys[$i]];
1550 $link['description'] = format_description(
1551 $link['description'],
1552 $conf->get('redirector.url'),
1553 $conf->get('redirector.encode_url')
1555 $classLi = ($i %
2) != 0 ? '' : 'publicLinkHightLight';
1556 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
1557 $link['timestamp'] = $link['created']->getTimestamp();
1558 if (! empty($link['updated'])) {
1559 $link['updated_timestamp'] = $link['updated']->getTimestamp();
1561 $link['updated_timestamp'] = '';
1563 $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY
);
1564 uasort($taglist, 'strcasecmp');
1565 $link['taglist'] = $taglist;
1566 // Check for both signs of a note: starting with ? and 7 chars long.
1567 if ($link['url'][0] === '?' &&
1568 strlen($link['url']) === 7) {
1569 $link['url'] = index_url($_SERVER) . $link['url'];
1572 $linkDisp[$keys[$i]] = $link;
1576 // Compute paging navigation
1577 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
1578 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1579 $previous_page_url = '';
1580 if ($i != count($keys)) {
1581 $previous_page_url = '?page=' . ($page+
1) . $searchtermUrl . $searchtagsUrl;
1585 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1588 // Fill all template fields.
1590 'previous_page_url' => $previous_page_url,
1591 'next_page_url' => $next_page_url,
1592 'page_current' => $page,
1593 'page_max' => $pagecount,
1594 'result_count' => count($linksToDisplay),
1595 'search_term' => $searchterm,
1596 'search_tags' => $searchtags,
1597 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
1598 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
1599 'links' => $linkDisp,
1602 // If there is only a single link, we change on-the-fly the title of the page.
1603 if (count($linksToDisplay) == 1) {
1604 $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
1605 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1606 $data['pagetitle'] = t('Search: ');
1607 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1608 $bracketWrap = function ($tag) {
1609 return '['. $tag .']';
1611 $data['pagetitle'] .= ! empty($searchtags)
1612 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1614 $data['pagetitle'] .= '- '. $conf->get('general.title');
1617 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
1619 foreach ($data as $key => $value) {
1620 $PAGE->assign($key, $value);
1627 * Compute the thumbnail for a link.
1629 * With a link to the original URL.
1630 * Understands various services (youtube.com...)
1631 * Input: $url = URL for which the thumbnail must be found.
1632 * $href = if provided, this URL will be followed instead of $url
1633 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1634 * Some of them may be missing.
1635 * Return an empty array if no thumbnail available.
1637 * @param ConfigManager $conf Configuration Manager instance.
1638 * @param string $url
1639 * @param string|bool $href
1643 function computeThumbnail($conf, $url, $href = false)
1645 if (!$conf->get('thumbnail.enable_thumbnails')) return array();
1646 if ($href==false) $href=$url;
1648 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1649 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1650 // ^^^^^^^^^^^ ^^^^^^^^^^^
1651 $domain = parse_url($url,PHP_URL_HOST
);
1652 if ($domain=='youtube.com' || $domain=='www.youtube.com')
1654 parse_str(parse_url($url,PHP_URL_QUERY
), $params); // Extract video ID and get thumbnail
1655 if (!empty($params['v'])) return array('src'=>'https://img.youtube.com/vi/'.$params['v'].'/default.jpg',
1656 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1658 if ($domain=='youtu.be') // Youtube short links
1660 $path = parse_url($url,PHP_URL_PATH
);
1661 return array('src'=>'https://img.youtube.com/vi'.$path.'/default.jpg',
1662 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1664 if ($domain=='pix.toile-libre.org') // pix.toile-libre.org image hosting
1666 parse_str(parse_url($url,PHP_URL_QUERY
), $params); // Extract image filename.
1667 if (!empty($params) && !empty($params['img'])) return array('src'=>'http://pix.toile-libre.org/upload/thumb/'.urlencode($params['img']),
1668 'href'=>$href,'style'=>'max-width:120px; max-height:150px','alt'=>'pix.toile-libre.org thumbnail');
1671 if ($domain=='imgur.com')
1673 $path = parse_url($url,PHP_URL_PATH
);
1674 if (startsWith($path,'/a/')) return array(); // Thumbnails for albums are not available.
1675 if (startsWith($path,'/r/')) return array('src'=>'https://i.imgur.com/'.basename($path).'s.jpg',
1676 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1677 if (startsWith($path,'/gallery/')) return array('src'=>'https://i.imgur.com'.substr($path,8).'s.jpg',
1678 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1680 if (substr_count($path,'/')==1) return array('src'=>'https://i.imgur.com/'.substr($path,1).'s.jpg',
1681 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1683 if ($domain=='i.imgur.com')
1685 $pi = pathinfo(parse_url($url,PHP_URL_PATH
));
1686 if (!empty($pi['filename'])) return array('src'=>'https://i.imgur.com/'.$pi['filename'].'s.jpg',
1687 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1689 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
1691 if (strpos($url,'dailymotion.com/video/')!==false)
1693 $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
1694 return array('src'=>$thumburl,
1695 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'DailyMotion thumbnail');
1698 if (endsWith($domain,'.imageshack.us'))
1700 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION
));
1701 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1703 $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
1704 return array('src'=>$thumburl,
1705 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'imageshack.us thumbnail');
1709 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1710 // So we deport the thumbnail generation in order not to slow down page generation
1711 // (and we also cache the thumbnail)
1713 if (! $conf->get('thumbnail.enable_localcache')) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1715 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
1716 || $domain=='vimeo.com'
1717 || $domain=='ted.com' || endsWith($domain,'.ted.com')
1718 || $domain=='xkcd.com' || endsWith($domain,'.xkcd.com')
1721 if ($domain=='vimeo.com')
1722 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1723 $path = parse_url($url,PHP_URL_PATH
);
1724 if (!preg_match('!/\d+.+?!',$path)) return array(); // This is not a single video URL.
1726 if ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
1727 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1728 $path = parse_url($url,PHP_URL_PATH
);
1729 if (!preg_match('!/\d+.+?!',$path)) return array();
1731 if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
1732 { // Make sure this TED URL points to a video (/talks/...)
1733 $path = parse_url($url,PHP_URL_PATH
);
1734 if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
1736 $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)
1737 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1738 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1741 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1742 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1743 // But using the extension will do.
1744 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION
));
1745 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1747 $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)
1748 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1749 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1751 return array(); // No thumbnail.
1756 // Returns the HTML code to display a thumbnail for a link
1757 // with a link to the original URL.
1758 // Understands various services (youtube.com...)
1759 // Input: $url = URL for which the thumbnail must be found.
1760 // $href = if provided, this URL will be followed instead of $url
1761 // Returns '' if no thumbnail available.
1762 function thumbnail($url,$href=false)
1766 $t = computeThumbnail($conf, $url,$href);
1767 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1769 $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"';
1770 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1771 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1772 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1773 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1778 // Returns the HTML code to display a thumbnail for a link
1779 // for the picture wall (using lazy image loading)
1780 // Understands various services (youtube.com...)
1781 // Input: $url = URL for which the thumbnail must be found.
1782 // $href = if provided, this URL will be followed instead of $url
1783 // Returns '' if no thumbnail available.
1784 function lazyThumbnail($conf, $url,$href=false)
1788 $t = computeThumbnail($conf, $url,$href);
1789 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1791 $html='<a href="'.escape($t['href']).'">';
1794 $html.='<img class="b-lazy" src="#" data-src="'.escape($t['src']).'"';
1796 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1797 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1798 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1799 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1802 // No-JavaScript fallback.
1803 $html.='<noscript><img 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']).'"';
1808 $html.='></noscript></a>';
1816 * This function should NEVER be called if the file data/config.php exists.
1818 * @param ConfigManager $conf Configuration Manager instance.
1819 * @param SessionManager $sessionManager SessionManager instance
1821 function install($conf, $sessionManager) {
1822 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1823 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1826 // This part makes sure sessions works correctly.
1827 // (Because on some hosts, session.save_path may not be set correctly,
1828 // or we may not have write access to it.)
1829 if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working'))
1831 // Step 2: Check if data in session is correct.
1833 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1834 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1835 'and that you have write access to it.<br>'.
1836 'It currently points to %s.<br>'.
1837 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1838 'or any custom hostname without a dot causes cookie storage to fail. '.
1839 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1841 $msg = sprintf($msg, session_save_path());
1843 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1846 if (!isset($_SESSION['session_tested']))
1847 { // Step 1 : Try to store data in session and reload page.
1848 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1849 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1851 if (isset($_GET['test_session']))
1852 { // Step 3: Sessions are OK. Remove test parameter from URL.
1853 header('Location: '.index_url($_SERVER));
1857 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1860 if (!empty($_POST['continent']) && !empty($_POST['city'])
1861 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1863 $tz = $_POST['continent'].'/'.$_POST['city'];
1865 $conf->set('general.timezone', $tz);
1866 $login = $_POST['setlogin'];
1867 $conf->set('credentials.login', $login);
1868 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1869 $conf->set('credentials.salt', $salt);
1870 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
1871 if (!empty($_POST['title'])) {
1872 $conf->set('general.title', escape($_POST['title']));
1874 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
1876 $conf->set('translation.language', escape($_POST['language']));
1877 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1878 $conf->set('api.enabled', !empty($_POST['enableApi']));
1881 generate_api_secret(
1882 $conf->get('credentials.login'),
1883 $conf->get('credentials.salt')
1887 // Everything is ok, let's create config file.
1888 $conf->write($loginManager->isLoggedIn());
1890 catch(Exception
$e) {
1892 'ERROR while writing config file after installation.' . PHP_EOL
.
1896 // TODO: do not handle exceptions/errors in JS.
1897 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1900 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
1904 $PAGE = new PageBuilder($conf, null, $sessionManager->generateToken());
1905 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1906 $PAGE->assign('continents', $continents);
1907 $PAGE->assign('cities', $cities);
1908 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1909 $PAGE->renderPage('install');
1914 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
1915 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1916 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
1917 * This function is called by passing the URL:
1918 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1919 * [URL] is the URL of the link (e.g. a flickr page)
1920 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1921 * The function below will fetch the image from the webservice and store it in the cache.
1923 * @param ConfigManager $conf Configuration Manager instance,
1925 function genThumbnail($conf)
1927 // Make sure the parameters in the URL were generated by us.
1928 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt'));
1929 if ($sign!=$_GET['hmac']) die('Naughty boy!');
1931 $cacheDir = $conf->get('resource.thumbnails_cache', 'cache');
1932 // Let's see if we don't already have the image for this URL in the cache.
1933 $thumbname=hash('sha1',$_GET['url']).'.jpg';
1934 if (is_file($cacheDir .'/'. $thumbname))
1935 { // We have the thumbnail, just serve it:
1936 header('Content-Type: image/jpeg');
1937 echo file_get_contents($cacheDir .'/'. $thumbname);
1940 // We may also serve a blank image (if service did not respond)
1941 $blankname=hash('sha1',$_GET['url']).'.gif';
1942 if (is_file($cacheDir .'/'. $blankname))
1944 header('Content-Type: image/gif');
1945 echo file_get_contents($cacheDir .'/'. $blankname);
1949 // Otherwise, generate the thumbnail.
1950 $url = $_GET['url'];
1951 $domain = parse_url($url,PHP_URL_HOST
);
1953 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
1955 // Crude replacement to handle new flickr domain policy (They prefer www. now)
1956 $url = str_replace('http://flickr.com/','http://www.flickr.com/',$url);
1958 // Is this a link to an image, or to a flickr page ?
1960 if (endsWith(parse_url($url, PHP_URL_PATH
), '.jpg'))
1961 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
1962 preg_match('!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
1963 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
1965 else // This is a flickr page (html)
1967 // Get the flickr html page.
1968 list($headers, $content) = get_http_response($url, 20);
1969 if (strpos($headers[0], '200 OK') !== false)
1971 // flickr now nicely provides the URL of the thumbnail in each flickr page.
1972 preg_match('!<link rel=\"image_src\" href=\"(.+?)\"!', $content, $matches);
1973 if (!empty($matches[1])) $imageurl=$matches[1];
1975 // In albums (and some other pages), the link rel="image_src" is not provided,
1976 // but flickr provides:
1977 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
1980 preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!', $content, $matches);
1981 if (!empty($matches[1])) $imageurl=$matches[1];
1987 { // Let's download the image.
1988 // Image is 240x120, so 10 seconds to download should be enough.
1989 list($headers, $content) = get_http_response($imageurl, 10);
1990 if (strpos($headers[0], '200 OK') !== false) {
1991 // Save image to cache.
1992 file_put_contents($cacheDir .'/'. $thumbname, $content);
1993 header('Content-Type: image/jpeg');
2000 elseif ($domain=='vimeo.com' )
2002 // This is more complex: we have to perform a HTTP request, then parse the result.
2003 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2004 $vid = substr(parse_url($url,PHP_URL_PATH
),1);
2005 list($headers, $content) = get_http_response('https://vimeo.com/api/v2/video/'.escape($vid).'.php', 5);
2006 if (strpos($headers[0], '200 OK') !== false) {
2007 $t = unserialize($content);
2008 $imageurl = $t[0]['thumbnail_medium'];
2009 // Then we download the image and serve it to our client.
2010 list($headers, $content) = get_http_response($imageurl, 10);
2011 if (strpos($headers[0], '200 OK') !== false) {
2012 // Save image to cache.
2013 file_put_contents($cacheDir .'/'. $thumbname, $content);
2014 header('Content-Type: image/jpeg');
2021 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
2023 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2024 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2025 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2026 list($headers, $content) = get_http_response($url, 5);
2027 if (strpos($headers[0], '200 OK') !== false) {
2028 // Extract the link to the thumbnail
2029 preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!', $content, $matches);
2030 if (!empty($matches[1]))
2031 { // Let's download the image.
2032 $imageurl=$matches[1];
2033 // No control on image size, so wait long enough
2034 list($headers, $content) = get_http_response($imageurl, 20);
2035 if (strpos($headers[0], '200 OK') !== false) {
2036 $filepath = $cacheDir .'/'. $thumbname;
2037 file_put_contents($filepath, $content); // Save image to cache.
2038 if (resizeImage($filepath))
2040 header('Content-Type: image/jpeg');
2041 echo file_get_contents($filepath);
2049 elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
2051 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2052 // http://xkcd.com/327/
2053 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2054 list($headers, $content) = get_http_response($url, 5);
2055 if (strpos($headers[0], '200 OK') !== false) {
2056 // Extract the link to the thumbnail
2057 preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!', $content, $matches);
2058 if (!empty($matches[1]))
2059 { // Let's download the image.
2060 $imageurl=$matches[1];
2061 // No control on image size, so wait long enough
2062 list($headers, $content) = get_http_response($imageurl, 20);
2063 if (strpos($headers[0], '200 OK') !== false) {
2064 $filepath = $cacheDir.'/'.$thumbname;
2065 // Save image to cache.
2066 file_put_contents($filepath, $content);
2067 if (resizeImage($filepath))
2069 header('Content-Type: image/jpeg');
2070 echo file_get_contents($filepath);
2080 // For all other domains, we try to download the image and make a thumbnail.
2081 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2082 list($headers, $content) = get_http_response($url, 30);
2083 if (strpos($headers[0], '200 OK') !== false) {
2084 $filepath = $cacheDir .'/'.$thumbname;
2085 // Save image to cache.
2086 file_put_contents($filepath, $content);
2087 if (resizeImage($filepath))
2089 header('Content-Type: image/jpeg');
2090 echo file_get_contents($filepath);
2097 // Otherwise, return an empty image (8x8 transparent gif)
2098 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
2099 // Also put something in cache so that this URL is not requested twice.
2100 file_put_contents($cacheDir .'/'. $blankname, $blankgif);
2101 header('Content-Type: image/gif');
2105 // Make a thumbnail of the image (to width: 120 pixels)
2106 // Returns true if success, false otherwise.
2107 function resizeImage($filepath)
2109 if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
2111 // Trick: some stupid people rename GIF as JPEG... or else.
2112 // So we really try to open each image type whatever the extension is.
2113 $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
2115 $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
2116 $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
2117 $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
2118 if (!$im) return false; // Unable to open image (corrupted or not an image)
2121 $ystart = 0; $yheight=$h;
2122 if ($h>$w) { $ystart
= ($h
/2)-($w
/2); $yheight
=$w
/2; }
2123 $nw = 120; // Desired width
2124 $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
2126 $im2 = imagecreatetruecolor($nw,$nh);
2127 imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
2128 imageinterlace($im2,true); // For progressive JPEG.
2129 $tempname=$filepath.'_TEMP.jpg';
2130 imagejpeg($im2, $tempname, 90);
2134 rename($tempname,$filepath); // Overwrite original picture with thumbnail.
2138 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf
); exit; } // Thumbnail generation/cache does not need the link database.
2139 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf
); exit; }
2140 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
2141 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
2145 $history = new History($conf->get('resource.history'));
2146 } catch(Exception
$e) {
2147 die($e->getMessage());
2150 $linkDb = new LinkDB(
2151 $conf->get('resource.datastore'),
2152 $loginManager->isLoggedIn(),
2153 $conf->get('privacy.hide_public_links'),
2154 $conf->get('redirector.url'),
2155 $conf->get('redirector.encode_url')
2158 $container = new \Slim\
Container();
2159 $container['conf'] = $conf;
2160 $container['plugins'] = $pluginManager;
2161 $container['history'] = $history;
2162 $app = new \Slim\
App($container);
2165 $app->group('/api/v1', function() {
2166 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
2167 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
2168 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
2169 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
2170 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
2171 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
2172 $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
2173 })->add('\Shaarli\Api\ApiMiddleware');
2175 $response = $app->run(true);
2176 // Hack to make Slim and Shaarli router work together:
2177 // If a Slim route isn't found and NOT API call, we call renderPage().
2178 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
2179 // We use UTF-8 for proper international characters handling.
2180 header('Content-Type: text/html; charset=utf-8');
2181 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
2183 $app->respond($response);