]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
Refactor session and cookie timeout control
[github/shaarli/Shaarli.git] / index.php
1 <?php
2 /**
3 * Shaarli - The personal, minimalist, super-fast, database free, bookmarking service.
4 *
5 * Friendly fork by the Shaarli community:
6 * - https://github.com/shaarli/Shaarli
7 *
8 * Original project by sebsauvage.net:
9 * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
10 * - https://github.com/sebsauvage/Shaarli
11 *
12 * Licence: http://www.opensource.org/licenses/zlib-license.php
13 *
14 * Requires: PHP 5.5.x
15 */
16
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');
21 }
22
23 /*
24 * PHP configuration
25 */
26
27 // http://server.com/x/shaarli --> /shaarli/
28 define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0)));
29
30 // High execution time in case of problematic imports/exports.
31 ini_set('max_input_time','60');
32
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');
37
38 // See all error except warnings
39 error_reporting(E_ALL^E_WARNING);
40 // See all errors (for debugging only)
41 //error_reporting(-1);
42
43
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/";
53 exit;
54 }
55 require_once 'inc/rain.tpl.class.php';
56 require_once __DIR__ . '/vendor/autoload.php';
57
58 // Shaarli library
59 require_once 'application/ApplicationUtils.php';
60 require_once 'application/Cache.php';
61 require_once 'application/CachedPage.php';
62 require_once 'application/config/ConfigPlugin.php';
63 require_once 'application/FeedBuilder.php';
64 require_once 'application/FileUtils.php';
65 require_once 'application/History.php';
66 require_once 'application/HttpUtils.php';
67 require_once 'application/LinkDB.php';
68 require_once 'application/LinkFilter.php';
69 require_once 'application/LinkUtils.php';
70 require_once 'application/NetscapeBookmarkUtils.php';
71 require_once 'application/PageBuilder.php';
72 require_once 'application/TimeZone.php';
73 require_once 'application/Url.php';
74 require_once 'application/Utils.php';
75 require_once 'application/PluginManager.php';
76 require_once 'application/Router.php';
77 require_once 'application/Updater.php';
78 use \Shaarli\Languages;
79 use \Shaarli\ThemeUtils;
80 use \Shaarli\Config\ConfigManager;
81 use \Shaarli\Security\LoginManager;
82 use \Shaarli\Security\SessionManager;
83
84 // Ensure the PHP version is supported
85 try {
86 ApplicationUtils::checkPHPVersion('5.5', PHP_VERSION);
87 } catch(Exception $exc) {
88 header('Content-Type: text/plain; charset=utf-8');
89 echo $exc->getMessage();
90 exit;
91 }
92
93 define('SHAARLI_VERSION', ApplicationUtils::getVersion(__DIR__ .'/'. ApplicationUtils::$VERSION_FILE));
94
95 // Force cookie path (but do not change lifetime)
96 $cookie = session_get_cookie_params();
97 $cookiedir = '';
98 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
99 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
100 }
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);
110
111 session_name('shaarli');
112 // Start session if needed (Some server auto-start sessions).
113 if (session_id() == '') {
114 session_start();
115 }
116
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();
121 }
122
123 $conf = new ConfigManager();
124 $sessionManager = new SessionManager($_SESSION, $conf);
125 $loginManager = new LoginManager($GLOBALS, $conf, $sessionManager);
126 $clientIpId = client_ip_id($_SERVER);
127
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);
131 }
132
133 // Sniff browser language and set date format accordingly.
134 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
135 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
136 }
137
138 new Languages(setlocale(LC_MESSAGES, 0), $conf);
139
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
144
145 $pluginManager = new PluginManager($conf);
146 $pluginManager->load($conf->get('general.enabled_plugins'));
147
148 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
149
150 ob_start(); // Output buffering for the page cache.
151
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");
157
158 if (! is_file($conf->getConfigFileExt())) {
159 // Ensure Shaarli has proper access to its resources
160 $errors = ApplicationUtils::checkResourcePermissions($conf);
161
162 if ($errors != array()) {
163 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
164
165 foreach ($errors as $error) {
166 $message .= '<li>'.$error.'</li>';
167 }
168 $message .= '</ul>';
169
170 header('Content-Type: text/html; charset=utf-8');
171 echo $message;
172 exit;
173 }
174
175 // Display the installation form if no existing config is found
176 install($conf, $sessionManager);
177 }
178
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')));
181
182 $loginManager->checkLoginState($_COOKIE, $clientIpId, STAY_SIGNED_IN_TOKEN);
183
184 /**
185 * Adapter function to ensure compatibility with third-party templates
186 *
187 * @see https://github.com/shaarli/Shaarli/pull/1086
188 *
189 * @return bool true when the user is logged in, false otherwise
190 */
191 function isLoggedIn()
192 {
193 global $loginManager;
194 return $loginManager->isLoggedIn();
195 }
196
197
198 // ------------------------------------------------------------------------------------------
199 // Process login form: Check if login/password is correct.
200 if (isset($_POST['login'])) {
201 if (! $loginManager->canLogin($_SERVER)) {
202 die(t('I said: NO. You are banned for the moment. Go away.'));
203 }
204 if (isset($_POST['password'])
205 && $sessionManager->checkToken($_POST['token'])
206 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
207 ) {
208 $loginManager->handleSuccessfulLogin($_SERVER);
209
210 $cookiedir = '';
211 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
212 // Note: Never forget the trailing slash on the cookie path!
213 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
214 }
215
216 if (!empty($_POST['longlastingsession'])) {
217 // Keep the session cookie even after the browser closes
218 $sessionManager->setStaySignedIn(true);
219 $expirationTime = $sessionManager->extendSession();
220
221 setcookie(
222 $sessionManager::$LOGGED_IN_COOKIE,
223 STAY_SIGNED_IN_TOKEN,
224 $expirationTime,
225 WEB_PATH
226 );
227
228 } else {
229 // Standard session expiration (=when browser closes)
230 $expirationTime = 0;
231 }
232
233 // Send cookie with the new expiration date to the browser
234 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
235 session_regenerate_id(true);
236
237 // Optional redirect after login:
238 if (isset($_GET['post'])) {
239 $uri = '?post='. urlencode($_GET['post']);
240 foreach (array('description', 'source', 'title', 'tags') as $param) {
241 if (!empty($_GET[$param])) {
242 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
243 }
244 }
245 header('Location: '. $uri);
246 exit;
247 }
248
249 if (isset($_GET['edit_link'])) {
250 header('Location: ?edit_link='. escape($_GET['edit_link']));
251 exit;
252 }
253
254 if (isset($_POST['returnurl'])) {
255 // Prevent loops over login screen.
256 if (strpos($_POST['returnurl'], 'do=login') === false) {
257 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
258 exit;
259 }
260 }
261 header('Location: ?'); exit;
262 } else {
263 $loginManager->handleFailedLogin($_SERVER);
264 $redir = '&username='. urlencode($_POST['login']);
265 if (isset($_GET['post'])) {
266 $redir .= '&post=' . urlencode($_GET['post']);
267 foreach (array('description', 'source', 'title', 'tags') as $param) {
268 if (!empty($_GET[$param])) {
269 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
270 }
271 }
272 }
273 // Redirect to login screen.
274 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
275 exit;
276 }
277 }
278
279 // ------------------------------------------------------------------------------------------
280 // Token management for XSRF protection
281 // Token should be used in any form which acts on data (create,update,delete,import...).
282 if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
283
284 /**
285 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
286 * Gives the last 7 days (which have links).
287 * This RSS feed cannot be filtered.
288 *
289 * @param ConfigManager $conf Configuration Manager instance
290 * @param LoginManager $loginManager LoginManager instance
291 */
292 function showDailyRSS($conf, $loginManager) {
293 // Cache system
294 $query = $_SERVER['QUERY_STRING'];
295 $cache = new CachedPage(
296 $conf->get('config.PAGE_CACHE'),
297 page_url($_SERVER),
298 startsWith($query,'do=dailyrss') && !$loginManager->isLoggedIn()
299 );
300 $cached = $cache->cachedVersion();
301 if (!empty($cached)) {
302 echo $cached;
303 exit;
304 }
305
306 // If cached was not found (or not usable), then read the database and build the response:
307 // Read links from database (and filter private links if used it not logged in).
308 $LINKSDB = new LinkDB(
309 $conf->get('resource.datastore'),
310 $loginManager->isLoggedIn(),
311 $conf->get('privacy.hide_public_links'),
312 $conf->get('redirector.url'),
313 $conf->get('redirector.encode_url')
314 );
315
316 /* Some Shaarlies may have very few links, so we need to look
317 back in time until we have enough days ($nb_of_days).
318 */
319 $nb_of_days = 7; // We take 7 days.
320 $today = date('Ymd');
321 $days = array();
322
323 foreach ($LINKSDB as $link) {
324 $day = $link['created']->format('Ymd'); // Extract day (without time)
325 if (strcmp($day, $today) < 0) {
326 if (empty($days[$day])) {
327 $days[$day] = array();
328 }
329 $days[$day][] = $link;
330 }
331
332 if (count($days) > $nb_of_days) {
333 break; // Have we collected enough days?
334 }
335 }
336
337 // Build the RSS feed.
338 header('Content-Type: application/rss+xml; charset=utf-8');
339 $pageaddr = escape(index_url($_SERVER));
340 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
341 echo '<channel>';
342 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
343 echo '<link>'. $pageaddr .'</link>';
344 echo '<description>Daily shared links</description>';
345 echo '<language>en-en</language>';
346 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL;
347
348 // For each day.
349 foreach ($days as $day => $links) {
350 $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
351 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
352
353 // We pre-format some fields for proper output.
354 foreach ($links as &$link) {
355 $link['formatedDescription'] = format_description(
356 $link['description'],
357 $conf->get('redirector.url'),
358 $conf->get('redirector.encode_url')
359 );
360 $link['thumbnail'] = thumbnail($conf, $link['url']);
361 $link['timestamp'] = $link['created']->getTimestamp();
362 if (startsWith($link['url'], '?')) {
363 $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
364 }
365 }
366
367 // Then build the HTML for this day:
368 $tpl = new RainTPL;
369 $tpl->assign('title', $conf->get('general.title'));
370 $tpl->assign('daydate', $dayDate->getTimestamp());
371 $tpl->assign('absurl', $absurl);
372 $tpl->assign('links', $links);
373 $tpl->assign('rssdate', escape($dayDate->format(DateTime::RSS)));
374 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
375 $html = $tpl->draw('dailyrss', true);
376
377 echo $html . PHP_EOL;
378 }
379 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
380
381 $cache->cache(ob_get_contents());
382 ob_end_flush();
383 exit;
384 }
385
386 /**
387 * Show the 'Daily' page.
388 *
389 * @param PageBuilder $pageBuilder Template engine wrapper.
390 * @param LinkDB $LINKSDB LinkDB instance.
391 * @param ConfigManager $conf Configuration Manager instance.
392 * @param PluginManager $pluginManager Plugin Manager instance.
393 * @param LoginManager $loginManager Login Manager instance
394 */
395 function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
396 {
397 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
398 if (isset($_GET['day'])) {
399 $day = $_GET['day'];
400 }
401
402 $days = $LINKSDB->days();
403 $i = array_search($day, $days);
404 if ($i === false && count($days)) {
405 // no links for day, but at least one day with links
406 $i = count($days) - 1;
407 $day = $days[$i];
408 }
409 $previousday = '';
410 $nextday = '';
411
412 if ($i !== false) {
413 if ($i >= 1) {
414 $previousday=$days[$i - 1];
415 }
416 if ($i < count($days) - 1) {
417 $nextday = $days[$i + 1];
418 }
419 }
420 try {
421 $linksToDisplay = $LINKSDB->filterDay($day);
422 } catch (Exception $exc) {
423 error_log($exc);
424 $linksToDisplay = array();
425 }
426
427 // We pre-format some fields for proper output.
428 foreach($linksToDisplay as $key => $link) {
429 $taglist = explode(' ',$link['tags']);
430 uasort($taglist, 'strcasecmp');
431 $linksToDisplay[$key]['taglist']=$taglist;
432 $linksToDisplay[$key]['formatedDescription'] = format_description(
433 $link['description'],
434 $conf->get('redirector.url'),
435 $conf->get('redirector.encode_url')
436 );
437 $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
438 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
439 }
440
441 $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
442 $data = array(
443 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
444 'linksToDisplay' => $linksToDisplay,
445 'day' => $dayDate->getTimestamp(),
446 'dayDate' => $dayDate,
447 'previousday' => $previousday,
448 'nextday' => $nextday,
449 );
450
451 /* Hook is called before column construction so that plugins don't have
452 to deal with columns. */
453 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
454
455 /* We need to spread the articles on 3 columns.
456 I did not want to use a JavaScript lib like http://masonry.desandro.com/
457 so I manually spread entries with a simple method: I roughly evaluate the
458 height of a div according to title and description length.
459 */
460 $columns = array(array(), array(), array()); // Entries to display, for each column.
461 $fill = array(0, 0, 0); // Rough estimate of columns fill.
462 foreach($data['linksToDisplay'] as $key => $link) {
463 // Roughly estimate length of entry (by counting characters)
464 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
465 // Description: 836 characters gives roughly 342 pixel height.
466 // This is not perfect, but it's usually OK.
467 $length = strlen($link['title']) + (342 * strlen($link['description'])) / 836;
468 if ($link['thumbnail']) {
469 $length += 100; // 1 thumbnails roughly takes 100 pixels height.
470 }
471 // Then put in column which is the less filled:
472 $smallest = min($fill); // find smallest value in array.
473 $index = array_search($smallest, $fill); // find index of this smallest value.
474 array_push($columns[$index], $link); // Put entry in this column.
475 $fill[$index] += $length;
476 }
477
478 $data['cols'] = $columns;
479
480 foreach ($data as $key => $value) {
481 $pageBuilder->assign($key, $value);
482 }
483
484 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
485 $pageBuilder->renderPage('daily');
486 exit;
487 }
488
489 /**
490 * Renders the linklist
491 *
492 * @param pageBuilder $PAGE pageBuilder instance.
493 * @param LinkDB $LINKSDB LinkDB instance.
494 * @param ConfigManager $conf Configuration Manager instance.
495 * @param PluginManager $pluginManager Plugin Manager instance.
496 */
497 function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager) {
498 buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager, $loginManager);
499 $PAGE->renderPage('linklist');
500 }
501
502 /**
503 * Render HTML page (according to URL parameters and user rights)
504 *
505 * @param ConfigManager $conf Configuration Manager instance.
506 * @param PluginManager $pluginManager Plugin Manager instance,
507 * @param LinkDB $LINKSDB
508 * @param History $history instance
509 * @param SessionManager $sessionManager SessionManager instance
510 * @param LoginManager $loginManager LoginManager instance
511 */
512 function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
513 {
514 $updater = new Updater(
515 read_updates_file($conf->get('resource.updates')),
516 $LINKSDB,
517 $conf,
518 $loginManager->isLoggedIn()
519 );
520 try {
521 $newUpdates = $updater->update();
522 if (! empty($newUpdates)) {
523 write_updates_file(
524 $conf->get('resource.updates'),
525 $updater->getDoneUpdates()
526 );
527 }
528 }
529 catch(Exception $e) {
530 die($e->getMessage());
531 }
532
533 $PAGE = new PageBuilder($conf, $LINKSDB, $sessionManager->generateToken(), $loginManager->isLoggedIn());
534 $PAGE->assign('linkcount', count($LINKSDB));
535 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
536 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
537
538 // Determine which page will be rendered.
539 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
540 $targetPage = Router::findPage($query, $_GET, $loginManager->isLoggedIn());
541
542 if (
543 // if the user isn't logged in
544 !$loginManager->isLoggedIn() &&
545 // and Shaarli doesn't have public content...
546 $conf->get('privacy.hide_public_links') &&
547 // and is configured to enforce the login
548 $conf->get('privacy.force_login') &&
549 // and the current page isn't already the login page
550 $targetPage !== Router::$PAGE_LOGIN &&
551 // and the user is not requesting a feed (which would lead to a different content-type as expected)
552 $targetPage !== Router::$PAGE_FEED_ATOM &&
553 $targetPage !== Router::$PAGE_FEED_RSS
554 ) {
555 // force current page to be the login page
556 $targetPage = Router::$PAGE_LOGIN;
557 }
558
559 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
560 // Then assign generated data to RainTPL.
561 $common_hooks = array(
562 'includes',
563 'header',
564 'footer',
565 );
566
567 foreach($common_hooks as $name) {
568 $plugin_data = array();
569 $pluginManager->executeHooks('render_' . $name, $plugin_data,
570 array(
571 'target' => $targetPage,
572 'loggedin' => $loginManager->isLoggedIn()
573 )
574 );
575 $PAGE->assign('plugins_' . $name, $plugin_data);
576 }
577
578 // -------- Display login form.
579 if ($targetPage == Router::$PAGE_LOGIN)
580 {
581 if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
582 if (isset($_GET['username'])) {
583 $PAGE->assign('username', escape($_GET['username']));
584 }
585 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
586 // add default state of the 'remember me' checkbox
587 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
588 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
589 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
590 $PAGE->renderPage('loginform');
591 exit;
592 }
593 // -------- User wants to logout.
594 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
595 {
596 invalidateCaches($conf->get('resource.page_cache'));
597 $sessionManager->logout();
598 setcookie(SessionManager::$LOGGED_IN_COOKIE, 'false', 0, WEB_PATH);
599 header('Location: ?');
600 exit;
601 }
602
603 // -------- Picture wall
604 if ($targetPage == Router::$PAGE_PICWALL)
605 {
606 // Optionally filter the results:
607 $links = $LINKSDB->filterSearch($_GET);
608 $linksToDisplay = array();
609
610 // Get only links which have a thumbnail.
611 foreach($links as $link)
612 {
613 $permalink='?'.$link['shorturl'];
614 $thumb=lazyThumbnail($conf, $link['url'],$permalink);
615 if ($thumb!='') // Only output links which have a thumbnail.
616 {
617 $link['thumbnail']=$thumb; // Thumbnail HTML code.
618 $linksToDisplay[]=$link; // Add to array.
619 }
620 }
621
622 $data = array(
623 'linksToDisplay' => $linksToDisplay,
624 );
625 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => $loginManager->isLoggedIn()));
626
627 foreach ($data as $key => $value) {
628 $PAGE->assign($key, $value);
629 }
630
631 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
632 $PAGE->renderPage('picwall');
633 exit;
634 }
635
636 // -------- Tag cloud
637 if ($targetPage == Router::$PAGE_TAGCLOUD)
638 {
639 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
640 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
641 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
642
643 // We sort tags alphabetically, then choose a font size according to count.
644 // First, find max value.
645 $maxcount = 0;
646 foreach ($tags as $value) {
647 $maxcount = max($maxcount, $value);
648 }
649
650 alphabetical_sort($tags, false, true);
651
652 $tagList = array();
653 foreach($tags as $key => $value) {
654 if (in_array($key, $filteringTags)) {
655 continue;
656 }
657 // Tag font size scaling:
658 // default 15 and 30 logarithm bases affect scaling,
659 // 22 and 6 are arbitrary font sizes for max and min sizes.
660 $size = log($value, 15) / log($maxcount, 30) * 2.2 + 0.8;
661 $tagList[$key] = array(
662 'count' => $value,
663 'size' => number_format($size, 2, '.', ''),
664 );
665 }
666
667 $searchTags = implode(' ', escape($filteringTags));
668 $data = array(
669 'search_tags' => $searchTags,
670 'tags' => $tagList,
671 );
672 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
673
674 foreach ($data as $key => $value) {
675 $PAGE->assign($key, $value);
676 }
677
678 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
679 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
680 $PAGE->renderPage('tag.cloud');
681 exit;
682 }
683
684 // -------- Tag list
685 if ($targetPage == Router::$PAGE_TAGLIST)
686 {
687 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
688 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
689 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
690 foreach ($filteringTags as $tag) {
691 if (array_key_exists($tag, $tags)) {
692 unset($tags[$tag]);
693 }
694 }
695
696 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
697 alphabetical_sort($tags, false, true);
698 }
699
700 $searchTags = implode(' ', escape($filteringTags));
701 $data = [
702 'search_tags' => $searchTags,
703 'tags' => $tags,
704 ];
705 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
706
707 foreach ($data as $key => $value) {
708 $PAGE->assign($key, $value);
709 }
710
711 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
712 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
713 $PAGE->renderPage('tag.list');
714 exit;
715 }
716
717 // Daily page.
718 if ($targetPage == Router::$PAGE_DAILY) {
719 showDaily($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
720 }
721
722 // ATOM and RSS feed.
723 if ($targetPage == Router::$PAGE_FEED_ATOM || $targetPage == Router::$PAGE_FEED_RSS) {
724 $feedType = $targetPage == Router::$PAGE_FEED_RSS ? FeedBuilder::$FEED_RSS : FeedBuilder::$FEED_ATOM;
725 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
726
727 // Cache system
728 $query = $_SERVER['QUERY_STRING'];
729 $cache = new CachedPage(
730 $conf->get('resource.page_cache'),
731 page_url($_SERVER),
732 startsWith($query,'do='. $targetPage) && !$loginManager->isLoggedIn()
733 );
734 $cached = $cache->cachedVersion();
735 if (!empty($cached)) {
736 echo $cached;
737 exit;
738 }
739
740 // Generate data.
741 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, $loginManager->isLoggedIn());
742 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0)));
743 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
744 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
745 $data = $feedGenerator->buildData();
746
747 // Process plugin hook.
748 $pluginManager->executeHooks('render_feed', $data, array(
749 'loggedin' => $loginManager->isLoggedIn(),
750 'target' => $targetPage,
751 ));
752
753 // Render the template.
754 $PAGE->assignAll($data);
755 $PAGE->renderPage('feed.'. $feedType);
756 $cache->cache(ob_get_contents());
757 ob_end_flush();
758 exit;
759 }
760
761 // Display opensearch plugin (XML)
762 if ($targetPage == Router::$PAGE_OPENSEARCH) {
763 header('Content-Type: application/xml; charset=utf-8');
764 $PAGE->assign('serverurl', index_url($_SERVER));
765 $PAGE->renderPage('opensearch');
766 exit;
767 }
768
769 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
770 if (isset($_GET['addtag']))
771 {
772 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
773 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER
774 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
775
776 // Prevent redirection loop
777 if (isset($params['addtag'])) {
778 unset($params['addtag']);
779 }
780
781 // Check if this tag is already in the search query and ignore it if it is.
782 // Each tag is always separated by a space
783 if (isset($params['searchtags'])) {
784 $current_tags = explode(' ', $params['searchtags']);
785 } else {
786 $current_tags = array();
787 }
788 $addtag = true;
789 foreach ($current_tags as $value) {
790 if ($value === $_GET['addtag']) {
791 $addtag = false;
792 break;
793 }
794 }
795 // Append the tag if necessary
796 if (empty($params['searchtags'])) {
797 $params['searchtags'] = trim($_GET['addtag']);
798 }
799 elseif ($addtag) {
800 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
801 }
802
803 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
804 header('Location: ?'.http_build_query($params));
805 exit;
806 }
807
808 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
809 if (isset($_GET['removetag'])) {
810 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
811 if (empty($_SERVER['HTTP_REFERER'])) {
812 header('Location: ?');
813 exit;
814 }
815
816 // In case browser does not send HTTP_REFERER
817 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
818
819 // Prevent redirection loop
820 if (isset($params['removetag'])) {
821 unset($params['removetag']);
822 }
823
824 if (isset($params['searchtags'])) {
825 $tags = explode(' ', $params['searchtags']);
826 // Remove value from array $tags.
827 $tags = array_diff($tags, array($_GET['removetag']));
828 $params['searchtags'] = implode(' ',$tags);
829
830 if (empty($params['searchtags'])) {
831 unset($params['searchtags']);
832 }
833
834 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
835 }
836 header('Location: ?'.http_build_query($params));
837 exit;
838 }
839
840 // -------- User wants to change the number of links per page (linksperpage=...)
841 if (isset($_GET['linksperpage'])) {
842 if (is_numeric($_GET['linksperpage'])) {
843 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
844 }
845
846 if (! empty($_SERVER['HTTP_REFERER'])) {
847 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
848 } else {
849 $location = '?';
850 }
851 header('Location: '. $location);
852 exit;
853 }
854
855 // -------- User wants to see only private links (toggle)
856 if (isset($_GET['visibility'])) {
857 if ($_GET['visibility'] === 'private') {
858 // Visibility not set or not already private, set private, otherwise reset it
859 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
860 // See only private links
861 $_SESSION['visibility'] = 'private';
862 } else {
863 unset($_SESSION['visibility']);
864 }
865 } elseif ($_GET['visibility'] === 'public') {
866 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
867 // See only public links
868 $_SESSION['visibility'] = 'public';
869 } else {
870 unset($_SESSION['visibility']);
871 }
872 }
873
874 if (! empty($_SERVER['HTTP_REFERER'])) {
875 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
876 } else {
877 $location = '?';
878 }
879 header('Location: '. $location);
880 exit;
881 }
882
883 // -------- User wants to see only untagged links (toggle)
884 if (isset($_GET['untaggedonly'])) {
885 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
886
887 if (! empty($_SERVER['HTTP_REFERER'])) {
888 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
889 } else {
890 $location = '?';
891 }
892 header('Location: '. $location);
893 exit;
894 }
895
896 // -------- Handle other actions allowed for non-logged in users:
897 if (!$loginManager->isLoggedIn())
898 {
899 // User tries to post new link but is not logged in:
900 // Show login screen, then redirect to ?post=...
901 if (isset($_GET['post']))
902 {
903 header( // Redirect to login page, then back to post link.
904 'Location: ?do=login&post='.urlencode($_GET['post']).
905 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
906 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
907 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
908 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
909 );
910 exit;
911 }
912
913 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
914 if (isset($_GET['edit_link'])) {
915 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
916 exit;
917 }
918
919 exit; // Never remove this one! All operations below are reserved for logged in user.
920 }
921
922 // -------- All other functions are reserved for the registered user:
923
924 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
925 if ($targetPage == Router::$PAGE_TOOLS)
926 {
927 $data = [
928 'pageabsaddr' => index_url($_SERVER),
929 'sslenabled' => is_https($_SERVER),
930 ];
931 $pluginManager->executeHooks('render_tools', $data);
932
933 foreach ($data as $key => $value) {
934 $PAGE->assign($key, $value);
935 }
936
937 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
938 $PAGE->renderPage('tools');
939 exit;
940 }
941
942 // -------- User wants to change his/her password.
943 if ($targetPage == Router::$PAGE_CHANGEPASSWORD)
944 {
945 if ($conf->get('security.open_shaarli')) {
946 die(t('You are not supposed to change a password on an Open Shaarli.'));
947 }
948
949 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
950 {
951 if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away!
952
953 // Make sure old password is correct.
954 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
955 if ($oldhash!= $conf->get('credentials.hash')) {
956 echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>';
957 exit;
958 }
959 // Save new password
960 // Salt renders rainbow-tables attacks useless.
961 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
962 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt')));
963 try {
964 $conf->write($loginManager->isLoggedIn());
965 }
966 catch(Exception $e) {
967 error_log(
968 'ERROR while writing config file after changing password.' . PHP_EOL .
969 $e->getMessage()
970 );
971
972 // TODO: do not handle exceptions/errors in JS.
973 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
974 exit;
975 }
976 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
977 exit;
978 }
979 else // show the change password form.
980 {
981 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
982 $PAGE->renderPage('changepassword');
983 exit;
984 }
985 }
986
987 // -------- User wants to change configuration
988 if ($targetPage == Router::$PAGE_CONFIGURE)
989 {
990 if (!empty($_POST['title']) )
991 {
992 if (!$sessionManager->checkToken($_POST['token'])) {
993 die(t('Wrong token.')); // Go away!
994 }
995 $tz = 'UTC';
996 if (!empty($_POST['continent']) && !empty($_POST['city'])
997 && isTimeZoneValid($_POST['continent'], $_POST['city'])
998 ) {
999 $tz = $_POST['continent'] . '/' . $_POST['city'];
1000 }
1001 $conf->set('general.timezone', $tz);
1002 $conf->set('general.title', escape($_POST['title']));
1003 $conf->set('general.header_link', escape($_POST['titleLink']));
1004 $conf->set('resource.theme', escape($_POST['theme']));
1005 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
1006 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
1007 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1008 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1009 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
1010 $conf->set('api.enabled', !empty($_POST['enableApi']));
1011 $conf->set('api.secret', escape($_POST['apiSecret']));
1012 $conf->set('translation.language', escape($_POST['language']));
1013
1014 try {
1015 $conf->write($loginManager->isLoggedIn());
1016 $history->updateSettings();
1017 invalidateCaches($conf->get('resource.page_cache'));
1018 }
1019 catch(Exception $e) {
1020 error_log(
1021 'ERROR while writing config file after configuration update.' . PHP_EOL .
1022 $e->getMessage()
1023 );
1024
1025 // TODO: do not handle exceptions/errors in JS.
1026 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1027 exit;
1028 }
1029 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1030 exit;
1031 }
1032 else // Show the configuration form.
1033 {
1034 $PAGE->assign('title', $conf->get('general.title'));
1035 $PAGE->assign('theme', $conf->get('resource.theme'));
1036 $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl')));
1037 list($continents, $cities) = generateTimeZoneData(
1038 timezone_identifiers_list(),
1039 $conf->get('general.timezone')
1040 );
1041 $PAGE->assign('continents', $continents);
1042 $PAGE->assign('cities', $cities);
1043 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
1044 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1045 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1046 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1047 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1048 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1049 $PAGE->assign('api_secret', $conf->get('api.secret'));
1050 $PAGE->assign('languages', Languages::getAvailableLanguages());
1051 $PAGE->assign('language', $conf->get('translation.language'));
1052 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
1053 $PAGE->renderPage('configure');
1054 exit;
1055 }
1056 }
1057
1058 // -------- User wants to rename a tag or delete it
1059 if ($targetPage == Router::$PAGE_CHANGETAG)
1060 {
1061 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1062 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1063 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
1064 $PAGE->renderPage('changetag');
1065 exit;
1066 }
1067
1068 if (!$sessionManager->checkToken($_POST['token'])) {
1069 die(t('Wrong token.'));
1070 }
1071
1072 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), escape($_POST['totag']));
1073 $LINKSDB->save($conf->get('resource.page_cache'));
1074 foreach ($alteredLinks as $link) {
1075 $history->updateLink($link);
1076 }
1077 $delete = empty($_POST['totag']);
1078 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1079 $count = count($alteredLinks);
1080 $alert = $delete
1081 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d links.', $count), $count)
1082 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d links.', $count), $count);
1083 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1084 exit;
1085 }
1086
1087 // -------- User wants to add a link without using the bookmarklet: Show form.
1088 if ($targetPage == Router::$PAGE_ADDLINK)
1089 {
1090 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1091 $PAGE->renderPage('addlink');
1092 exit;
1093 }
1094
1095 // -------- User clicked the "Save" button when editing a link: Save link to database.
1096 if (isset($_POST['save_edit']))
1097 {
1098 // Go away!
1099 if (! $sessionManager->checkToken($_POST['token'])) {
1100 die(t('Wrong token.'));
1101 }
1102
1103 // lf_id should only be present if the link exists.
1104 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
1105 // Linkdate is kept here to:
1106 // - use the same permalink for notes as they're displayed when creating them
1107 // - let users hack creation date of their posts
1108 // See: https://shaarli.readthedocs.io/en/master/Various-hacks/#changing-the-timestamp-for-a-shaare
1109 $linkdate = escape($_POST['lf_linkdate']);
1110 if (isset($LINKSDB[$id])) {
1111 // Edit
1112 $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
1113 $updated = new DateTime();
1114 $shortUrl = $LINKSDB[$id]['shorturl'];
1115 $new = false;
1116 } else {
1117 // New link
1118 $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
1119 $updated = null;
1120 $shortUrl = link_small_hash($created, $id);
1121 $new = true;
1122 }
1123
1124 // Remove multiple spaces.
1125 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
1126 // Remove first '-' char in tags.
1127 $tags = preg_replace('/(^| )\-/', '$1', $tags);
1128 // Remove duplicates.
1129 $tags = implode(' ', array_unique(explode(' ', $tags)));
1130
1131 if (empty(trim($_POST['lf_url']))) {
1132 $_POST['lf_url'] = '?' . smallHash($linkdate . $id);
1133 }
1134 $url = whitelist_protocols(trim($_POST['lf_url']), $conf->get('security.allowed_protocols'));
1135
1136 $link = array(
1137 'id' => $id,
1138 'title' => trim($_POST['lf_title']),
1139 'url' => $url,
1140 'description' => $_POST['lf_description'],
1141 'private' => (isset($_POST['lf_private']) ? 1 : 0),
1142 'created' => $created,
1143 'updated' => $updated,
1144 'tags' => str_replace(',', ' ', $tags),
1145 'shorturl' => $shortUrl,
1146 );
1147
1148 // If title is empty, use the URL as title.
1149 if ($link['title'] == '') {
1150 $link['title'] = $link['url'];
1151 }
1152
1153 $pluginManager->executeHooks('save_link', $link);
1154
1155 $LINKSDB[$id] = $link;
1156 $LINKSDB->save($conf->get('resource.page_cache'));
1157 if ($new) {
1158 $history->addLink($link);
1159 } else {
1160 $history->updateLink($link);
1161 }
1162
1163 // If we are called from the bookmarklet, we must close the popup:
1164 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1165 echo '<script>self.close();</script>';
1166 exit;
1167 }
1168
1169 $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?';
1170 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1171 // Scroll to the link which has been edited.
1172 $location .= '#' . $link['shorturl'];
1173 // After saving the link, redirect to the page the user was on.
1174 header('Location: '. $location);
1175 exit;
1176 }
1177
1178 // -------- User clicked the "Cancel" button when editing a link.
1179 if (isset($_POST['cancel_edit']))
1180 {
1181 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1182 if (! isset($LINKSDB[$id])) {
1183 header('Location: ?');
1184 }
1185 // If we are called from the bookmarklet, we must close the popup:
1186 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1187 $link = $LINKSDB[$id];
1188 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1189 // Scroll to the link which has been edited.
1190 $returnurl .= '#'. $link['shorturl'];
1191 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1192 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1193 exit;
1194 }
1195
1196 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1197 if ($targetPage == Router::$PAGE_DELETELINK)
1198 {
1199 if (! $sessionManager->checkToken($_GET['token'])) {
1200 die(t('Wrong token.'));
1201 }
1202
1203 $ids = trim($_GET['lf_linkdate']);
1204 if (strpos($ids, ' ') !== false) {
1205 // multiple, space-separated ids provided
1206 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1207 } else {
1208 // only a single id provided
1209 $ids = [$ids];
1210 }
1211 // assert at least one id is given
1212 if(!count($ids)){
1213 die('no id provided');
1214 }
1215 foreach ($ids as $id) {
1216 $id = (int) escape($id);
1217 $link = $LINKSDB[$id];
1218 $pluginManager->executeHooks('delete_link', $link);
1219 unset($LINKSDB[$id]);
1220 }
1221 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1222 $history->deleteLink($link);
1223
1224 // If we are called from the bookmarklet, we must close the popup:
1225 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
1226
1227 $location = '?';
1228 if (isset($_SERVER['HTTP_REFERER'])) {
1229 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1230 $location = generateLocation(
1231 $_SERVER['HTTP_REFERER'],
1232 $_SERVER['HTTP_HOST'],
1233 ['delete_link', 'edit_link', $link['shorturl']]
1234 );
1235 }
1236
1237 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1238 exit;
1239 }
1240
1241 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1242 if (isset($_GET['edit_link']))
1243 {
1244 $id = (int) escape($_GET['edit_link']);
1245 $link = $LINKSDB[$id]; // Read database
1246 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
1247 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
1248 $data = array(
1249 'link' => $link,
1250 'link_is_new' => false,
1251 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1252 'tags' => $LINKSDB->linksCountPerTag(),
1253 );
1254 $pluginManager->executeHooks('render_editlink', $data);
1255
1256 foreach ($data as $key => $value) {
1257 $PAGE->assign($key, $value);
1258 }
1259
1260 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1261 $PAGE->renderPage('editlink');
1262 exit;
1263 }
1264
1265 // -------- User want to post a new link: Display link edit form.
1266 if (isset($_GET['post'])) {
1267 $url = cleanup_url($_GET['post']);
1268
1269 $link_is_new = false;
1270 // Check if URL is not already in database (in this case, we will edit the existing link)
1271 $link = $LINKSDB->getLinkFromUrl($url);
1272 if (! $link)
1273 {
1274 $link_is_new = true;
1275 $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT));
1276 // Get title if it was provided in URL (by the bookmarklet).
1277 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1278 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1279 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1280 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1281 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1282 // If this is an HTTP(S) link, we try go get the page to extract the title (otherwise we will to straight to the edit form.)
1283 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1284 // Short timeout to keep the application responsive
1285 // The callback will fill $charset and $title with data from the downloaded page.
1286 get_http_response(
1287 $url,
1288 $conf->get('general.download_timeout', 30),
1289 $conf->get('general.download_max_size', 4194304),
1290 get_curl_download_callback($charset, $title)
1291 );
1292 if (! empty($title) && strtolower($charset) != 'utf-8') {
1293 $title = mb_convert_encoding($title, 'utf-8', $charset);
1294 }
1295 }
1296
1297 if ($url == '') {
1298 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1299 $title = $conf->get('general.default_note_title', t('Note: '));
1300 }
1301 $url = escape($url);
1302 $title = escape($title);
1303
1304 $link = array(
1305 'linkdate' => $linkdate,
1306 'title' => $title,
1307 'url' => $url,
1308 'description' => $description,
1309 'tags' => $tags,
1310 'private' => $private,
1311 );
1312 } else {
1313 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
1314 }
1315
1316 $data = array(
1317 'link' => $link,
1318 'link_is_new' => $link_is_new,
1319 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1320 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1321 'tags' => $LINKSDB->linksCountPerTag(),
1322 'default_private_links' => $conf->get('privacy.default_private_links', false),
1323 );
1324 $pluginManager->executeHooks('render_editlink', $data);
1325
1326 foreach ($data as $key => $value) {
1327 $PAGE->assign($key, $value);
1328 }
1329
1330 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1331 $PAGE->renderPage('editlink');
1332 exit;
1333 }
1334
1335 if ($targetPage == Router::$PAGE_EXPORT) {
1336 // Export links as a Netscape Bookmarks file
1337
1338 if (empty($_GET['selection'])) {
1339 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1340 $PAGE->renderPage('export');
1341 exit;
1342 }
1343
1344 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1345 $selection = $_GET['selection'];
1346 if (isset($_GET['prepend_note_url'])) {
1347 $prependNoteUrl = $_GET['prepend_note_url'];
1348 } else {
1349 $prependNoteUrl = false;
1350 }
1351
1352 try {
1353 $PAGE->assign(
1354 'links',
1355 NetscapeBookmarkUtils::filterAndFormat(
1356 $LINKSDB,
1357 $selection,
1358 $prependNoteUrl,
1359 index_url($_SERVER)
1360 )
1361 );
1362 } catch (Exception $exc) {
1363 header('Content-Type: text/plain; charset=utf-8');
1364 echo $exc->getMessage();
1365 exit;
1366 }
1367 $now = new DateTime();
1368 header('Content-Type: text/html; charset=utf-8');
1369 header(
1370 'Content-disposition: attachment; filename=bookmarks_'
1371 .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html'
1372 );
1373 $PAGE->assign('date', $now->format(DateTime::RFC822));
1374 $PAGE->assign('eol', PHP_EOL);
1375 $PAGE->assign('selection', $selection);
1376 $PAGE->renderPage('export.bookmarks');
1377 exit;
1378 }
1379
1380 if ($targetPage == Router::$PAGE_IMPORT) {
1381 // Upload a Netscape bookmark dump to import its contents
1382
1383 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1384 // Show import dialog
1385 $PAGE->assign(
1386 'maxfilesize',
1387 get_max_upload_size(
1388 ini_get('post_max_size'),
1389 ini_get('upload_max_filesize'),
1390 false
1391 )
1392 );
1393 $PAGE->assign(
1394 'maxfilesizeHuman',
1395 get_max_upload_size(
1396 ini_get('post_max_size'),
1397 ini_get('upload_max_filesize'),
1398 true
1399 )
1400 );
1401 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1402 $PAGE->renderPage('import');
1403 exit;
1404 }
1405
1406 // Import bookmarks from an uploaded file
1407 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1408 // The file is too big or some form field may be missing.
1409 $msg = sprintf(
1410 t(
1411 'The file you are trying to upload is probably bigger than what this webserver can accept'
1412 .' (%s). Please upload in smaller chunks.'
1413 ),
1414 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1415 );
1416 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router::$PAGE_IMPORT .'\';</script>';
1417 exit;
1418 }
1419 if (! $sessionManager->checkToken($_POST['token'])) {
1420 die('Wrong token.');
1421 }
1422 $status = NetscapeBookmarkUtils::import(
1423 $_POST,
1424 $_FILES,
1425 $LINKSDB,
1426 $conf,
1427 $history
1428 );
1429 echo '<script>alert("'.$status.'");document.location=\'?do='
1430 .Router::$PAGE_IMPORT .'\';</script>';
1431 exit;
1432 }
1433
1434 // Plugin administration page
1435 if ($targetPage == Router::$PAGE_PLUGINSADMIN) {
1436 $pluginMeta = $pluginManager->getPluginsMeta();
1437
1438 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1439 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; });
1440 // Load parameters.
1441 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1442 uasort(
1443 $enabledPlugins,
1444 function($a, $b) { return $a['order'] - $b['order']; }
1445 );
1446 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] === false; });
1447
1448 $PAGE->assign('enabledPlugins', $enabledPlugins);
1449 $PAGE->assign('disabledPlugins', $disabledPlugins);
1450 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
1451 $PAGE->renderPage('pluginsadmin');
1452 exit;
1453 }
1454
1455 // Plugin administration form action
1456 if ($targetPage == Router::$PAGE_SAVE_PLUGINSADMIN) {
1457 try {
1458 if (isset($_POST['parameters_form'])) {
1459 unset($_POST['parameters_form']);
1460 foreach ($_POST as $param => $value) {
1461 $conf->set('plugins.'. $param, escape($value));
1462 }
1463 }
1464 else {
1465 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1466 }
1467 $conf->write($loginManager->isLoggedIn());
1468 $history->updateSettings();
1469 }
1470 catch (Exception $e) {
1471 error_log(
1472 'ERROR while saving plugin configuration:.' . PHP_EOL .
1473 $e->getMessage()
1474 );
1475
1476 // TODO: do not handle exceptions/errors in JS.
1477 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router::$PAGE_PLUGINSADMIN .'\';</script>';
1478 exit;
1479 }
1480 header('Location: ?do='. Router::$PAGE_PLUGINSADMIN);
1481 exit;
1482 }
1483
1484 // Get a fresh token
1485 if ($targetPage == Router::$GET_TOKEN) {
1486 header('Content-Type:text/plain');
1487 echo $sessionManager->generateToken($conf);
1488 exit;
1489 }
1490
1491 // -------- Otherwise, simply display search form and links:
1492 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
1493 exit;
1494 }
1495
1496 /**
1497 * Template for the list of links (<div id="linklist">)
1498 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1499 *
1500 * @param pageBuilder $PAGE pageBuilder instance.
1501 * @param LinkDB $LINKSDB LinkDB instance.
1502 * @param ConfigManager $conf Configuration Manager instance.
1503 * @param PluginManager $pluginManager Plugin Manager instance.
1504 * @param LoginManager $loginManager LoginManager instance
1505 */
1506 function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
1507 {
1508 // Used in templates
1509 if (isset($_GET['searchtags'])) {
1510 if (! empty($_GET['searchtags'])) {
1511 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1512 } else {
1513 $searchtags = false;
1514 }
1515 } else {
1516 $searchtags = '';
1517 }
1518 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1519
1520 // Smallhash filter
1521 if (! empty($_SERVER['QUERY_STRING'])
1522 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1523 try {
1524 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1525 } catch (LinkNotFoundException $e) {
1526 $PAGE->render404($e->getMessage());
1527 exit;
1528 }
1529 } else {
1530 // Filter links according search parameters.
1531 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
1532 $request = [
1533 'searchtags' => $searchtags,
1534 'searchterm' => $searchterm,
1535 ];
1536 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
1537 }
1538
1539 // ---- Handle paging.
1540 $keys = array();
1541 foreach ($linksToDisplay as $key => $value) {
1542 $keys[] = $key;
1543 }
1544
1545 // Select articles according to paging.
1546 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1547 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1548 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1549 $page = $page < 1 ? 1 : $page;
1550 $page = $page > $pagecount ? $pagecount : $page;
1551 // Start index.
1552 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1553 $end = $i + $_SESSION['LINKS_PER_PAGE'];
1554 $linkDisp = array();
1555 while ($i<$end && $i<count($keys))
1556 {
1557 $link = $linksToDisplay[$keys[$i]];
1558 $link['description'] = format_description(
1559 $link['description'],
1560 $conf->get('redirector.url'),
1561 $conf->get('redirector.encode_url')
1562 );
1563 $classLi = ($i % 2) != 0 ? '' : 'publicLinkHightLight';
1564 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
1565 $link['timestamp'] = $link['created']->getTimestamp();
1566 if (! empty($link['updated'])) {
1567 $link['updated_timestamp'] = $link['updated']->getTimestamp();
1568 } else {
1569 $link['updated_timestamp'] = '';
1570 }
1571 $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY);
1572 uasort($taglist, 'strcasecmp');
1573 $link['taglist'] = $taglist;
1574 // Check for both signs of a note: starting with ? and 7 chars long.
1575 if ($link['url'][0] === '?' &&
1576 strlen($link['url']) === 7) {
1577 $link['url'] = index_url($_SERVER) . $link['url'];
1578 }
1579
1580 $linkDisp[$keys[$i]] = $link;
1581 $i++;
1582 }
1583
1584 // Compute paging navigation
1585 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
1586 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1587 $previous_page_url = '';
1588 if ($i != count($keys)) {
1589 $previous_page_url = '?page=' . ($page+1) . $searchtermUrl . $searchtagsUrl;
1590 }
1591 $next_page_url='';
1592 if ($page>1) {
1593 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1594 }
1595
1596 // Fill all template fields.
1597 $data = array(
1598 'previous_page_url' => $previous_page_url,
1599 'next_page_url' => $next_page_url,
1600 'page_current' => $page,
1601 'page_max' => $pagecount,
1602 'result_count' => count($linksToDisplay),
1603 'search_term' => $searchterm,
1604 'search_tags' => $searchtags,
1605 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
1606 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
1607 'links' => $linkDisp,
1608 );
1609
1610 // If there is only a single link, we change on-the-fly the title of the page.
1611 if (count($linksToDisplay) == 1) {
1612 $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
1613 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1614 $data['pagetitle'] = t('Search: ');
1615 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1616 $bracketWrap = function ($tag) {
1617 return '['. $tag .']';
1618 };
1619 $data['pagetitle'] .= ! empty($searchtags)
1620 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1621 : '';
1622 $data['pagetitle'] .= '- '. $conf->get('general.title');
1623 }
1624
1625 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
1626
1627 foreach ($data as $key => $value) {
1628 $PAGE->assign($key, $value);
1629 }
1630
1631 return;
1632 }
1633
1634 /**
1635 * Compute the thumbnail for a link.
1636 *
1637 * With a link to the original URL.
1638 * Understands various services (youtube.com...)
1639 * Input: $url = URL for which the thumbnail must be found.
1640 * $href = if provided, this URL will be followed instead of $url
1641 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1642 * Some of them may be missing.
1643 * Return an empty array if no thumbnail available.
1644 *
1645 * @param ConfigManager $conf Configuration Manager instance.
1646 * @param string $url
1647 * @param string|bool $href
1648 *
1649 * @return array
1650 */
1651 function computeThumbnail($conf, $url, $href = false)
1652 {
1653 if (!$conf->get('thumbnail.enable_thumbnails')) return array();
1654 if ($href==false) $href=$url;
1655
1656 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
1657 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
1658 // ^^^^^^^^^^^ ^^^^^^^^^^^
1659 $domain = parse_url($url,PHP_URL_HOST);
1660 if ($domain=='youtube.com' || $domain=='www.youtube.com')
1661 {
1662 parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract video ID and get thumbnail
1663 if (!empty($params['v'])) return array('src'=>'https://img.youtube.com/vi/'.$params['v'].'/default.jpg',
1664 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1665 }
1666 if ($domain=='youtu.be') // Youtube short links
1667 {
1668 $path = parse_url($url,PHP_URL_PATH);
1669 return array('src'=>'https://img.youtube.com/vi'.$path.'/default.jpg',
1670 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1671 }
1672 if ($domain=='pix.toile-libre.org') // pix.toile-libre.org image hosting
1673 {
1674 parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract image filename.
1675 if (!empty($params) && !empty($params['img'])) return array('src'=>'http://pix.toile-libre.org/upload/thumb/'.urlencode($params['img']),
1676 'href'=>$href,'style'=>'max-width:120px; max-height:150px','alt'=>'pix.toile-libre.org thumbnail');
1677 }
1678
1679 if ($domain=='imgur.com')
1680 {
1681 $path = parse_url($url,PHP_URL_PATH);
1682 if (startsWith($path,'/a/')) return array(); // Thumbnails for albums are not available.
1683 if (startsWith($path,'/r/')) return array('src'=>'https://i.imgur.com/'.basename($path).'s.jpg',
1684 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1685 if (startsWith($path,'/gallery/')) return array('src'=>'https://i.imgur.com'.substr($path,8).'s.jpg',
1686 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1687
1688 if (substr_count($path,'/')==1) return array('src'=>'https://i.imgur.com/'.substr($path,1).'s.jpg',
1689 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1690 }
1691 if ($domain=='i.imgur.com')
1692 {
1693 $pi = pathinfo(parse_url($url,PHP_URL_PATH));
1694 if (!empty($pi['filename'])) return array('src'=>'https://i.imgur.com/'.$pi['filename'].'s.jpg',
1695 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1696 }
1697 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
1698 {
1699 if (strpos($url,'dailymotion.com/video/')!==false)
1700 {
1701 $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
1702 return array('src'=>$thumburl,
1703 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'DailyMotion thumbnail');
1704 }
1705 }
1706 if (endsWith($domain,'.imageshack.us'))
1707 {
1708 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1709 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1710 {
1711 $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
1712 return array('src'=>$thumburl,
1713 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'imageshack.us thumbnail');
1714 }
1715 }
1716
1717 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1718 // So we deport the thumbnail generation in order not to slow down page generation
1719 // (and we also cache the thumbnail)
1720
1721 if (! $conf->get('thumbnail.enable_localcache')) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
1722
1723 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
1724 || $domain=='vimeo.com'
1725 || $domain=='ted.com' || endsWith($domain,'.ted.com')
1726 || $domain=='xkcd.com' || endsWith($domain,'.xkcd.com')
1727 )
1728 {
1729 if ($domain=='vimeo.com')
1730 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
1731 $path = parse_url($url,PHP_URL_PATH);
1732 if (!preg_match('!/\d+.+?!',$path)) return array(); // This is not a single video URL.
1733 }
1734 if ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
1735 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
1736 $path = parse_url($url,PHP_URL_PATH);
1737 if (!preg_match('!/\d+.+?!',$path)) return array();
1738 }
1739 if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
1740 { // Make sure this TED URL points to a video (/talks/...)
1741 $path = parse_url($url,PHP_URL_PATH);
1742 if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
1743 }
1744 $sign = hash_hmac('sha256', $url, $conf->get('credentials.salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
1745 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1746 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1747 }
1748
1749 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1750 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1751 // But using the extension will do.
1752 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1753 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1754 {
1755 $sign = hash_hmac('sha256', $url, $conf->get('credentials.salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
1756 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
1757 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1758 }
1759 return array(); // No thumbnail.
1760
1761 }
1762
1763
1764 // Returns the HTML code to display a thumbnail for a link
1765 // with a link to the original URL.
1766 // Understands various services (youtube.com...)
1767 // Input: $url = URL for which the thumbnail must be found.
1768 // $href = if provided, this URL will be followed instead of $url
1769 // Returns '' if no thumbnail available.
1770 function thumbnail($url,$href=false)
1771 {
1772 // FIXME!
1773 global $conf;
1774 $t = computeThumbnail($conf, $url,$href);
1775 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1776
1777 $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"';
1778 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1779 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1780 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1781 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1782 $html.='></a>';
1783 return $html;
1784 }
1785
1786 // Returns the HTML code to display a thumbnail for a link
1787 // for the picture wall (using lazy image loading)
1788 // Understands various services (youtube.com...)
1789 // Input: $url = URL for which the thumbnail must be found.
1790 // $href = if provided, this URL will be followed instead of $url
1791 // Returns '' if no thumbnail available.
1792 function lazyThumbnail($conf, $url,$href=false)
1793 {
1794 // FIXME!
1795 global $conf;
1796 $t = computeThumbnail($conf, $url,$href);
1797 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1798
1799 $html='<a href="'.escape($t['href']).'">';
1800
1801 // Lazy image
1802 $html.='<img class="b-lazy" src="#" data-src="'.escape($t['src']).'"';
1803
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.='>';
1809
1810 // No-JavaScript fallback.
1811 $html.='<noscript><img src="'.escape($t['src']).'"';
1812 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1813 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1814 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1815 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
1816 $html.='></noscript></a>';
1817
1818 return $html;
1819 }
1820
1821
1822 /**
1823 * Installation
1824 * This function should NEVER be called if the file data/config.php exists.
1825 *
1826 * @param ConfigManager $conf Configuration Manager instance.
1827 * @param SessionManager $sessionManager SessionManager instance
1828 */
1829 function install($conf, $sessionManager) {
1830 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1831 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1832
1833
1834 // This part makes sure sessions works correctly.
1835 // (Because on some hosts, session.save_path may not be set correctly,
1836 // or we may not have write access to it.)
1837 if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working'))
1838 {
1839 // Step 2: Check if data in session is correct.
1840 $msg = t(
1841 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1842 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1843 'and that you have write access to it.<br>'.
1844 'It currently points to %s.<br>'.
1845 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1846 'or any custom hostname without a dot causes cookie storage to fail. '.
1847 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1848 );
1849 $msg = sprintf($msg, session_save_path());
1850 echo $msg;
1851 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1852 die;
1853 }
1854 if (!isset($_SESSION['session_tested']))
1855 { // Step 1 : Try to store data in session and reload page.
1856 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1857 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1858 }
1859 if (isset($_GET['test_session']))
1860 { // Step 3: Sessions are OK. Remove test parameter from URL.
1861 header('Location: '.index_url($_SERVER));
1862 }
1863
1864
1865 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1866 {
1867 $tz = 'UTC';
1868 if (!empty($_POST['continent']) && !empty($_POST['city'])
1869 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1870 ) {
1871 $tz = $_POST['continent'].'/'.$_POST['city'];
1872 }
1873 $conf->set('general.timezone', $tz);
1874 $login = $_POST['setlogin'];
1875 $conf->set('credentials.login', $login);
1876 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1877 $conf->set('credentials.salt', $salt);
1878 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
1879 if (!empty($_POST['title'])) {
1880 $conf->set('general.title', escape($_POST['title']));
1881 } else {
1882 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
1883 }
1884 $conf->set('translation.language', escape($_POST['language']));
1885 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1886 $conf->set('api.enabled', !empty($_POST['enableApi']));
1887 $conf->set(
1888 'api.secret',
1889 generate_api_secret(
1890 $conf->get('credentials.login'),
1891 $conf->get('credentials.salt')
1892 )
1893 );
1894 try {
1895 // Everything is ok, let's create config file.
1896 $conf->write($loginManager->isLoggedIn());
1897 }
1898 catch(Exception $e) {
1899 error_log(
1900 'ERROR while writing config file after installation.' . PHP_EOL .
1901 $e->getMessage()
1902 );
1903
1904 // TODO: do not handle exceptions/errors in JS.
1905 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1906 exit;
1907 }
1908 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
1909 exit;
1910 }
1911
1912 $PAGE = new PageBuilder($conf, null, $sessionManager->generateToken());
1913 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1914 $PAGE->assign('continents', $continents);
1915 $PAGE->assign('cities', $cities);
1916 $PAGE->assign('languages', Languages::getAvailableLanguages());
1917 $PAGE->renderPage('install');
1918 exit;
1919 }
1920
1921 /**
1922 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
1923 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1924 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
1925 * This function is called by passing the URL:
1926 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1927 * [URL] is the URL of the link (e.g. a flickr page)
1928 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1929 * The function below will fetch the image from the webservice and store it in the cache.
1930 *
1931 * @param ConfigManager $conf Configuration Manager instance,
1932 */
1933 function genThumbnail($conf)
1934 {
1935 // Make sure the parameters in the URL were generated by us.
1936 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt'));
1937 if ($sign!=$_GET['hmac']) die('Naughty boy!');
1938
1939 $cacheDir = $conf->get('resource.thumbnails_cache', 'cache');
1940 // Let's see if we don't already have the image for this URL in the cache.
1941 $thumbname=hash('sha1',$_GET['url']).'.jpg';
1942 if (is_file($cacheDir .'/'. $thumbname))
1943 { // We have the thumbnail, just serve it:
1944 header('Content-Type: image/jpeg');
1945 echo file_get_contents($cacheDir .'/'. $thumbname);
1946 return;
1947 }
1948 // We may also serve a blank image (if service did not respond)
1949 $blankname=hash('sha1',$_GET['url']).'.gif';
1950 if (is_file($cacheDir .'/'. $blankname))
1951 {
1952 header('Content-Type: image/gif');
1953 echo file_get_contents($cacheDir .'/'. $blankname);
1954 return;
1955 }
1956
1957 // Otherwise, generate the thumbnail.
1958 $url = $_GET['url'];
1959 $domain = parse_url($url,PHP_URL_HOST);
1960
1961 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
1962 {
1963 // Crude replacement to handle new flickr domain policy (They prefer www. now)
1964 $url = str_replace('http://flickr.com/','http://www.flickr.com/',$url);
1965
1966 // Is this a link to an image, or to a flickr page ?
1967 $imageurl='';
1968 if (endsWith(parse_url($url, PHP_URL_PATH), '.jpg'))
1969 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
1970 preg_match('!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
1971 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
1972 }
1973 else // This is a flickr page (html)
1974 {
1975 // Get the flickr html page.
1976 list($headers, $content) = get_http_response($url, 20);
1977 if (strpos($headers[0], '200 OK') !== false)
1978 {
1979 // flickr now nicely provides the URL of the thumbnail in each flickr page.
1980 preg_match('!<link rel=\"image_src\" href=\"(.+?)\"!', $content, $matches);
1981 if (!empty($matches[1])) $imageurl=$matches[1];
1982
1983 // In albums (and some other pages), the link rel="image_src" is not provided,
1984 // but flickr provides:
1985 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
1986 if ($imageurl=='')
1987 {
1988 preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!', $content, $matches);
1989 if (!empty($matches[1])) $imageurl=$matches[1];
1990 }
1991 }
1992 }
1993
1994 if ($imageurl!='')
1995 { // Let's download the image.
1996 // Image is 240x120, so 10 seconds to download should be enough.
1997 list($headers, $content) = get_http_response($imageurl, 10);
1998 if (strpos($headers[0], '200 OK') !== false) {
1999 // Save image to cache.
2000 file_put_contents($cacheDir .'/'. $thumbname, $content);
2001 header('Content-Type: image/jpeg');
2002 echo $content;
2003 return;
2004 }
2005 }
2006 }
2007
2008 elseif ($domain=='vimeo.com' )
2009 {
2010 // This is more complex: we have to perform a HTTP request, then parse the result.
2011 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
2012 $vid = substr(parse_url($url,PHP_URL_PATH),1);
2013 list($headers, $content) = get_http_response('https://vimeo.com/api/v2/video/'.escape($vid).'.php', 5);
2014 if (strpos($headers[0], '200 OK') !== false) {
2015 $t = unserialize($content);
2016 $imageurl = $t[0]['thumbnail_medium'];
2017 // Then we download the image and serve it to our client.
2018 list($headers, $content) = get_http_response($imageurl, 10);
2019 if (strpos($headers[0], '200 OK') !== false) {
2020 // Save image to cache.
2021 file_put_contents($cacheDir .'/'. $thumbname, $content);
2022 header('Content-Type: image/jpeg');
2023 echo $content;
2024 return;
2025 }
2026 }
2027 }
2028
2029 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
2030 {
2031 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2032 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2033 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
2034 list($headers, $content) = get_http_response($url, 5);
2035 if (strpos($headers[0], '200 OK') !== false) {
2036 // Extract the link to the thumbnail
2037 preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!', $content, $matches);
2038 if (!empty($matches[1]))
2039 { // Let's download the image.
2040 $imageurl=$matches[1];
2041 // No control on image size, so wait long enough
2042 list($headers, $content) = get_http_response($imageurl, 20);
2043 if (strpos($headers[0], '200 OK') !== false) {
2044 $filepath = $cacheDir .'/'. $thumbname;
2045 file_put_contents($filepath, $content); // Save image to cache.
2046 if (resizeImage($filepath))
2047 {
2048 header('Content-Type: image/jpeg');
2049 echo file_get_contents($filepath);
2050 return;
2051 }
2052 }
2053 }
2054 }
2055 }
2056
2057 elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
2058 {
2059 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2060 // http://xkcd.com/327/
2061 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
2062 list($headers, $content) = get_http_response($url, 5);
2063 if (strpos($headers[0], '200 OK') !== false) {
2064 // Extract the link to the thumbnail
2065 preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!', $content, $matches);
2066 if (!empty($matches[1]))
2067 { // Let's download the image.
2068 $imageurl=$matches[1];
2069 // No control on image size, so wait long enough
2070 list($headers, $content) = get_http_response($imageurl, 20);
2071 if (strpos($headers[0], '200 OK') !== false) {
2072 $filepath = $cacheDir.'/'.$thumbname;
2073 // Save image to cache.
2074 file_put_contents($filepath, $content);
2075 if (resizeImage($filepath))
2076 {
2077 header('Content-Type: image/jpeg');
2078 echo file_get_contents($filepath);
2079 return;
2080 }
2081 }
2082 }
2083 }
2084 }
2085
2086 else
2087 {
2088 // For all other domains, we try to download the image and make a thumbnail.
2089 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
2090 list($headers, $content) = get_http_response($url, 30);
2091 if (strpos($headers[0], '200 OK') !== false) {
2092 $filepath = $cacheDir .'/'.$thumbname;
2093 // Save image to cache.
2094 file_put_contents($filepath, $content);
2095 if (resizeImage($filepath))
2096 {
2097 header('Content-Type: image/jpeg');
2098 echo file_get_contents($filepath);
2099 return;
2100 }
2101 }
2102 }
2103
2104
2105 // Otherwise, return an empty image (8x8 transparent gif)
2106 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
2107 // Also put something in cache so that this URL is not requested twice.
2108 file_put_contents($cacheDir .'/'. $blankname, $blankgif);
2109 header('Content-Type: image/gif');
2110 echo $blankgif;
2111 }
2112
2113 // Make a thumbnail of the image (to width: 120 pixels)
2114 // Returns true if success, false otherwise.
2115 function resizeImage($filepath)
2116 {
2117 if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
2118
2119 // Trick: some stupid people rename GIF as JPEG... or else.
2120 // So we really try to open each image type whatever the extension is.
2121 $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
2122 $im=false;
2123 $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
2124 $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
2125 $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
2126 if (!$im) return false; // Unable to open image (corrupted or not an image)
2127 $w = imagesx($im);
2128 $h = imagesy($im);
2129 $ystart = 0; $yheight=$h;
2130 if ($h>$w) { $ystart= ($h/2)-($w/2); $yheight=$w/2; }
2131 $nw = 120; // Desired width
2132 $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
2133 // Resize image:
2134 $im2 = imagecreatetruecolor($nw,$nh);
2135 imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
2136 imageinterlace($im2,true); // For progressive JPEG.
2137 $tempname=$filepath.'_TEMP.jpg';
2138 imagejpeg($im2, $tempname, 90);
2139 imagedestroy($im);
2140 imagedestroy($im2);
2141 unlink($filepath);
2142 rename($tempname,$filepath); // Overwrite original picture with thumbnail.
2143 return true;
2144 }
2145
2146 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf); exit; } // Thumbnail generation/cache does not need the link database.
2147 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf); exit; }
2148 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
2149 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
2150 }
2151
2152 try {
2153 $history = new History($conf->get('resource.history'));
2154 } catch(Exception $e) {
2155 die($e->getMessage());
2156 }
2157
2158 $linkDb = new LinkDB(
2159 $conf->get('resource.datastore'),
2160 $loginManager->isLoggedIn(),
2161 $conf->get('privacy.hide_public_links'),
2162 $conf->get('redirector.url'),
2163 $conf->get('redirector.encode_url')
2164 );
2165
2166 $container = new \Slim\Container();
2167 $container['conf'] = $conf;
2168 $container['plugins'] = $pluginManager;
2169 $container['history'] = $history;
2170 $app = new \Slim\App($container);
2171
2172 // REST API routes
2173 $app->group('/api/v1', function() {
2174 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
2175 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
2176 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
2177 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
2178 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
2179 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
2180 $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
2181 })->add('\Shaarli\Api\ApiMiddleware');
2182
2183 $response = $app->run(true);
2184 // Hack to make Slim and Shaarli router work together:
2185 // If a Slim route isn't found and NOT API call, we call renderPage().
2186 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
2187 // We use UTF-8 for proper international characters handling.
2188 header('Content-Type: text/html; charset=utf-8');
2189 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
2190 } else {
2191 $app->respond($response);
2192 }