]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
Refactor SessionManager::$INACTIVITY_TIMEOUT
[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\LoginManager;
82 use \Shaarli\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 $loginManager = new LoginManager($GLOBALS, $conf);
125 $sessionManager = new SessionManager($_SESSION, $conf);
126
127 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
128 if (! defined('LC_MESSAGES')) {
129 define('LC_MESSAGES', LC_COLLATE);
130 }
131
132 // Sniff browser language and set date format accordingly.
133 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
134 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
135 }
136
137 new Languages(setlocale(LC_MESSAGES, 0), $conf);
138
139 $conf->setEmpty('general.timezone', date_default_timezone_get());
140 $conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
141 RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
142 RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
143
144 $pluginManager = new PluginManager($conf);
145 $pluginManager->load($conf->get('general.enabled_plugins'));
146
147 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
148
149 ob_start(); // Output buffering for the page cache.
150
151 // Prevent caching on client side or proxy: (yes, it's ugly)
152 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
153 header("Cache-Control: no-store, no-cache, must-revalidate");
154 header("Cache-Control: post-check=0, pre-check=0", false);
155 header("Pragma: no-cache");
156
157 if (! is_file($conf->getConfigFileExt())) {
158 // Ensure Shaarli has proper access to its resources
159 $errors = ApplicationUtils::checkResourcePermissions($conf);
160
161 if ($errors != array()) {
162 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
163
164 foreach ($errors as $error) {
165 $message .= '<li>'.$error.'</li>';
166 }
167 $message .= '</ul>';
168
169 header('Content-Type: text/html; charset=utf-8');
170 echo $message;
171 exit;
172 }
173
174 // Display the installation form if no existing config is found
175 install($conf, $sessionManager);
176 }
177
178 // a token depending of deployment salt, user password, and the current ip
179 define('STAY_SIGNED_IN_TOKEN', sha1($conf->get('credentials.hash') . $_SERVER['REMOTE_ADDR'] . $conf->get('credentials.salt')));
180
181 /**
182 * Checking session state (i.e. is the user still logged in)
183 *
184 * @param ConfigManager $conf Configuration Manager instance.
185 * @param SessionManager $sessionManager SessionManager instance
186 *
187 * @return bool true if the user is logged in, false otherwise.
188 */
189 function setup_login_state($conf, $sessionManager)
190 {
191 if ($conf->get('security.open_shaarli')) {
192 return true;
193 }
194 $userIsLoggedIn = false; // By default, we do not consider the user as logged in;
195 $loginFailure = false; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
196 if (! $conf->exists('credentials.login')) {
197 $userIsLoggedIn = false; // Shaarli is not configured yet.
198 $loginFailure = true;
199 }
200 if (isset($_COOKIE['shaarli_staySignedIn']) &&
201 $_COOKIE['shaarli_staySignedIn']===STAY_SIGNED_IN_TOKEN &&
202 !$loginFailure)
203 {
204 fillSessionInfo($conf, $sessionManager);
205 $userIsLoggedIn = true;
206 }
207 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
208 if (empty($_SESSION['uid'])
209 || ($conf->get('security.session_protection_disabled') === false && $_SESSION['ip'] != client_ip_id($_SERVER))
210 || time() >= $_SESSION['expires_on'])
211 {
212 logout();
213 $userIsLoggedIn = false;
214 $loginFailure = true;
215 }
216 if (!empty($_SESSION['longlastingsession'])) {
217 $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // In case of "Stay signed in" checked.
218 } else {
219 $_SESSION['expires_on'] = time() + $sessionManager::$INACTIVITY_TIMEOUT;
220 }
221 if (!$loginFailure) {
222 $userIsLoggedIn = true;
223 }
224
225 return $userIsLoggedIn;
226 }
227
228 $userIsLoggedIn = setup_login_state($conf, $sessionManager);
229
230 // ------------------------------------------------------------------------------------------
231 // Session management
232
233 /**
234 * Load user session
235 *
236 * @param ConfigManager $conf Configuration Manager instance.
237 * @param SessionManager $sessionManager SessionManager instance
238 */
239 function fillSessionInfo($conf, $sessionManager)
240 {
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() + $sessionManager::$INACTIVITY_TIMEOUT;
245 }
246
247 /**
248 * Check that user/password is correct.
249 *
250 * @param string $login Username
251 * @param string $password User password
252 * @param ConfigManager $conf Configuration Manager instance.
253 * @param SessionManager $sessionManager SessionManager instance
254 *
255 * @return bool: authentication successful or not.
256 */
257 function check_auth($login, $password, $conf, $sessionManager)
258 {
259 $hash = sha1($password . $login . $conf->get('credentials.salt'));
260 if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash')) {
261 // Login/password is correct.
262 fillSessionInfo($conf, $sessionManager);
263 logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login successful');
264 return true;
265 }
266 logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login);
267 return false;
268 }
269
270 // Returns true if the user is logged in.
271 function isLoggedIn()
272 {
273 global $userIsLoggedIn;
274 return $userIsLoggedIn;
275 }
276
277 // Force logout.
278 function logout() {
279 if (isset($_SESSION)) {
280 unset($_SESSION['uid']);
281 unset($_SESSION['ip']);
282 unset($_SESSION['username']);
283 unset($_SESSION['visibility']);
284 unset($_SESSION['untaggedonly']);
285 }
286 setcookie('shaarli_staySignedIn', FALSE, 0, WEB_PATH);
287 }
288
289 // ------------------------------------------------------------------------------------------
290 // Process login form: Check if login/password is correct.
291 if (isset($_POST['login'])) {
292 if (! $loginManager->canLogin($_SERVER)) {
293 die(t('I said: NO. You are banned for the moment. Go away.'));
294 }
295 if (isset($_POST['password'])
296 && $sessionManager->checkToken($_POST['token'])
297 && (check_auth($_POST['login'], $_POST['password'], $conf, $sessionManager))
298 ) {
299 // Login/password is OK.
300 $loginManager->handleSuccessfulLogin($_SERVER);
301
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.
308
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.
313 }
314 else // Standard session expiration (=when browser closes)
315 {
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);
319 }
320
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]);
327 }
328 }
329 header('Location: '. $uri);
330 exit;
331 }
332
333 if (isset($_GET['edit_link'])) {
334 header('Location: ?edit_link='. escape($_GET['edit_link']));
335 exit;
336 }
337
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']));
342 exit;
343 }
344 }
345 header('Location: ?'); exit;
346 } else {
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]);
354 }
355 }
356 }
357 // Redirect to login screen.
358 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
359 exit;
360 }
361 }
362
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.
367
368 /**
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.
372 *
373 * @param ConfigManager $conf Configuration Manager instance.
374 */
375 function showDailyRSS($conf) {
376 // Cache system
377 $query = $_SERVER['QUERY_STRING'];
378 $cache = new CachedPage(
379 $conf->get('config.PAGE_CACHE'),
380 page_url($_SERVER),
381 startsWith($query,'do=dailyrss') && !isLoggedIn()
382 );
383 $cached = $cache->cachedVersion();
384 if (!empty($cached)) {
385 echo $cached;
386 exit;
387 }
388
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'),
393 isLoggedIn(),
394 $conf->get('privacy.hide_public_links'),
395 $conf->get('redirector.url'),
396 $conf->get('redirector.encode_url')
397 );
398
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).
401 */
402 $nb_of_days = 7; // We take 7 days.
403 $today = date('Ymd');
404 $days = array();
405
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();
411 }
412 $days[$day][] = $link;
413 }
414
415 if (count($days) > $nb_of_days) {
416 break; // Have we collected enough days?
417 }
418 }
419
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">';
424 echo '<channel>';
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;
430
431 // For each day.
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.
435
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')
442 );
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
447 }
448 }
449
450 // Then build the HTML for this day:
451 $tpl = new RainTPL;
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);
459
460 echo $html . PHP_EOL;
461 }
462 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
463
464 $cache->cache(ob_get_contents());
465 ob_end_flush();
466 exit;
467 }
468
469 /**
470 * Show the 'Daily' page.
471 *
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.
476 */
477 function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager)
478 {
479 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
480 if (isset($_GET['day'])) {
481 $day = $_GET['day'];
482 }
483
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;
489 $day = $days[$i];
490 }
491 $previousday = '';
492 $nextday = '';
493
494 if ($i !== false) {
495 if ($i >= 1) {
496 $previousday=$days[$i - 1];
497 }
498 if ($i < count($days) - 1) {
499 $nextday = $days[$i + 1];
500 }
501 }
502 try {
503 $linksToDisplay = $LINKSDB->filterDay($day);
504 } catch (Exception $exc) {
505 error_log($exc);
506 $linksToDisplay = array();
507 }
508
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')
518 );
519 $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
520 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
521 }
522
523 $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
524 $data = array(
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,
531 );
532
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()));
536
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.
541 */
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.
552 }
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;
558 }
559
560 $data['cols'] = $columns;
561
562 foreach ($data as $key => $value) {
563 $pageBuilder->assign($key, $value);
564 }
565
566 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
567 $pageBuilder->renderPage('daily');
568 exit;
569 }
570
571 /**
572 * Renders the linklist
573 *
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.
578 */
579 function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager) {
580 buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager); // Compute list of links to display
581 $PAGE->renderPage('linklist');
582 }
583
584 /**
585 * Render HTML page (according to URL parameters and user rights)
586 *
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
593 */
594 function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
595 {
596 $updater = new Updater(
597 read_updates_file($conf->get('resource.updates')),
598 $LINKSDB,
599 $conf,
600 isLoggedIn()
601 );
602 try {
603 $newUpdates = $updater->update();
604 if (! empty($newUpdates)) {
605 write_updates_file(
606 $conf->get('resource.updates'),
607 $updater->getDoneUpdates()
608 );
609 }
610 }
611 catch(Exception $e) {
612 die($e->getMessage());
613 }
614
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());
619
620 // Determine which page will be rendered.
621 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
622 $targetPage = Router::findPage($query, $_GET, isLoggedIn());
623
624 if (
625 // if the user isn't logged in
626 !isLoggedIn() &&
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
636 ) {
637 // force current page to be the login page
638 $targetPage = Router::$PAGE_LOGIN;
639 }
640
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(
644 'includes',
645 'header',
646 'footer',
647 );
648
649 foreach($common_hooks as $name) {
650 $plugin_data = array();
651 $pluginManager->executeHooks('render_' . $name, $plugin_data,
652 array(
653 'target' => $targetPage,
654 'loggedin' => isLoggedIn()
655 )
656 );
657 $PAGE->assign('plugins_' . $name, $plugin_data);
658 }
659
660 // -------- Display login form.
661 if ($targetPage == Router::$PAGE_LOGIN)
662 {
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']));
666 }
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');
673 exit;
674 }
675 // -------- User wants to logout.
676 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
677 {
678 invalidateCaches($conf->get('resource.page_cache'));
679 logout();
680 header('Location: ?');
681 exit;
682 }
683
684 // -------- Picture wall
685 if ($targetPage == Router::$PAGE_PICWALL)
686 {
687 // Optionally filter the results:
688 $links = $LINKSDB->filterSearch($_GET);
689 $linksToDisplay = array();
690
691 // Get only links which have a thumbnail.
692 foreach($links as $link)
693 {
694 $permalink='?'.$link['shorturl'];
695 $thumb=lazyThumbnail($conf, $link['url'],$permalink);
696 if ($thumb!='') // Only output links which have a thumbnail.
697 {
698 $link['thumbnail']=$thumb; // Thumbnail HTML code.
699 $linksToDisplay[]=$link; // Add to array.
700 }
701 }
702
703 $data = array(
704 'linksToDisplay' => $linksToDisplay,
705 );
706 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => isLoggedIn()));
707
708 foreach ($data as $key => $value) {
709 $PAGE->assign($key, $value);
710 }
711
712 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
713 $PAGE->renderPage('picwall');
714 exit;
715 }
716
717 // -------- Tag cloud
718 if ($targetPage == Router::$PAGE_TAGCLOUD)
719 {
720 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
721 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
722 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
723
724 // We sort tags alphabetically, then choose a font size according to count.
725 // First, find max value.
726 $maxcount = 0;
727 foreach ($tags as $value) {
728 $maxcount = max($maxcount, $value);
729 }
730
731 alphabetical_sort($tags, false, true);
732
733 $tagList = array();
734 foreach($tags as $key => $value) {
735 if (in_array($key, $filteringTags)) {
736 continue;
737 }
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(
743 'count' => $value,
744 'size' => number_format($size, 2, '.', ''),
745 );
746 }
747
748 $searchTags = implode(' ', escape($filteringTags));
749 $data = array(
750 'search_tags' => $searchTags,
751 'tags' => $tagList,
752 );
753 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => isLoggedIn()));
754
755 foreach ($data as $key => $value) {
756 $PAGE->assign($key, $value);
757 }
758
759 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
760 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
761 $PAGE->renderPage('tag.cloud');
762 exit;
763 }
764
765 // -------- Tag list
766 if ($targetPage == Router::$PAGE_TAGLIST)
767 {
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)) {
773 unset($tags[$tag]);
774 }
775 }
776
777 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
778 alphabetical_sort($tags, false, true);
779 }
780
781 $searchTags = implode(' ', escape($filteringTags));
782 $data = [
783 'search_tags' => $searchTags,
784 'tags' => $tags,
785 ];
786 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => isLoggedIn()]);
787
788 foreach ($data as $key => $value) {
789 $PAGE->assign($key, $value);
790 }
791
792 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
793 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
794 $PAGE->renderPage('tag.list');
795 exit;
796 }
797
798 // Daily page.
799 if ($targetPage == Router::$PAGE_DAILY) {
800 showDaily($PAGE, $LINKSDB, $conf, $pluginManager);
801 }
802
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');
807
808 // Cache system
809 $query = $_SERVER['QUERY_STRING'];
810 $cache = new CachedPage(
811 $conf->get('resource.page_cache'),
812 page_url($_SERVER),
813 startsWith($query,'do='. $targetPage) && !isLoggedIn()
814 );
815 $cached = $cache->cachedVersion();
816 if (!empty($cached)) {
817 echo $cached;
818 exit;
819 }
820
821 // Generate data.
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();
827
828 // Process plugin hook.
829 $pluginManager->executeHooks('render_feed', $data, array(
830 'loggedin' => isLoggedIn(),
831 'target' => $targetPage,
832 ));
833
834 // Render the template.
835 $PAGE->assignAll($data);
836 $PAGE->renderPage('feed.'. $feedType);
837 $cache->cache(ob_get_contents());
838 ob_end_flush();
839 exit;
840 }
841
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');
847 exit;
848 }
849
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']))
852 {
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);
856
857 // Prevent redirection loop
858 if (isset($params['addtag'])) {
859 unset($params['addtag']);
860 }
861
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']);
866 } else {
867 $current_tags = array();
868 }
869 $addtag = true;
870 foreach ($current_tags as $value) {
871 if ($value === $_GET['addtag']) {
872 $addtag = false;
873 break;
874 }
875 }
876 // Append the tag if necessary
877 if (empty($params['searchtags'])) {
878 $params['searchtags'] = trim($_GET['addtag']);
879 }
880 elseif ($addtag) {
881 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
882 }
883
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));
886 exit;
887 }
888
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: ?');
894 exit;
895 }
896
897 // In case browser does not send HTTP_REFERER
898 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
899
900 // Prevent redirection loop
901 if (isset($params['removetag'])) {
902 unset($params['removetag']);
903 }
904
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);
910
911 if (empty($params['searchtags'])) {
912 unset($params['searchtags']);
913 }
914
915 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
916 }
917 header('Location: ?'.http_build_query($params));
918 exit;
919 }
920
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']));
925 }
926
927 if (! empty($_SERVER['HTTP_REFERER'])) {
928 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
929 } else {
930 $location = '?';
931 }
932 header('Location: '. $location);
933 exit;
934 }
935
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';
943 } else {
944 unset($_SESSION['visibility']);
945 }
946 } elseif ($_GET['visibility'] === 'public') {
947 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
948 // See only public links
949 $_SESSION['visibility'] = 'public';
950 } else {
951 unset($_SESSION['visibility']);
952 }
953 }
954
955 if (! empty($_SERVER['HTTP_REFERER'])) {
956 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
957 } else {
958 $location = '?';
959 }
960 header('Location: '. $location);
961 exit;
962 }
963
964 // -------- User wants to see only untagged links (toggle)
965 if (isset($_GET['untaggedonly'])) {
966 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
967
968 if (! empty($_SERVER['HTTP_REFERER'])) {
969 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
970 } else {
971 $location = '?';
972 }
973 header('Location: '. $location);
974 exit;
975 }
976
977 // -------- Handle other actions allowed for non-logged in users:
978 if (!isLoggedIn())
979 {
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']))
983 {
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']):'')
990 );
991 exit;
992 }
993
994 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
995 if (isset($_GET['edit_link'])) {
996 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
997 exit;
998 }
999
1000 exit; // Never remove this one! All operations below are reserved for logged in user.
1001 }
1002
1003 // -------- All other functions are reserved for the registered user:
1004
1005 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
1006 if ($targetPage == Router::$PAGE_TOOLS)
1007 {
1008 $data = [
1009 'pageabsaddr' => index_url($_SERVER),
1010 'sslenabled' => is_https($_SERVER),
1011 ];
1012 $pluginManager->executeHooks('render_tools', $data);
1013
1014 foreach ($data as $key => $value) {
1015 $PAGE->assign($key, $value);
1016 }
1017
1018 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
1019 $PAGE->renderPage('tools');
1020 exit;
1021 }
1022
1023 // -------- User wants to change his/her password.
1024 if ($targetPage == Router::$PAGE_CHANGEPASSWORD)
1025 {
1026 if ($conf->get('security.open_shaarli')) {
1027 die(t('You are not supposed to change a password on an Open Shaarli.'));
1028 }
1029
1030 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
1031 {
1032 if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away!
1033
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>';
1038 exit;
1039 }
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')));
1044 try {
1045 $conf->write(isLoggedIn());
1046 }
1047 catch(Exception $e) {
1048 error_log(
1049 'ERROR while writing config file after changing password.' . PHP_EOL .
1050 $e->getMessage()
1051 );
1052
1053 // TODO: do not handle exceptions/errors in JS.
1054 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
1055 exit;
1056 }
1057 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
1058 exit;
1059 }
1060 else // show the change password form.
1061 {
1062 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
1063 $PAGE->renderPage('changepassword');
1064 exit;
1065 }
1066 }
1067
1068 // -------- User wants to change configuration
1069 if ($targetPage == Router::$PAGE_CONFIGURE)
1070 {
1071 if (!empty($_POST['title']) )
1072 {
1073 if (!$sessionManager->checkToken($_POST['token'])) {
1074 die(t('Wrong token.')); // Go away!
1075 }
1076 $tz = 'UTC';
1077 if (!empty($_POST['continent']) && !empty($_POST['city'])
1078 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1079 ) {
1080 $tz = $_POST['continent'] . '/' . $_POST['city'];
1081 }
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']));
1094
1095 try {
1096 $conf->write(isLoggedIn());
1097 $history->updateSettings();
1098 invalidateCaches($conf->get('resource.page_cache'));
1099 }
1100 catch(Exception $e) {
1101 error_log(
1102 'ERROR while writing config file after configuration update.' . PHP_EOL .
1103 $e->getMessage()
1104 );
1105
1106 // TODO: do not handle exceptions/errors in JS.
1107 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1108 exit;
1109 }
1110 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1111 exit;
1112 }
1113 else // Show the configuration form.
1114 {
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')
1121 );
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');
1135 exit;
1136 }
1137 }
1138
1139 // -------- User wants to rename a tag or delete it
1140 if ($targetPage == Router::$PAGE_CHANGETAG)
1141 {
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');
1146 exit;
1147 }
1148
1149 if (!$sessionManager->checkToken($_POST['token'])) {
1150 die(t('Wrong token.'));
1151 }
1152
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);
1157 }
1158 $delete = empty($_POST['totag']);
1159 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1160 $count = count($alteredLinks);
1161 $alert = $delete
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>';
1165 exit;
1166 }
1167
1168 // -------- User wants to add a link without using the bookmarklet: Show form.
1169 if ($targetPage == Router::$PAGE_ADDLINK)
1170 {
1171 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1172 $PAGE->renderPage('addlink');
1173 exit;
1174 }
1175
1176 // -------- User clicked the "Save" button when editing a link: Save link to database.
1177 if (isset($_POST['save_edit']))
1178 {
1179 // Go away!
1180 if (! $sessionManager->checkToken($_POST['token'])) {
1181 die(t('Wrong token.'));
1182 }
1183
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])) {
1192 // Edit
1193 $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
1194 $updated = new DateTime();
1195 $shortUrl = $LINKSDB[$id]['shorturl'];
1196 $new = false;
1197 } else {
1198 // New link
1199 $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
1200 $updated = null;
1201 $shortUrl = link_small_hash($created, $id);
1202 $new = true;
1203 }
1204
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)));
1211
1212 if (empty(trim($_POST['lf_url']))) {
1213 $_POST['lf_url'] = '?' . smallHash($linkdate . $id);
1214 }
1215 $url = whitelist_protocols(trim($_POST['lf_url']), $conf->get('security.allowed_protocols'));
1216
1217 $link = array(
1218 'id' => $id,
1219 'title' => trim($_POST['lf_title']),
1220 'url' => $url,
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,
1227 );
1228
1229 // If title is empty, use the URL as title.
1230 if ($link['title'] == '') {
1231 $link['title'] = $link['url'];
1232 }
1233
1234 $pluginManager->executeHooks('save_link', $link);
1235
1236 $LINKSDB[$id] = $link;
1237 $LINKSDB->save($conf->get('resource.page_cache'));
1238 if ($new) {
1239 $history->addLink($link);
1240 } else {
1241 $history->updateLink($link);
1242 }
1243
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>';
1247 exit;
1248 }
1249
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);
1256 exit;
1257 }
1258
1259 // -------- User clicked the "Cancel" button when editing a link.
1260 if (isset($_POST['cancel_edit']))
1261 {
1262 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1263 if (! isset($LINKSDB[$id])) {
1264 header('Location: ?');
1265 }
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.
1274 exit;
1275 }
1276
1277 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1278 if ($targetPage == Router::$PAGE_DELETELINK)
1279 {
1280 if (! $sessionManager->checkToken($_GET['token'])) {
1281 die(t('Wrong token.'));
1282 }
1283
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))));
1288 } else {
1289 // only a single id provided
1290 $ids = [$ids];
1291 }
1292 // assert at least one id is given
1293 if(!count($ids)){
1294 die('no id provided');
1295 }
1296 foreach ($ids as $id) {
1297 $id = (int) escape($id);
1298 $link = $LINKSDB[$id];
1299 $pluginManager->executeHooks('delete_link', $link);
1300 unset($LINKSDB[$id]);
1301 }
1302 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
1303 $history->deleteLink($link);
1304
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; }
1307
1308 $location = '?';
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']]
1315 );
1316 }
1317
1318 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1319 exit;
1320 }
1321
1322 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1323 if (isset($_GET['edit_link']))
1324 {
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);
1329 $data = array(
1330 'link' => $link,
1331 'link_is_new' => false,
1332 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1333 'tags' => $LINKSDB->linksCountPerTag(),
1334 );
1335 $pluginManager->executeHooks('render_editlink', $data);
1336
1337 foreach ($data as $key => $value) {
1338 $PAGE->assign($key, $value);
1339 }
1340
1341 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1342 $PAGE->renderPage('editlink');
1343 exit;
1344 }
1345
1346 // -------- User want to post a new link: Display link edit form.
1347 if (isset($_GET['post'])) {
1348 $url = cleanup_url($_GET['post']);
1349
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);
1353 if (! $link)
1354 {
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.
1367 get_http_response(
1368 $url,
1369 $conf->get('general.download_timeout', 30),
1370 $conf->get('general.download_max_size', 4194304),
1371 get_curl_download_callback($charset, $title)
1372 );
1373 if (! empty($title) && strtolower($charset) != 'utf-8') {
1374 $title = mb_convert_encoding($title, 'utf-8', $charset);
1375 }
1376 }
1377
1378 if ($url == '') {
1379 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
1380 $title = $conf->get('general.default_note_title', t('Note: '));
1381 }
1382 $url = escape($url);
1383 $title = escape($title);
1384
1385 $link = array(
1386 'linkdate' => $linkdate,
1387 'title' => $title,
1388 'url' => $url,
1389 'description' => $description,
1390 'tags' => $tags,
1391 'private' => $private,
1392 );
1393 } else {
1394 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
1395 }
1396
1397 $data = array(
1398 'link' => $link,
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),
1404 );
1405 $pluginManager->executeHooks('render_editlink', $data);
1406
1407 foreach ($data as $key => $value) {
1408 $PAGE->assign($key, $value);
1409 }
1410
1411 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1412 $PAGE->renderPage('editlink');
1413 exit;
1414 }
1415
1416 if ($targetPage == Router::$PAGE_EXPORT) {
1417 // Export links as a Netscape Bookmarks file
1418
1419 if (empty($_GET['selection'])) {
1420 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1421 $PAGE->renderPage('export');
1422 exit;
1423 }
1424
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'];
1429 } else {
1430 $prependNoteUrl = false;
1431 }
1432
1433 try {
1434 $PAGE->assign(
1435 'links',
1436 NetscapeBookmarkUtils::filterAndFormat(
1437 $LINKSDB,
1438 $selection,
1439 $prependNoteUrl,
1440 index_url($_SERVER)
1441 )
1442 );
1443 } catch (Exception $exc) {
1444 header('Content-Type: text/plain; charset=utf-8');
1445 echo $exc->getMessage();
1446 exit;
1447 }
1448 $now = new DateTime();
1449 header('Content-Type: text/html; charset=utf-8');
1450 header(
1451 'Content-disposition: attachment; filename=bookmarks_'
1452 .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html'
1453 );
1454 $PAGE->assign('date', $now->format(DateTime::RFC822));
1455 $PAGE->assign('eol', PHP_EOL);
1456 $PAGE->assign('selection', $selection);
1457 $PAGE->renderPage('export.bookmarks');
1458 exit;
1459 }
1460
1461 if ($targetPage == Router::$PAGE_IMPORT) {
1462 // Upload a Netscape bookmark dump to import its contents
1463
1464 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1465 // Show import dialog
1466 $PAGE->assign(
1467 'maxfilesize',
1468 get_max_upload_size(
1469 ini_get('post_max_size'),
1470 ini_get('upload_max_filesize'),
1471 false
1472 )
1473 );
1474 $PAGE->assign(
1475 'maxfilesizeHuman',
1476 get_max_upload_size(
1477 ini_get('post_max_size'),
1478 ini_get('upload_max_filesize'),
1479 true
1480 )
1481 );
1482 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1483 $PAGE->renderPage('import');
1484 exit;
1485 }
1486
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.
1490 $msg = sprintf(
1491 t(
1492 'The file you are trying to upload is probably bigger than what this webserver can accept'
1493 .' (%s). Please upload in smaller chunks.'
1494 ),
1495 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1496 );
1497 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router::$PAGE_IMPORT .'\';</script>';
1498 exit;
1499 }
1500 if (! $sessionManager->checkToken($_POST['token'])) {
1501 die('Wrong token.');
1502 }
1503 $status = NetscapeBookmarkUtils::import(
1504 $_POST,
1505 $_FILES,
1506 $LINKSDB,
1507 $conf,
1508 $history
1509 );
1510 echo '<script>alert("'.$status.'");document.location=\'?do='
1511 .Router::$PAGE_IMPORT .'\';</script>';
1512 exit;
1513 }
1514
1515 // Plugin administration page
1516 if ($targetPage == Router::$PAGE_PLUGINSADMIN) {
1517 $pluginMeta = $pluginManager->getPluginsMeta();
1518
1519 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1520 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; });
1521 // Load parameters.
1522 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1523 uasort(
1524 $enabledPlugins,
1525 function($a, $b) { return $a['order'] - $b['order']; }
1526 );
1527 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] === false; });
1528
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');
1533 exit;
1534 }
1535
1536 // Plugin administration form action
1537 if ($targetPage == Router::$PAGE_SAVE_PLUGINSADMIN) {
1538 try {
1539 if (isset($_POST['parameters_form'])) {
1540 unset($_POST['parameters_form']);
1541 foreach ($_POST as $param => $value) {
1542 $conf->set('plugins.'. $param, escape($value));
1543 }
1544 }
1545 else {
1546 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1547 }
1548 $conf->write(isLoggedIn());
1549 $history->updateSettings();
1550 }
1551 catch (Exception $e) {
1552 error_log(
1553 'ERROR while saving plugin configuration:.' . PHP_EOL .
1554 $e->getMessage()
1555 );
1556
1557 // TODO: do not handle exceptions/errors in JS.
1558 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router::$PAGE_PLUGINSADMIN .'\';</script>';
1559 exit;
1560 }
1561 header('Location: ?do='. Router::$PAGE_PLUGINSADMIN);
1562 exit;
1563 }
1564
1565 // Get a fresh token
1566 if ($targetPage == Router::$GET_TOKEN) {
1567 header('Content-Type:text/plain');
1568 echo $sessionManager->generateToken($conf);
1569 exit;
1570 }
1571
1572 // -------- Otherwise, simply display search form and links:
1573 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
1574 exit;
1575 }
1576
1577 /**
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'
1580 *
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.
1585 */
1586 function buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager)
1587 {
1588 // Used in templates
1589 if (isset($_GET['searchtags'])) {
1590 if (! empty($_GET['searchtags'])) {
1591 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1592 } else {
1593 $searchtags = false;
1594 }
1595 } else {
1596 $searchtags = '';
1597 }
1598 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1599
1600 // Smallhash filter
1601 if (! empty($_SERVER['QUERY_STRING'])
1602 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1603 try {
1604 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1605 } catch (LinkNotFoundException $e) {
1606 $PAGE->render404($e->getMessage());
1607 exit;
1608 }
1609 } else {
1610 // Filter links according search parameters.
1611 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
1612 $request = [
1613 'searchtags' => $searchtags,
1614 'searchterm' => $searchterm,
1615 ];
1616 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
1617 }
1618
1619 // ---- Handle paging.
1620 $keys = array();
1621 foreach ($linksToDisplay as $key => $value) {
1622 $keys[] = $key;
1623 }
1624
1625
1626
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;
1633 // Start index.
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))
1638 {
1639 $link = $linksToDisplay[$keys[$i]];
1640 $link['description'] = format_description(
1641 $link['description'],
1642 $conf->get('redirector.url'),
1643 $conf->get('redirector.encode_url')
1644 );
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();
1650 } else {
1651 $link['updated_timestamp'] = '';
1652 }
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'];
1660 }
1661
1662 $linkDisp[$keys[$i]] = $link;
1663 $i++;
1664 }
1665
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;
1672 }
1673 $next_page_url='';
1674 if ($page>1) {
1675 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1676 }
1677
1678 // Fill all template fields.
1679 $data = array(
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,
1690 );
1691
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 .']';
1700 };
1701 $data['pagetitle'] .= ! empty($searchtags)
1702 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1703 : '';
1704 $data['pagetitle'] .= '- '. $conf->get('general.title');
1705 }
1706
1707 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => isLoggedIn()));
1708
1709 foreach ($data as $key => $value) {
1710 $PAGE->assign($key, $value);
1711 }
1712
1713 return;
1714 }
1715
1716 /**
1717 * Compute the thumbnail for a link.
1718 *
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.
1726 *
1727 * @param ConfigManager $conf Configuration Manager instance.
1728 * @param string $url
1729 * @param string|bool $href
1730 *
1731 * @return array
1732 */
1733 function computeThumbnail($conf, $url, $href = false)
1734 {
1735 if (!$conf->get('thumbnail.enable_thumbnails')) return array();
1736 if ($href==false) $href=$url;
1737
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')
1743 {
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');
1747 }
1748 if ($domain=='youtu.be') // Youtube short links
1749 {
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');
1753 }
1754 if ($domain=='pix.toile-libre.org') // pix.toile-libre.org image hosting
1755 {
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');
1759 }
1760
1761 if ($domain=='imgur.com')
1762 {
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');
1769
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');
1772 }
1773 if ($domain=='i.imgur.com')
1774 {
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');
1778 }
1779 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
1780 {
1781 if (strpos($url,'dailymotion.com/video/')!==false)
1782 {
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');
1786 }
1787 }
1788 if (endsWith($domain,'.imageshack.us'))
1789 {
1790 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1791 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1792 {
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');
1796 }
1797 }
1798
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)
1802
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.
1804
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')
1809 )
1810 {
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.
1815 }
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();
1820 }
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.
1825 }
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');
1829 }
1830
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')
1836 {
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');
1840 }
1841 return array(); // No thumbnail.
1842
1843 }
1844
1845
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)
1853 {
1854 // FIXME!
1855 global $conf;
1856 $t = computeThumbnail($conf, $url,$href);
1857 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1858
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']).'"';
1864 $html.='></a>';
1865 return $html;
1866 }
1867
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)
1875 {
1876 // FIXME!
1877 global $conf;
1878 $t = computeThumbnail($conf, $url,$href);
1879 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1880
1881 $html='<a href="'.escape($t['href']).'">';
1882
1883 // Lazy image
1884 $html.='<img class="b-lazy" src="#" data-src="'.escape($t['src']).'"';
1885
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']).'"';
1890 $html.='>';
1891
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>';
1899
1900 return $html;
1901 }
1902
1903
1904 /**
1905 * Installation
1906 * This function should NEVER be called if the file data/config.php exists.
1907 *
1908 * @param ConfigManager $conf Configuration Manager instance.
1909 * @param SessionManager $sessionManager SessionManager instance
1910 */
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);
1914
1915
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'))
1920 {
1921 // Step 2: Check if data in session is correct.
1922 $msg = t(
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>'
1930 );
1931 $msg = sprintf($msg, session_save_path());
1932 echo $msg;
1933 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1934 die;
1935 }
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.
1940 }
1941 if (isset($_GET['test_session']))
1942 { // Step 3: Sessions are OK. Remove test parameter from URL.
1943 header('Location: '.index_url($_SERVER));
1944 }
1945
1946
1947 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1948 {
1949 $tz = 'UTC';
1950 if (!empty($_POST['continent']) && !empty($_POST['city'])
1951 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1952 ) {
1953 $tz = $_POST['continent'].'/'.$_POST['city'];
1954 }
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']));
1963 } else {
1964 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
1965 }
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']));
1969 $conf->set(
1970 'api.secret',
1971 generate_api_secret(
1972 $conf->get('credentials.login'),
1973 $conf->get('credentials.salt')
1974 )
1975 );
1976 try {
1977 // Everything is ok, let's create config file.
1978 $conf->write(isLoggedIn());
1979 }
1980 catch(Exception $e) {
1981 error_log(
1982 'ERROR while writing config file after installation.' . PHP_EOL .
1983 $e->getMessage()
1984 );
1985
1986 // TODO: do not handle exceptions/errors in JS.
1987 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1988 exit;
1989 }
1990 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
1991 exit;
1992 }
1993
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');
2000 exit;
2001 }
2002
2003 /**
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.
2012 *
2013 * @param ConfigManager $conf Configuration Manager instance,
2014 */
2015 function genThumbnail($conf)
2016 {
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!');
2020
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);
2028 return;
2029 }
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))
2033 {
2034 header('Content-Type: image/gif');
2035 echo file_get_contents($cacheDir .'/'. $blankname);
2036 return;
2037 }
2038
2039 // Otherwise, generate the thumbnail.
2040 $url = $_GET['url'];
2041 $domain = parse_url($url,PHP_URL_HOST);
2042
2043 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
2044 {
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);
2047
2048 // Is this a link to an image, or to a flickr page ?
2049 $imageurl='';
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';
2054 }
2055 else // This is a flickr page (html)
2056 {
2057 // Get the flickr html page.
2058 list($headers, $content) = get_http_response($url, 20);
2059 if (strpos($headers[0], '200 OK') !== false)
2060 {
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];
2064
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" />
2068 if ($imageurl=='')
2069 {
2070 preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!', $content, $matches);
2071 if (!empty($matches[1])) $imageurl=$matches[1];
2072 }
2073 }
2074 }
2075
2076 if ($imageurl!='')
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');
2084 echo $content;
2085 return;
2086 }
2087 }
2088 }
2089
2090 elseif ($domain=='vimeo.com' )
2091 {
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');
2105 echo $content;
2106 return;
2107 }
2108 }
2109 }
2110
2111 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
2112 {
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))
2129 {
2130 header('Content-Type: image/jpeg');
2131 echo file_get_contents($filepath);
2132 return;
2133 }
2134 }
2135 }
2136 }
2137 }
2138
2139 elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
2140 {
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))
2158 {
2159 header('Content-Type: image/jpeg');
2160 echo file_get_contents($filepath);
2161 return;
2162 }
2163 }
2164 }
2165 }
2166 }
2167
2168 else
2169 {
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))
2178 {
2179 header('Content-Type: image/jpeg');
2180 echo file_get_contents($filepath);
2181 return;
2182 }
2183 }
2184 }
2185
2186
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');
2192 echo $blankgif;
2193 }
2194
2195 // Make a thumbnail of the image (to width: 120 pixels)
2196 // Returns true if success, false otherwise.
2197 function resizeImage($filepath)
2198 {
2199 if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
2200
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.
2204 $im=false;
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)
2209 $w = imagesx($im);
2210 $h = imagesy($im);
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.
2215 // Resize image:
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);
2221 imagedestroy($im);
2222 imagedestroy($im2);
2223 unlink($filepath);
2224 rename($tempname,$filepath); // Overwrite original picture with thumbnail.
2225 return true;
2226 }
2227
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);
2232 }
2233
2234 try {
2235 $history = new History($conf->get('resource.history'));
2236 } catch(Exception $e) {
2237 die($e->getMessage());
2238 }
2239
2240 $linkDb = new LinkDB(
2241 $conf->get('resource.datastore'),
2242 isLoggedIn(),
2243 $conf->get('privacy.hide_public_links'),
2244 $conf->get('redirector.url'),
2245 $conf->get('redirector.encode_url')
2246 );
2247
2248 $container = new \Slim\Container();
2249 $container['conf'] = $conf;
2250 $container['plugins'] = $pluginManager;
2251 $container['history'] = $history;
2252 $app = new \Slim\App($container);
2253
2254 // REST API routes
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');
2264
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);
2272 } else {
2273 $app->respond($response);
2274 }