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 // If the user does not access any page within this time, his/her session is considered expired.
105 define('INACTIVITY_TIMEOUT', 3600); // in seconds.
106 // Use cookies to store session.
107 ini_set('session.use_cookies', 1);
108 // Force cookies for session (phpsessionID forbidden in URL).
109 ini_set('session.use_only_cookies', 1);
110 // Prevent PHP form using sessionID in URL if cookies are disabled.
111 ini_set('session.use_trans_sid', false);
113 session_name('shaarli');
114 // Start session if needed (Some server auto-start sessions).
115 if (session_id() == '') {
119 // Regenerate session ID if invalid or not defined in cookie.
120 if (isset($_COOKIE['shaarli']) && !SessionManager
::checkId($_COOKIE['shaarli'])) {
121 session_regenerate_id(true);
122 $_COOKIE['shaarli'] = session_id();
125 $conf = new ConfigManager();
126 $loginManager = new LoginManager($GLOBALS, $conf);
127 $sessionManager = new SessionManager($_SESSION, $conf);
129 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
130 if (! defined('LC_MESSAGES')) {
131 define('LC_MESSAGES', LC_COLLATE
);
134 // Sniff browser language and set date format accordingly.
135 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
136 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
139 new Languages(setlocale(LC_MESSAGES
, 0), $conf);
141 $conf->setEmpty('general.timezone', date_default_timezone_get());
142 $conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
143 RainTPL
::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
144 RainTPL
::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
146 $pluginManager = new PluginManager($conf);
147 $pluginManager->load($conf->get('general.enabled_plugins'));
149 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
151 ob_start(); // Output buffering for the page cache.
153 // Prevent caching on client side or proxy: (yes, it's ugly)
154 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
155 header("Cache-Control: no-store, no-cache, must-revalidate");
156 header("Cache-Control: post-check=0, pre-check=0", false);
157 header("Pragma: no-cache");
159 if (! is_file($conf->getConfigFileExt())) {
160 // Ensure Shaarli has proper access to its resources
161 $errors = ApplicationUtils
::checkResourcePermissions($conf);
163 if ($errors != array()) {
164 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
166 foreach ($errors as $error) {
167 $message .= '<li>'.$error.'</li>';
171 header('Content-Type: text/html; charset=utf-8');
176 // Display the installation form if no existing config is found
177 install($conf, $sessionManager);
180 // a token depending of deployment salt, user password, and the current ip
181 define('STAY_SIGNED_IN_TOKEN', sha1($conf->get('credentials.hash') . $_SERVER['REMOTE_ADDR'] . $conf->get('credentials.salt')));
184 * Checking session state (i.e. is the user still logged in)
186 * @param ConfigManager $conf The configuration manager.
188 * @return bool: true if the user is logged in, false otherwise.
190 function setup_login_state($conf)
192 if ($conf->get('security.open_shaarli')) {
195 $userIsLoggedIn = false; // By default, we do not consider the user as logged in;
196 $loginFailure = false; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
197 if (! $conf->exists('credentials.login')) {
198 $userIsLoggedIn = false; // Shaarli is not configured yet.
199 $loginFailure = true;
201 if (isset($_COOKIE['shaarli_staySignedIn']) &&
202 $_COOKIE['shaarli_staySignedIn']===STAY_SIGNED_IN_TOKEN
&&
205 fillSessionInfo($conf);
206 $userIsLoggedIn = true;
208 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
209 if (empty($_SESSION['uid'])
210 || ($conf->get('security.session_protection_disabled') === false && $_SESSION['ip'] != client_ip_id($_SERVER))
211 || time() >= $_SESSION['expires_on'])
214 $userIsLoggedIn = false;
215 $loginFailure = true;
217 if (!empty($_SESSION['longlastingsession'])) {
218 $_SESSION['expires_on']=time()+
$_SESSION['longlastingsession']; // In case of "Stay signed in" checked.
221 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT
; // Standard session expiration date.
223 if (!$loginFailure) {
224 $userIsLoggedIn = true;
227 return $userIsLoggedIn;
229 $userIsLoggedIn = setup_login_state($conf);
231 // ------------------------------------------------------------------------------------------
232 // Session management
237 * @param ConfigManager $conf Configuration Manager instance.
239 function fillSessionInfo($conf)
241 $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid)
242 $_SESSION['ip'] = client_ip_id($_SERVER);
243 $_SESSION['username']= $conf->get('credentials.login');
244 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT
; // Set session expiration.
248 * Check that user/password is correct.
250 * @param string $login Username
251 * @param string $password User password
252 * @param ConfigManager $conf Configuration Manager instance.
254 * @return bool: authentication successful or not.
256 function check_auth($login, $password, $conf)
258 $hash = sha1($password . $login . $conf->get('credentials.salt'));
259 if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash'))
260 { // Login/password is correct.
261 fillSessionInfo($conf);
262 logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login successful');
265 logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login);
269 // Returns true if the user is logged in.
270 function isLoggedIn()
272 global $userIsLoggedIn;
273 return $userIsLoggedIn;
278 if (isset($_SESSION)) {
279 unset($_SESSION['uid']);
280 unset($_SESSION['ip']);
281 unset($_SESSION['username']);
282 unset($_SESSION['visibility']);
283 unset($_SESSION['untaggedonly']);
285 setcookie('shaarli_staySignedIn', FALSE, 0, WEB_PATH
);
288 // ------------------------------------------------------------------------------------------
289 // Process login form: Check if login/password is correct.
290 if (isset($_POST['login']))
292 if (! $loginManager->canLogin($_SERVER)) {
293 die(t('I said: NO. You are banned for the moment. Go away.'));
295 if (isset($_POST['password'])
296 && $sessionManager->checkToken($_POST['token'])
297 && (check_auth($_POST['login'], $_POST['password'], $conf))
299 // Login/password is OK.
300 $loginManager->handleSuccessfulLogin($_SERVER);
302 // If user wants to keep the session cookie even after the browser closes:
303 if (!empty($_POST['longlastingsession'])) {
304 $_SESSION['longlastingsession'] = 31536000; // (31536000 seconds = 1 year)
305 $expiration = time() +
$_SESSION['longlastingsession']; // calculate relative cookie expiration (1 year from now)
306 setcookie('shaarli_staySignedIn', STAY_SIGNED_IN_TOKEN
, $expiration, WEB_PATH
);
307 $_SESSION['expires_on'] = $expiration; // Set session expiration on server-side.
309 $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
310 session_set_cookie_params($_SESSION['longlastingsession'],$cookiedir,$_SERVER['SERVER_NAME']); // Set session cookie expiration on client side
311 // Note: Never forget the trailing slash on the cookie path!
312 session_regenerate_id(true); // Send cookie with new expiration date to browser.
314 else // Standard session expiration (=when browser closes)
316 $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
317 session_set_cookie_params(0,$cookiedir,$_SERVER['SERVER_NAME']); // 0 means "When browser closes"
318 session_regenerate_id(true);
321 // Optional redirect after login:
322 if (isset($_GET['post'])) {
323 $uri = '?post='. urlencode($_GET['post']);
324 foreach (array('description', 'source', 'title', 'tags') as $param) {
325 if (!empty($_GET[$param])) {
326 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
329 header('Location: '. $uri);
333 if (isset($_GET['edit_link'])) {
334 header('Location: ?edit_link='. escape($_GET['edit_link']));
338 if (isset($_POST['returnurl'])) {
339 // Prevent loops over login screen.
340 if (strpos($_POST['returnurl'], 'do=login') === false) {
341 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
345 header('Location: ?'); exit;
347 $loginManager->handleFailedLogin($_SERVER);
348 $redir = '&username='. urlencode($_POST['login']);
349 if (isset($_GET['post'])) {
350 $redir .= '&post=' . urlencode($_GET['post']);
351 foreach (array('description', 'source', 'title', 'tags') as $param) {
352 if (!empty($_GET[$param])) {
353 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
357 // Redirect to login screen.
358 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
363 // ------------------------------------------------------------------------------------------
364 // Token management for XSRF protection
365 // Token should be used in any form which acts on data (create,update,delete,import...).
366 if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
369 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
370 * Gives the last 7 days (which have links).
371 * This RSS feed cannot be filtered.
373 * @param ConfigManager $conf Configuration Manager instance.
375 function showDailyRSS($conf) {
377 $query = $_SERVER['QUERY_STRING'];
378 $cache = new CachedPage(
379 $conf->get('config.PAGE_CACHE'),
381 startsWith($query,'do=dailyrss') && !isLoggedIn()
383 $cached = $cache->cachedVersion();
384 if (!empty($cached)) {
389 // If cached was not found (or not usable), then read the database and build the response:
390 // Read links from database (and filter private links if used it not logged in).
391 $LINKSDB = new LinkDB(
392 $conf->get('resource.datastore'),
394 $conf->get('privacy.hide_public_links'),
395 $conf->get('redirector.url'),
396 $conf->get('redirector.encode_url')
399 /* Some Shaarlies may have very few links, so we need to look
400 back in time until we have enough days ($nb_of_days).
402 $nb_of_days = 7; // We take 7 days.
403 $today = date('Ymd');
406 foreach ($LINKSDB as $link) {
407 $day = $link['created']->format('Ymd'); // Extract day (without time)
408 if (strcmp($day, $today) < 0) {
409 if (empty($days[$day])) {
410 $days[$day] = array();
412 $days[$day][] = $link;
415 if (count($days) > $nb_of_days) {
416 break; // Have we collected enough days?
420 // Build the RSS feed.
421 header('Content-Type: application/rss+xml; charset=utf-8');
422 $pageaddr = escape(index_url($_SERVER));
423 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
425 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
426 echo '<link>'. $pageaddr .'</link>';
427 echo '<description>Daily shared links</description>';
428 echo '<language>en-en</language>';
429 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL
;
432 foreach ($days as $day => $links) {
433 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
434 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
436 // We pre-format some fields for proper output.
437 foreach ($links as &$link) {
438 $link['formatedDescription'] = format_description(
439 $link['description'],
440 $conf->get('redirector.url'),
441 $conf->get('redirector.encode_url')
443 $link['thumbnail'] = thumbnail($conf, $link['url']);
444 $link['timestamp'] = $link['created']->getTimestamp();
445 if (startsWith($link['url'], '?')) {
446 $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
450 // Then build the HTML for this day:
452 $tpl->assign('title', $conf->get('general.title'));
453 $tpl->assign('daydate', $dayDate->getTimestamp());
454 $tpl->assign('absurl', $absurl);
455 $tpl->assign('links', $links);
456 $tpl->assign('rssdate', escape($dayDate->format(DateTime
::RSS
)));
457 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
458 $html = $tpl->draw('dailyrss', true);
460 echo $html . PHP_EOL
;
462 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
464 $cache->cache(ob_get_contents());
470 * Show the 'Daily' page.
472 * @param PageBuilder $pageBuilder Template engine wrapper.
473 * @param LinkDB $LINKSDB LinkDB instance.
474 * @param ConfigManager $conf Configuration Manager instance.
475 * @param PluginManager $pluginManager Plugin Manager instane.
477 function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager)
479 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
480 if (isset($_GET['day'])) {
484 $days = $LINKSDB->days();
485 $i = array_search($day, $days);
486 if ($i === false && count($days)) {
487 // no links for day, but at least one day with links
488 $i = count($days) - 1;
496 $previousday=$days[$i - 1];
498 if ($i < count($days) - 1) {
499 $nextday = $days[$i +
1];
503 $linksToDisplay = $LINKSDB->filterDay($day);
504 } catch (Exception
$exc) {
506 $linksToDisplay = array();
509 // We pre-format some fields for proper output.
510 foreach($linksToDisplay as $key => $link) {
511 $taglist = explode(' ',$link['tags']);
512 uasort($taglist, 'strcasecmp');
513 $linksToDisplay[$key]['taglist']=$taglist;
514 $linksToDisplay[$key]['formatedDescription'] = format_description(
515 $link['description'],
516 $conf->get('redirector.url'),
517 $conf->get('redirector.encode_url')
519 $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
520 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
523 $dayDate = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $day.'_000000');
525 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
526 'linksToDisplay' => $linksToDisplay,
527 'day' => $dayDate->getTimestamp(),
528 'dayDate' => $dayDate,
529 'previousday' => $previousday,
530 'nextday' => $nextday,
533 /* Hook is called before column construction so that plugins don't have
534 to deal with columns. */
535 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => isLoggedIn()));
537 /* We need to spread the articles on 3 columns.
538 I did not want to use a JavaScript lib like http://masonry.desandro.com/
539 so I manually spread entries with a simple method: I roughly evaluate the
540 height of a div according to title and description length.
542 $columns = array(array(), array(), array()); // Entries to display, for each column.
543 $fill = array(0, 0, 0); // Rough estimate of columns fill.
544 foreach($data['linksToDisplay'] as $key => $link) {
545 // Roughly estimate length of entry (by counting characters)
546 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
547 // Description: 836 characters gives roughly 342 pixel height.
548 // This is not perfect, but it's usually OK.
549 $length = strlen($link['title']) +
(342 * strlen($link['description'])) / 836;
550 if ($link['thumbnail']) {
551 $length +
= 100; // 1 thumbnails roughly takes 100 pixels height.
553 // Then put in column which is the less filled:
554 $smallest = min($fill); // find smallest value in array.
555 $index = array_search($smallest, $fill); // find index of this smallest value.
556 array_push($columns[$index], $link); // Put entry in this column.
557 $fill[$index] +
= $length;
560 $data['cols'] = $columns;
562 foreach ($data as $key => $value) {
563 $pageBuilder->assign($key, $value);
566 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
567 $pageBuilder->renderPage('daily');
572 * Renders the linklist
574 * @param pageBuilder $PAGE pageBuilder instance.
575 * @param LinkDB $LINKSDB LinkDB instance.
576 * @param ConfigManager $conf Configuration Manager instance.
577 * @param PluginManager $pluginManager Plugin Manager instance.
579 function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager) {
580 buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager); // Compute list of links to display
581 $PAGE->renderPage('linklist');
585 * Render HTML page (according to URL parameters and user rights)
587 * @param ConfigManager $conf Configuration Manager instance.
588 * @param PluginManager $pluginManager Plugin Manager instance,
589 * @param LinkDB $LINKSDB
590 * @param History $history instance
591 * @param SessionManager $sessionManager SessionManager instance
592 * @param LoginManager $loginManager LoginManager instance
594 function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
596 $updater = new Updater(
597 read_updates_file($conf->get('resource.updates')),
603 $newUpdates = $updater->update();
604 if (! empty($newUpdates)) {
606 $conf->get('resource.updates'),
607 $updater->getDoneUpdates()
611 catch(Exception
$e) {
612 die($e->getMessage());
615 $PAGE = new PageBuilder($conf, $LINKSDB, $sessionManager->generateToken());
616 $PAGE->assign('linkcount', count($LINKSDB));
617 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
618 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
620 // Determine which page will be rendered.
621 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
622 $targetPage = Router
::findPage($query, $_GET, isLoggedIn());
625 // if the user isn't logged in
627 // and Shaarli doesn't have public content...
628 $conf->get('privacy.hide_public_links') &&
629 // and is configured to enforce the login
630 $conf->get('privacy.force_login') &&
631 // and the current page isn't already the login page
632 $targetPage !== Router
::$PAGE_LOGIN &&
633 // and the user is not requesting a feed (which would lead to a different content-type as expected)
634 $targetPage !== Router
::$PAGE_FEED_ATOM &&
635 $targetPage !== Router
::$PAGE_FEED_RSS
637 // force current page to be the login page
638 $targetPage = Router
::$PAGE_LOGIN;
641 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
642 // Then assign generated data to RainTPL.
643 $common_hooks = array(
649 foreach($common_hooks as $name) {
650 $plugin_data = array();
651 $pluginManager->executeHooks('render_' . $name, $plugin_data,
653 'target' => $targetPage,
654 'loggedin' => isLoggedIn()
657 $PAGE->assign('plugins_' . $name, $plugin_data);
660 // -------- Display login form.
661 if ($targetPage == Router
::$PAGE_LOGIN)
663 if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
664 if (isset($_GET['username'])) {
665 $PAGE->assign('username', escape($_GET['username']));
667 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
668 // add default state of the 'remember me' checkbox
669 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
670 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
671 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
672 $PAGE->renderPage('loginform');
675 // -------- User wants to logout.
676 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
678 invalidateCaches($conf->get('resource.page_cache'));
680 header('Location: ?');
684 // -------- Picture wall
685 if ($targetPage == Router
::$PAGE_PICWALL)
687 // Optionally filter the results:
688 $links = $LINKSDB->filterSearch($_GET);
689 $linksToDisplay = array();
691 // Get only links which have a thumbnail.
692 foreach($links as $link)
694 $permalink='?'.$link['shorturl'];
695 $thumb=lazyThumbnail($conf, $link['url'],$permalink);
696 if ($thumb!='') // Only output links which have a thumbnail.
698 $link['thumbnail']=$thumb; // Thumbnail HTML code.
699 $linksToDisplay[]=$link; // Add to array.
704 'linksToDisplay' => $linksToDisplay,
706 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => isLoggedIn()));
708 foreach ($data as $key => $value) {
709 $PAGE->assign($key, $value);
712 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
713 $PAGE->renderPage('picwall');
717 // -------- Tag cloud
718 if ($targetPage == Router
::$PAGE_TAGCLOUD)
720 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
721 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
722 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
724 // We sort tags alphabetically, then choose a font size according to count.
725 // First, find max value.
727 foreach ($tags as $value) {
728 $maxcount = max($maxcount, $value);
731 alphabetical_sort($tags, false, true);
734 foreach($tags as $key => $value) {
735 if (in_array($key, $filteringTags)) {
738 // Tag font size scaling:
739 // default 15 and 30 logarithm bases affect scaling,
740 // 22 and 6 are arbitrary font sizes for max and min sizes.
741 $size = log($value, 15) / log($maxcount, 30) * 2.2 +
0.8;
742 $tagList[$key] = array(
744 'size' => number_format($size, 2, '.', ''),
748 $searchTags = implode(' ', escape($filteringTags));
750 'search_tags' => $searchTags,
753 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => isLoggedIn()));
755 foreach ($data as $key => $value) {
756 $PAGE->assign($key, $value);
759 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
760 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
761 $PAGE->renderPage('tag.cloud');
766 if ($targetPage == Router
::$PAGE_TAGLIST)
768 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
769 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
770 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
771 foreach ($filteringTags as $tag) {
772 if (array_key_exists($tag, $tags)) {
777 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
778 alphabetical_sort($tags, false, true);
781 $searchTags = implode(' ', escape($filteringTags));
783 'search_tags' => $searchTags,
786 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => isLoggedIn()]);
788 foreach ($data as $key => $value) {
789 $PAGE->assign($key, $value);
792 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
793 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
794 $PAGE->renderPage('tag.list');
799 if ($targetPage == Router
::$PAGE_DAILY) {
800 showDaily($PAGE, $LINKSDB, $conf, $pluginManager);
803 // ATOM and RSS feed.
804 if ($targetPage == Router
::$PAGE_FEED_ATOM || $targetPage == Router
::$PAGE_FEED_RSS) {
805 $feedType = $targetPage == Router
::$PAGE_FEED_RSS ? FeedBuilder
::$FEED_RSS : FeedBuilder
::$FEED_ATOM;
806 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
809 $query = $_SERVER['QUERY_STRING'];
810 $cache = new CachedPage(
811 $conf->get('resource.page_cache'),
813 startsWith($query,'do='. $targetPage) && !isLoggedIn()
815 $cached = $cache->cachedVersion();
816 if (!empty($cached)) {
822 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, isLoggedIn());
823 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE
, 0)));
824 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !isLoggedIn());
825 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
826 $data = $feedGenerator->buildData();
828 // Process plugin hook.
829 $pluginManager->executeHooks('render_feed', $data, array(
830 'loggedin' => isLoggedIn(),
831 'target' => $targetPage,
834 // Render the template.
835 $PAGE->assignAll($data);
836 $PAGE->renderPage('feed.'. $feedType);
837 $cache->cache(ob_get_contents());
842 // Display opensearch plugin (XML)
843 if ($targetPage == Router
::$PAGE_OPENSEARCH) {
844 header('Content-Type: application/xml; charset=utf-8');
845 $PAGE->assign('serverurl', index_url($_SERVER));
846 $PAGE->renderPage('opensearch');
850 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
851 if (isset($_GET['addtag']))
853 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
854 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET
['addtag'])); exit; } // In case browser does not send HTTP_REFERER
855 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY
), $params);
857 // Prevent redirection loop
858 if (isset($params['addtag'])) {
859 unset($params['addtag']);
862 // Check if this tag is already in the search query and ignore it if it is.
863 // Each tag is always separated by a space
864 if (isset($params['searchtags'])) {
865 $current_tags = explode(' ', $params['searchtags']);
867 $current_tags = array();
870 foreach ($current_tags as $value) {
871 if ($value === $_GET['addtag']) {
876 // Append the tag if necessary
877 if (empty($params['searchtags'])) {
878 $params['searchtags'] = trim($_GET['addtag']);
881 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
884 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
885 header('Location: ?'.http_build_query($params));
889 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
890 if (isset($_GET['removetag'])) {
891 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
892 if (empty($_SERVER['HTTP_REFERER'])) {
893 header('Location: ?');
897 // In case browser does not send HTTP_REFERER
898 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY
), $params);
900 // Prevent redirection loop
901 if (isset($params['removetag'])) {
902 unset($params['removetag']);
905 if (isset($params['searchtags'])) {
906 $tags = explode(' ', $params['searchtags']);
907 // Remove value from array $tags.
908 $tags = array_diff($tags, array($_GET['removetag']));
909 $params['searchtags'] = implode(' ',$tags);
911 if (empty($params['searchtags'])) {
912 unset($params['searchtags']);
915 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
917 header('Location: ?'.http_build_query($params));
921 // -------- User wants to change the number of links per page (linksperpage=...)
922 if (isset($_GET['linksperpage'])) {
923 if (is_numeric($_GET['linksperpage'])) {
924 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
927 if (! empty($_SERVER['HTTP_REFERER'])) {
928 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
932 header('Location: '. $location);
936 // -------- User wants to see only private links (toggle)
937 if (isset($_GET['visibility'])) {
938 if ($_GET['visibility'] === 'private') {
939 // Visibility not set or not already private, set private, otherwise reset it
940 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
941 // See only private links
942 $_SESSION['visibility'] = 'private';
944 unset($_SESSION['visibility']);
946 } elseif ($_GET['visibility'] === 'public') {
947 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
948 // See only public links
949 $_SESSION['visibility'] = 'public';
951 unset($_SESSION['visibility']);
955 if (! empty($_SERVER['HTTP_REFERER'])) {
956 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
960 header('Location: '. $location);
964 // -------- User wants to see only untagged links (toggle)
965 if (isset($_GET['untaggedonly'])) {
966 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
968 if (! empty($_SERVER['HTTP_REFERER'])) {
969 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
973 header('Location: '. $location);
977 // -------- Handle other actions allowed for non-logged in users:
980 // User tries to post new link but is not logged in:
981 // Show login screen, then redirect to ?post=...
982 if (isset($_GET['post']))
984 header( // Redirect to login page, then back to post link.
985 'Location: ?do=login&post='.urlencode($_GET['post']).
986 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
987 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
988 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
989 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
994 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
995 if (isset($_GET['edit_link'])) {
996 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
1000 exit; // Never remove this one! All operations below are reserved for logged in user.
1003 // -------- All other functions are reserved for the registered user:
1005 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1006 if ($targetPage == Router
::$PAGE_TOOLS)
1009 'pageabsaddr' => index_url($_SERVER),
1010 'sslenabled' => is_https($_SERVER),
1012 $pluginManager->executeHooks('render_tools', $data);
1014 foreach ($data as $key => $value) {
1015 $PAGE->assign($key, $value);
1018 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
1019 $PAGE->renderPage('tools');
1023 // -------- User wants to change his/her password.
1024 if ($targetPage == Router
::$PAGE_CHANGEPASSWORD)
1026 if ($conf->get('security.open_shaarli')) {
1027 die(t('You are not supposed to change a password on an Open Shaarli.'));
1030 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
1032 if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away!
1034 // Make sure old password is correct.
1035 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
1036 if ($oldhash!= $conf->get('credentials.hash')) {
1037 echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>';
1040 // Save new password
1041 // Salt renders rainbow-tables attacks useless.
1042 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
1043 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt')));
1045 $conf->write(isLoggedIn());
1047 catch(Exception
$e) {
1049 'ERROR while writing config file after changing password.' . PHP_EOL
.
1053 // TODO: do not handle exceptions/errors in JS.
1054 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
1057 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
1060 else // show the change password form.
1062 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
1063 $PAGE->renderPage('changepassword');
1068 // -------- User wants to change configuration
1069 if ($targetPage == Router
::$PAGE_CONFIGURE)
1071 if (!empty($_POST['title']) )
1073 if (!$sessionManager->checkToken($_POST['token'])) {
1074 die(t('Wrong token.')); // Go away!
1077 if (!empty($_POST['continent']) && !empty($_POST['city'])
1078 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1080 $tz = $_POST['continent'] . '/' . $_POST['city'];
1082 $conf->set('general.timezone', $tz);
1083 $conf->set('general.title', escape($_POST['title']));
1084 $conf->set('general.header_link', escape($_POST['titleLink']));
1085 $conf->set('resource.theme', escape($_POST['theme']));
1086 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
1087 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
1088 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1089 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1090 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
1091 $conf->set('api.enabled', !empty($_POST['enableApi']));
1092 $conf->set('api.secret', escape($_POST['apiSecret']));
1093 $conf->set('translation.language', escape($_POST['language']));
1096 $conf->write(isLoggedIn());
1097 $history->updateSettings();
1098 invalidateCaches($conf->get('resource.page_cache'));
1100 catch(Exception
$e) {
1102 'ERROR while writing config file after configuration update.' . PHP_EOL
.
1106 // TODO: do not handle exceptions/errors in JS.
1107 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1110 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1113 else // Show the configuration form.
1115 $PAGE->assign('title', $conf->get('general.title'));
1116 $PAGE->assign('theme', $conf->get('resource.theme'));
1117 $PAGE->assign('theme_available', ThemeUtils
::getThemes($conf->get('resource.raintpl_tpl')));
1118 list($continents, $cities) = generateTimeZoneData(
1119 timezone_identifiers_list(),
1120 $conf->get('general.timezone')
1122 $PAGE->assign('continents', $continents);
1123 $PAGE->assign('cities', $cities);
1124 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
1125 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1126 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1127 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1128 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1129 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1130 $PAGE->assign('api_secret', $conf->get('api.secret'));
1131 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1132 $PAGE->assign('language', $conf->get('translation.language'));
1133 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
1134 $PAGE->renderPage('configure');
1139 // -------- User wants to rename a tag or delete it
1140 if ($targetPage == Router
::$PAGE_CHANGETAG)
1142 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1143 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1144 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
1145 $PAGE->renderPage('changetag');
1149 if (!$sessionManager->checkToken($_POST['token'])) {
1150 die(t('Wrong token.'));
1153 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), escape($_POST['totag']));
1154 $LINKSDB->save($conf->get('resource.page_cache'));
1155 foreach ($alteredLinks as $link) {
1156 $history->updateLink($link);
1158 $delete = empty($_POST['totag']);
1159 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1160 $count = count($alteredLinks);
1162 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d links.', $count), $count)
1163 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d links.', $count), $count);
1164 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1168 // -------- User wants to add a link without using the bookmarklet: Show form.
1169 if ($targetPage == Router
::$PAGE_ADDLINK)
1171 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1172 $PAGE->renderPage('addlink');
1176 // -------- User clicked the "Save" button when editing a link: Save link to database.
1177 if (isset($_POST['save_edit']))
1180 if (! $sessionManager->checkToken($_POST['token'])) {
1181 die(t('Wrong token.'));
1184 // lf_id should only be present if the link exists.
1185 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
1186 // Linkdate is kept here to:
1187 // - use the same permalink for notes as they're displayed when creating them
1188 // - let users hack creation date of their posts
1189 // See: https://shaarli.readthedocs.io/en/master/Various-hacks/#changing-the-timestamp-for-a-shaare
1190 $linkdate = escape($_POST['lf_linkdate']);
1191 if (isset($LINKSDB[$id])) {
1193 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1194 $updated = new DateTime();
1195 $shortUrl = $LINKSDB[$id]['shorturl'];
1199 $created = DateTime
::createFromFormat(LinkDB
::LINK_DATE_FORMAT
, $linkdate);
1201 $shortUrl = link_small_hash($created, $id);
1205 // Remove multiple spaces.
1206 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
1207 // Remove first '-' char in tags.
1208 $tags = preg_replace('/(^| )\-/', '$1', $tags);
1209 // Remove duplicates.
1210 $tags = implode(' ', array_unique(explode(' ', $tags)));
1212 if (empty(trim($_POST['lf_url
']))) {
1213 $_POST['lf_url
'] = '?' . smallHash($linkdate . $id);
1215 $url = whitelist_protocols(trim($_POST['lf_url
']), $conf->get('security
.allowed_protocols
'));
1219 'title
' => trim($_POST['lf_title
']),
1221 'description
' => $_POST['lf_description
'],
1222 'private' => (isset($_POST['lf_private
']) ? 1 : 0),
1223 'created
' => $created,
1224 'updated
' => $updated,
1225 'tags
' => str_replace(',', ' ', $tags),
1226 'shorturl
' => $shortUrl,
1229 // If title is empty, use the URL as title.
1230 if ($link['title
'] == '') {
1231 $link['title
'] = $link['url
'];
1234 $pluginManager->executeHooks('save_link
', $link);
1236 $LINKSDB[$id] = $link;
1237 $LINKSDB->save($conf->get('resource.page_cache
'));
1239 $history->addLink($link);
1241 $history->updateLink($link);
1244 // If we are called from the bookmarklet, we must close the popup:
1245 if (isset($_GET['source
']) && ($_GET['source
']=='bookmarklet
' || $_GET['source
']=='firefoxsocialapi
')) {
1246 echo '<script
>self
.close();</script
>';
1250 $returnurl = !empty($_POST['returnurl
']) ? $_POST['returnurl
'] : '?';
1251 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST
'], array('addlink
', 'post
', 'edit_link
'));
1252 // Scroll to the link which has been edited.
1253 $location .= '#' . $link['shorturl'];
1254 // After saving the link, redirect to the page the user was on.
1255 header('Location: '. $location);
1259 // -------- User clicked the "Cancel" button when editing a link.
1260 if (isset($_POST['cancel_edit']))
1262 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1263 if (! isset($LINKSDB[$id])) {
1264 header('Location: ?');
1266 // If we are called from the bookmarklet, we must close the popup:
1267 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1268 $link = $LINKSDB[$id];
1269 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1270 // Scroll to the link which has been edited.
1271 $returnurl .= '#'. $link['shorturl'];
1272 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1273 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1277 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1278 if ($targetPage == Router
::$PAGE_DELETELINK)
1280 if (! $sessionManager->checkToken($_GET['token'])) {
1281 die(t('Wrong token.'));
1284 $ids = trim($_GET['lf_linkdate']);
1285 if (strpos($ids, ' ') !== false) {
1286 // multiple, space-separated ids provided
1287 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1289 // only a single id provided
1292 // assert at least one id is given
1294 die('no id provided');
1296 foreach ($ids as $id) {
1297 $id = (int) escape($id);
1298 $link = $LINKSDB[$id];
1299 $pluginManager->executeHooks('delete_link', $link);
1300 unset($LINKSDB[$id]);
1302 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1303 $history->deleteLink($link);
1305 // If we are called from the bookmarklet, we must close the popup:
1306 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1309 if (isset($_SERVER['HTTP_REFERER'])) {
1310 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1311 $location = generateLocation(
1312 $_SERVER['HTTP_REFERER'],
1313 $_SERVER['HTTP_HOST'],
1314 ['delete_link', 'edit_link', $link['shorturl']]
1318 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1322 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1323 if (isset($_GET['edit_link']))
1325 $id = (int) escape($_GET['edit_link']);
1326 $link = $LINKSDB[$id]; // Read database
1327 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
1328 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1331 'link_is_new' => false,
1332 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1333 'tags' => $LINKSDB->linksCountPerTag(),
1335 $pluginManager->executeHooks('render_editlink', $data);
1337 foreach ($data as $key => $value) {
1338 $PAGE->assign($key, $value);
1341 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1342 $PAGE->renderPage('editlink');
1346 // -------- User want to post a new link: Display link edit form.
1347 if (isset($_GET['post'])) {
1348 $url = cleanup_url($_GET['post']);
1350 $link_is_new = false;
1351 // Check if URL is not already in database (in this case, we will edit the existing link)
1352 $link = $LINKSDB->getLinkFromUrl($url);
1355 $link_is_new = true;
1356 $linkdate = strval(date(LinkDB
::LINK_DATE_FORMAT
));
1357 // Get title if it was provided in URL (by the bookmarklet).
1358 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1359 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1360 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1361 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1362 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1363 // 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.)
1364 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1365 // Short timeout to keep the application responsive
1366 // The callback will fill $charset and $title with data from the downloaded page.
1369 $conf->get('general.download_timeout', 30),
1370 $conf->get('general.download_max_size', 4194304),
1371 get_curl_download_callback($charset, $title)
1373 if (! empty($title) && strtolower($charset) != 'utf-8') {
1374 $title = mb_convert_encoding($title, 'utf-8', $charset);
1379 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1380 $title = $conf->get('general.default_note_title', t('Note: '));
1382 $url = escape($url);
1383 $title = escape($title);
1386 'linkdate' => $linkdate,
1389 'description' => $description,
1391 'private' => $private,
1394 $link['linkdate'] = $link['created']->format(LinkDB
::LINK_DATE_FORMAT
);
1399 'link_is_new' => $link_is_new,
1400 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1401 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1402 'tags' => $LINKSDB->linksCountPerTag(),
1403 'default_private_links' => $conf->get('privacy.default_private_links', false),
1405 $pluginManager->executeHooks('render_editlink', $data);
1407 foreach ($data as $key => $value) {
1408 $PAGE->assign($key, $value);
1411 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1412 $PAGE->renderPage('editlink');
1416 if ($targetPage == Router
::$PAGE_EXPORT) {
1417 // Export links as a Netscape Bookmarks file
1419 if (empty($_GET['selection'])) {
1420 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1421 $PAGE->renderPage('export');
1425 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1426 $selection = $_GET['selection'];
1427 if (isset($_GET['prepend_note_url'])) {
1428 $prependNoteUrl = $_GET['prepend_note_url'];
1430 $prependNoteUrl = false;
1436 NetscapeBookmarkUtils
::filterAndFormat(
1443 } catch (Exception
$exc) {
1444 header('Content-Type: text/plain; charset=utf-8');
1445 echo $exc->getMessage();
1448 $now = new DateTime();
1449 header('Content-Type: text/html; charset=utf-8');
1451 'Content-disposition: attachment; filename=bookmarks_'
1452 .$selection.'_'.$now->format(LinkDB
::LINK_DATE_FORMAT
).'.html'
1454 $PAGE->assign('date', $now->format(DateTime
::RFC822
));
1455 $PAGE->assign('eol', PHP_EOL
);
1456 $PAGE->assign('selection', $selection);
1457 $PAGE->renderPage('export.bookmarks');
1461 if ($targetPage == Router
::$PAGE_IMPORT) {
1462 // Upload a Netscape bookmark dump to import its contents
1464 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1465 // Show import dialog
1468 get_max_upload_size(
1469 ini_get('post_max_size'),
1470 ini_get('upload_max_filesize'),
1476 get_max_upload_size(
1477 ini_get('post_max_size'),
1478 ini_get('upload_max_filesize'),
1482 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1483 $PAGE->renderPage('import');
1487 // Import bookmarks from an uploaded file
1488 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1489 // The file is too big or some form field may be missing.
1492 'The file you are trying to upload is probably bigger than what this webserver can accept'
1493 .' (%s). Please upload in smaller chunks.'
1495 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1497 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router
::$PAGE_IMPORT .'\';</script>';
1500 if (! $sessionManager->checkToken($_POST['token'])) {
1501 die('Wrong token.');
1503 $status = NetscapeBookmarkUtils
::import(
1510 echo '<script>alert("'.$status.'");document.location=\'?do='
1511 .Router
::$PAGE_IMPORT .'\';</script>';
1515 // Plugin administration page
1516 if ($targetPage == Router
::$PAGE_PLUGINSADMIN) {
1517 $pluginMeta = $pluginManager->getPluginsMeta();
1519 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1520 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v
['order'] !== false; });
1522 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1525 function($a, $b) { return $a
['order'] - $b
['order']; }
1527 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v
['order'] === false; });
1529 $PAGE->assign('enabledPlugins', $enabledPlugins);
1530 $PAGE->assign('disabledPlugins', $disabledPlugins);
1531 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
1532 $PAGE->renderPage('pluginsadmin');
1536 // Plugin administration form action
1537 if ($targetPage == Router
::$PAGE_SAVE_PLUGINSADMIN) {
1539 if (isset($_POST['parameters_form'])) {
1540 unset($_POST['parameters_form']);
1541 foreach ($_POST as $param => $value) {
1542 $conf->set('plugins.'. $param, escape($value));
1546 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1548 $conf->write(isLoggedIn());
1549 $history->updateSettings();
1551 catch (Exception
$e) {
1553 'ERROR while saving plugin configuration:.' . PHP_EOL
.
1557 // TODO: do not handle exceptions/errors in JS.
1558 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router
::$PAGE_PLUGINSADMIN .'\';</script>';
1561 header('Location: ?do='. Router
::$PAGE_PLUGINSADMIN);
1565 // Get a fresh token
1566 if ($targetPage == Router
::$GET_TOKEN) {
1567 header('Content-Type:text/plain');
1568 echo $sessionManager->generateToken($conf);
1572 // -------- Otherwise, simply display search form and links:
1573 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
1578 * Template for the list of links (<div id="linklist">)
1579 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1581 * @param pageBuilder $PAGE pageBuilder instance.
1582 * @param LinkDB $LINKSDB LinkDB instance.
1583 * @param ConfigManager $conf Configuration Manager instance.
1584 * @param PluginManager $pluginManager Plugin Manager instance.
1586 function buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager)
1588 // Used in templates
1589 if (isset($_GET['searchtags'])) {
1590 if (! empty($_GET['searchtags'])) {
1591 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1593 $searchtags = false;
1598 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1601 if (! empty($_SERVER['QUERY_STRING'])
1602 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1604 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1605 } catch (LinkNotFoundException
$e) {
1606 $PAGE->render404($e->getMessage());
1610 // Filter links according search parameters.
1611 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
1613 'searchtags' => $searchtags,
1614 'searchterm' => $searchterm,
1616 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
1619 // ---- Handle paging.
1621 foreach ($linksToDisplay as $key => $value) {
1627 // Select articles according to paging.
1628 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1629 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1630 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1631 $page = $page < 1 ? 1 : $page;
1632 $page = $page > $pagecount ? $pagecount : $page;
1634 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1635 $end = $i +
$_SESSION['LINKS_PER_PAGE'];
1636 $linkDisp = array();
1637 while ($i<$end && $i<count($keys))
1639 $link = $linksToDisplay[$keys[$i]];
1640 $link['description'] = format_description(
1641 $link['description'],
1642 $conf->get('redirector.url'),
1643 $conf->get('redirector.encode_url')
1645 $classLi = ($i %
2) != 0 ? '' : 'publicLinkHightLight';
1646 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
1647 $link['timestamp'] = $link['created']->getTimestamp();
1648 if (! empty($link['updated'])) {
1649 $link['updated_timestamp'] = $link['updated']->getTimestamp();
1651 $link['updated_timestamp'] = '';
1653 $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY
);
1654 uasort($taglist, 'strcasecmp');
1655 $link['taglist'] = $taglist;
1656 // Check for both signs of a note: starting with ? and 7 chars long.
1657 if ($link['url'][0] === '?' &&
1658 strlen($link['url']) === 7) {
1659 $link['url'] = index_url($_SERVER) . $link['url'];
1662 $linkDisp[$keys[$i]] = $link;
1666 // Compute paging navigation
1667 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
1668 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1669 $previous_page_url = '';
1670 if ($i != count($keys)) {
1671 $previous_page_url = '?page=' . ($page+
1) . $searchtermUrl . $searchtagsUrl;
1675 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1678 // Fill all template fields.
1680 'previous_page_url' => $previous_page_url,
1681 'next_page_url' => $next_page_url,
1682 'page_current' => $page,
1683 'page_max' => $pagecount,
1684 'result_count' => count($linksToDisplay),
1685 'search_term' => $searchterm,
1686 'search_tags' => $searchtags,
1687 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
1688 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
1689 'links' => $linkDisp,
1692 // If there is only a single link, we change on-the-fly the title of the page.
1693 if (count($linksToDisplay) == 1) {
1694 $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
1695 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1696 $data['pagetitle'] = t('Search: ');
1697 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1698 $bracketWrap = function ($tag) {
1699 return '['. $tag .']';
1701 $data['pagetitle'] .= ! empty($searchtags)
1702 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1704 $data['pagetitle'] .= '- '. $conf->get('general.title');
1707 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => isLoggedIn()));
1709 foreach ($data as $key => $value) {
1710 $PAGE->assign($key, $value);
1717 * Compute the thumbnail for a link.
1719 * With a link to the original URL.
1720 * Understands various services (youtube.com...)
1721 * Input: $url = URL for which the thumbnail must be found.
1722 * $href = if provided, this URL will be followed instead of $url
1723 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1724 * Some of them may be missing.
1725 * Return an empty array if no thumbnail available.
1727 * @param ConfigManager $conf Configuration Manager instance.
1728 * @param string $url
1729 * @param string|bool $href
1733 function computeThumbnail($conf, $url, $href = false)
1735 if (!$conf->get('thumbnail.enable_thumbnails')) return array();
1736 if ($href==false) $href=$url;
1738 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1739 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1740 // ^^^^^^^^^^^ ^^^^^^^^^^^
1741 $domain = parse_url($url,PHP_URL_HOST
);
1742 if ($domain=='youtube.com' || $domain=='www.youtube.com')
1744 parse_str(parse_url($url,PHP_URL_QUERY
), $params); // Extract video ID and get thumbnail
1745 if (!empty($params['v'])) return array('src'=>'https://img.youtube.com/vi/'.$params['v'].'/default.jpg',
1746 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1748 if ($domain=='youtu.be') // Youtube short links
1750 $path = parse_url($url,PHP_URL_PATH
);
1751 return array('src'=>'https://img.youtube.com/vi'.$path.'/default.jpg',
1752 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1754 if ($domain=='pix.toile-libre.org') // pix.toile-libre.org image hosting
1756 parse_str(parse_url($url,PHP_URL_QUERY
), $params); // Extract image filename.
1757 if (!empty($params) && !empty($params['img'])) return array('src'=>'http://pix.toile-libre.org/upload/thumb/'.urlencode($params['img']),
1758 'href'=>$href,'style'=>'max-width:120px; max-height:150px','alt'=>'pix.toile-libre.org thumbnail');
1761 if ($domain=='imgur.com')
1763 $path = parse_url($url,PHP_URL_PATH
);
1764 if (startsWith($path,'/a/')) return array(); // Thumbnails for albums are not available.
1765 if (startsWith($path,'/r/')) return array('src'=>'https://i.imgur.com/'.basename($path).'s.jpg',
1766 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1767 if (startsWith($path,'/gallery/')) return array('src'=>'https://i.imgur.com'.substr($path,8).'s.jpg',
1768 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1770 if (substr_count($path,'/')==1) return array('src'=>'https://i.imgur.com/'.substr($path,1).'s.jpg',
1771 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1773 if ($domain=='i.imgur.com')
1775 $pi = pathinfo(parse_url($url,PHP_URL_PATH
));
1776 if (!empty($pi['filename'])) return array('src'=>'https://i.imgur.com/'.$pi['filename'].'s.jpg',
1777 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1779 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
1781 if (strpos($url,'dailymotion.com/video/')!==false)
1783 $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
1784 return array('src'=>$thumburl,
1785 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'DailyMotion thumbnail');
1788 if (endsWith($domain,'.imageshack.us'))
1790 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION
));
1791 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1793 $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
1794 return array('src'=>$thumburl,
1795 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'imageshack.us thumbnail');
1799 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1800 // So we deport the thumbnail generation in order not to slow down page generation
1801 // (and we also cache the thumbnail)
1803 if (! $conf->get('thumbnail.enable_localcache')) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1805 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
1806 || $domain=='vimeo.com'
1807 || $domain=='ted.com' || endsWith($domain,'.ted.com')
1808 || $domain=='xkcd.com' || endsWith($domain,'.xkcd.com')
1811 if ($domain=='vimeo.com')
1812 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1813 $path = parse_url($url,PHP_URL_PATH
);
1814 if (!preg_match('!/\d+.+?!',$path)) return array(); // This is not a single video URL.
1816 if ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
1817 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1818 $path = parse_url($url,PHP_URL_PATH
);
1819 if (!preg_match('!/\d+.+?!',$path)) return array();
1821 if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
1822 { // Make sure this TED URL points to a video (/talks/...)
1823 $path = parse_url($url,PHP_URL_PATH
);
1824 if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
1826 $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)
1827 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1828 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1831 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1832 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1833 // But using the extension will do.
1834 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION
));
1835 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1837 $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)
1838 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1839 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1841 return array(); // No thumbnail.
1846 // Returns the HTML code to display a thumbnail for a link
1847 // with a link to the original URL.
1848 // Understands various services (youtube.com...)
1849 // Input: $url = URL for which the thumbnail must be found.
1850 // $href = if provided, this URL will be followed instead of $url
1851 // Returns '' if no thumbnail available.
1852 function thumbnail($url,$href=false)
1856 $t = computeThumbnail($conf, $url,$href);
1857 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1859 $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"';
1860 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1861 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1862 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1863 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1868 // Returns the HTML code to display a thumbnail for a link
1869 // for the picture wall (using lazy image loading)
1870 // Understands various services (youtube.com...)
1871 // Input: $url = URL for which the thumbnail must be found.
1872 // $href = if provided, this URL will be followed instead of $url
1873 // Returns '' if no thumbnail available.
1874 function lazyThumbnail($conf, $url,$href=false)
1878 $t = computeThumbnail($conf, $url,$href);
1879 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1881 $html='<a href="'.escape($t['href']).'">';
1884 $html.='<img class="b-lazy" src="#" data-src="'.escape($t['src']).'"';
1886 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1887 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1888 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1889 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1892 // No-JavaScript fallback.
1893 $html.='<noscript><img src="'.escape($t['src']).'"';
1894 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1895 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1896 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1897 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1898 $html.='></noscript></a>';
1906 * This function should NEVER be called if the file data/config.php exists.
1908 * @param ConfigManager $conf Configuration Manager instance.
1909 * @param SessionManager $sessionManager SessionManager instance
1911 function install($conf, $sessionManager) {
1912 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1913 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1916 // This part makes sure sessions works correctly.
1917 // (Because on some hosts, session.save_path may not be set correctly,
1918 // or we may not have write access to it.)
1919 if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working'))
1921 // Step 2: Check if data in session is correct.
1923 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1924 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1925 'and that you have write access to it.<br>'.
1926 'It currently points to %s.<br>'.
1927 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1928 'or any custom hostname without a dot causes cookie storage to fail. '.
1929 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1931 $msg = sprintf($msg, session_save_path());
1933 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1936 if (!isset($_SESSION['session_tested']))
1937 { // Step 1 : Try to store data in session and reload page.
1938 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1939 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1941 if (isset($_GET['test_session']))
1942 { // Step 3: Sessions are OK. Remove test parameter from URL.
1943 header('Location: '.index_url($_SERVER));
1947 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1950 if (!empty($_POST['continent']) && !empty($_POST['city'])
1951 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1953 $tz = $_POST['continent'].'/'.$_POST['city'];
1955 $conf->set('general.timezone', $tz);
1956 $login = $_POST['setlogin'];
1957 $conf->set('credentials.login', $login);
1958 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1959 $conf->set('credentials.salt', $salt);
1960 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
1961 if (!empty($_POST['title'])) {
1962 $conf->set('general.title', escape($_POST['title']));
1964 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
1966 $conf->set('translation.language', escape($_POST['language']));
1967 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1968 $conf->set('api.enabled', !empty($_POST['enableApi']));
1971 generate_api_secret(
1972 $conf->get('credentials.login'),
1973 $conf->get('credentials.salt')
1977 // Everything is ok, let's create config file.
1978 $conf->write(isLoggedIn());
1980 catch(Exception
$e) {
1982 'ERROR while writing config file after installation.' . PHP_EOL
.
1986 // TODO: do not handle exceptions/errors in JS.
1987 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1990 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
1994 $PAGE = new PageBuilder($conf, null, $sessionManager->generateToken());
1995 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1996 $PAGE->assign('continents', $continents);
1997 $PAGE->assign('cities', $cities);
1998 $PAGE->assign('languages', Languages
::getAvailableLanguages());
1999 $PAGE->renderPage('install');
2004 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2005 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2006 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2007 * This function is called by passing the URL:
2008 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2009 * [URL] is the URL of the link (e.g. a flickr page)
2010 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2011 * The function below will fetch the image from the webservice and store it in the cache.
2013 * @param ConfigManager $conf Configuration Manager instance,
2015 function genThumbnail($conf)
2017 // Make sure the parameters in the URL were generated by us.
2018 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt'));
2019 if ($sign!=$_GET['hmac']) die('Naughty boy!');
2021 $cacheDir = $conf->get('resource.thumbnails_cache', 'cache');
2022 // Let's see if we don't already have the image for this URL in the cache.
2023 $thumbname=hash('sha1',$_GET['url']).'.jpg';
2024 if (is_file($cacheDir .'/'. $thumbname))
2025 { // We have the thumbnail, just serve it:
2026 header('Content-Type: image/jpeg');
2027 echo file_get_contents($cacheDir .'/'. $thumbname);
2030 // We may also serve a blank image (if service did not respond)
2031 $blankname=hash('sha1',$_GET['url']).'.gif';
2032 if (is_file($cacheDir .'/'. $blankname))
2034 header('Content-Type: image/gif');
2035 echo file_get_contents($cacheDir .'/'. $blankname);
2039 // Otherwise, generate the thumbnail.
2040 $url = $_GET['url'];
2041 $domain = parse_url($url,PHP_URL_HOST
);
2043 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
2045 // Crude replacement to handle new flickr domain policy (They prefer www. now)
2046 $url = str_replace('http://flickr.com/','http://www.flickr.com/',$url);
2048 // Is this a link to an image, or to a flickr page ?
2050 if (endsWith(parse_url($url, PHP_URL_PATH
), '.jpg'))
2051 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
2052 preg_match('!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
2053 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
2055 else // This is a flickr page (html)
2057 // Get the flickr html page.
2058 list($headers, $content) = get_http_response($url, 20);
2059 if (strpos($headers[0], '200 OK') !== false)
2061 // flickr now nicely provides the URL of the thumbnail in each flickr page.
2062 preg_match('!<link rel=\"image_src\" href=\"(.+?)\"!', $content, $matches);
2063 if (!empty($matches[1])) $imageurl=$matches[1];
2065 // In albums (and some other pages), the link rel="image_src" is not provided,
2066 // but flickr provides:
2067 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2070 preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!', $content, $matches);
2071 if (!empty($matches[1])) $imageurl=$matches[1];
2077 { // Let's download the image.
2078 // Image is 240x120, so 10 seconds to download should be enough.
2079 list($headers, $content) = get_http_response($imageurl, 10);
2080 if (strpos($headers[0], '200 OK') !== false) {
2081 // Save image to cache.
2082 file_put_contents($cacheDir .'/'. $thumbname, $content);
2083 header('Content-Type: image/jpeg');
2090 elseif ($domain=='vimeo.com' )
2092 // This is more complex: we have to perform a HTTP request, then parse the result.
2093 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2094 $vid = substr(parse_url($url,PHP_URL_PATH
),1);
2095 list($headers, $content) = get_http_response('https://vimeo.com/api/v2/video/'.escape($vid).'.php', 5);
2096 if (strpos($headers[0], '200 OK') !== false) {
2097 $t = unserialize($content);
2098 $imageurl = $t[0]['thumbnail_medium'];
2099 // Then we download the image and serve it to our client.
2100 list($headers, $content) = get_http_response($imageurl, 10);
2101 if (strpos($headers[0], '200 OK') !== false) {
2102 // Save image to cache.
2103 file_put_contents($cacheDir .'/'. $thumbname, $content);
2104 header('Content-Type: image/jpeg');
2111 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
2113 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2114 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2115 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2116 list($headers, $content) = get_http_response($url, 5);
2117 if (strpos($headers[0], '200 OK') !== false) {
2118 // Extract the link to the thumbnail
2119 preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!', $content, $matches);
2120 if (!empty($matches[1]))
2121 { // Let's download the image.
2122 $imageurl=$matches[1];
2123 // No control on image size, so wait long enough
2124 list($headers, $content) = get_http_response($imageurl, 20);
2125 if (strpos($headers[0], '200 OK') !== false) {
2126 $filepath = $cacheDir .'/'. $thumbname;
2127 file_put_contents($filepath, $content); // Save image to cache.
2128 if (resizeImage($filepath))
2130 header('Content-Type: image/jpeg');
2131 echo file_get_contents($filepath);
2139 elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
2141 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2142 // http://xkcd.com/327/
2143 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2144 list($headers, $content) = get_http_response($url, 5);
2145 if (strpos($headers[0], '200 OK') !== false) {
2146 // Extract the link to the thumbnail
2147 preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!', $content, $matches);
2148 if (!empty($matches[1]))
2149 { // Let's download the image.
2150 $imageurl=$matches[1];
2151 // No control on image size, so wait long enough
2152 list($headers, $content) = get_http_response($imageurl, 20);
2153 if (strpos($headers[0], '200 OK') !== false) {
2154 $filepath = $cacheDir.'/'.$thumbname;
2155 // Save image to cache.
2156 file_put_contents($filepath, $content);
2157 if (resizeImage($filepath))
2159 header('Content-Type: image/jpeg');
2160 echo file_get_contents($filepath);
2170 // For all other domains, we try to download the image and make a thumbnail.
2171 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2172 list($headers, $content) = get_http_response($url, 30);
2173 if (strpos($headers[0], '200 OK') !== false) {
2174 $filepath = $cacheDir .'/'.$thumbname;
2175 // Save image to cache.
2176 file_put_contents($filepath, $content);
2177 if (resizeImage($filepath))
2179 header('Content-Type: image/jpeg');
2180 echo file_get_contents($filepath);
2187 // Otherwise, return an empty image (8x8 transparent gif)
2188 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
2189 // Also put something in cache so that this URL is not requested twice.
2190 file_put_contents($cacheDir .'/'. $blankname, $blankgif);
2191 header('Content-Type: image/gif');
2195 // Make a thumbnail of the image (to width: 120 pixels)
2196 // Returns true if success, false otherwise.
2197 function resizeImage($filepath)
2199 if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
2201 // Trick: some stupid people rename GIF as JPEG... or else.
2202 // So we really try to open each image type whatever the extension is.
2203 $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
2205 $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
2206 $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
2207 $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
2208 if (!$im) return false; // Unable to open image (corrupted or not an image)
2211 $ystart = 0; $yheight=$h;
2212 if ($h>$w) { $ystart
= ($h
/2)-($w
/2); $yheight
=$w
/2; }
2213 $nw = 120; // Desired width
2214 $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
2216 $im2 = imagecreatetruecolor($nw,$nh);
2217 imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
2218 imageinterlace($im2,true); // For progressive JPEG.
2219 $tempname=$filepath.'_TEMP.jpg';
2220 imagejpeg($im2, $tempname, 90);
2224 rename($tempname,$filepath); // Overwrite original picture with thumbnail.
2228 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf
); exit; } // Thumbnail generation/cache does not need the link database.
2229 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf
); exit; }
2230 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
2231 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
2235 $history = new History($conf->get('resource.history'));
2236 } catch(Exception
$e) {
2237 die($e->getMessage());
2240 $linkDb = new LinkDB(
2241 $conf->get('resource.datastore'),
2243 $conf->get('privacy.hide_public_links'),
2244 $conf->get('redirector.url'),
2245 $conf->get('redirector.encode_url')
2248 $container = new \Slim\
Container();
2249 $container['conf'] = $conf;
2250 $container['plugins'] = $pluginManager;
2251 $container['history'] = $history;
2252 $app = new \Slim\
App($container);
2255 $app->group('/api/v1', function() {
2256 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
2257 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
2258 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
2259 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
2260 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
2261 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
2262 $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
2263 })->add('\Shaarli\Api\ApiMiddleware');
2265 $response = $app->run(true);
2266 // Hack to make Slim and Shaarli router work together:
2267 // If a Slim route isn't found and NOT API call, we call renderPage().
2268 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
2269 // We use UTF-8 for proper international characters handling.
2270 header('Content-Type: text/html; charset=utf-8');
2271 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
2273 $app->respond($response);