]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - index.php
Process daily page through Slim controller
[github/shaarli/Shaarli.git] / index.php
CommitLineData
45034273 1<?php
49e2b35b 2/**
b786c883 3 * Shaarli - The personal, minimalist, super-fast, database free, bookmarking service.
49e2b35b
V
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
49e2b35b 13 */
afd7b77b
V
14
15// Set 'UTC' as the default timezone if it is not defined in php.ini
16// See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
17if (date_default_timezone_get() == '') {
18 date_default_timezone_set('UTC');
19}
cb49ab94 20
28bb2b74
V
21/*
22 * PHP configuration
23 */
28bb2b74 24
ae00595b 25// http://server.com/x/shaarli --> /shaarli/
684e662a 26define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0)));
45034273 27
28bb2b74 28// High execution time in case of problematic imports/exports.
93bf0918 29ini_set('max_input_time', '60');
28bb2b74
V
30
31// Try to set max upload file size and read
32ini_set('memory_limit', '128M');
45034273
SS
33ini_set('post_max_size', '16M');
34ini_set('upload_max_filesize', '16M');
45034273 35
28bb2b74
V
36// See all error except warnings
37error_reporting(E_ALL^E_WARNING);
50c9a12e 38
a973afea 39// 3rd-party libraries
52831753
V
40if (! file_exists(__DIR__ . '/vendor/autoload.php')) {
41 header('Content-Type: text/plain; charset=utf-8');
42 echo "Error: missing Composer configuration\n\n"
43 ."If you installed Shaarli through Git or using the development branch,\n"
44 ."please refer to the installation documentation to install PHP"
45 ." dependencies using Composer:\n"
87f14312 46 ."- https://shaarli.readthedocs.io/en/master/Server-configuration/\n"
cc8f572b 47 ."- https://shaarli.readthedocs.io/en/master/Download-and-Installation/";
52831753
V
48 exit;
49}
a973afea
V
50require_once 'inc/rain.tpl.class.php';
51require_once __DIR__ . '/vendor/autoload.php';
52
ca74886f 53// Shaarli library
fe3713d2 54require_once 'application/bookmark/LinkUtils.php';
e6cd773f 55require_once 'application/config/ConfigPlugin.php';
51753e40
V
56require_once 'application/http/HttpUtils.php';
57require_once 'application/http/UrlUtils.php';
bcf056c9 58require_once 'application/updater/UpdaterUtils.php';
2e28269b 59require_once 'application/FileUtils.php';
d1e2f8e5 60require_once 'application/TimeZone.php';
ca74886f 61require_once 'application/Utils.php';
f24896b2 62
6c50a6cc 63use Shaarli\ApplicationUtils;
cf92b4dd 64use Shaarli\Bookmark\Bookmark;
cf92b4dd 65use Shaarli\Bookmark\BookmarkFileService;
6c50a6cc
A
66use Shaarli\Bookmark\BookmarkFilter;
67use Shaarli\Bookmark\BookmarkServiceInterface;
68use Shaarli\Bookmark\Exception\BookmarkNotFoundException;
69use Shaarli\Config\ConfigManager;
70use Shaarli\Container\ContainerBuilder;
71use Shaarli\Feed\CachedPage;
72use Shaarli\Feed\FeedBuilder;
a39acb25 73use Shaarli\Formatter\BookmarkMarkdownFormatter;
cf92b4dd 74use Shaarli\Formatter\FormatterFactory;
6c50a6cc
A
75use Shaarli\History;
76use Shaarli\Languages;
77use Shaarli\Netscape\NetscapeBookmarkUtils;
78use Shaarli\Plugin\PluginManager;
79use Shaarli\Render\PageBuilder;
b0428aa9 80use Shaarli\Render\PageCacheManager;
6c50a6cc
A
81use Shaarli\Render\ThemeUtils;
82use Shaarli\Router;
83use Shaarli\Security\LoginManager;
84use Shaarli\Security\SessionManager;
85use Shaarli\Thumbnailer;
86use Shaarli\Updater\Updater;
87use Shaarli\Updater\UpdaterUtils;
88use Slim\App;
ca74886f 89
d1e2f8e5
V
90// Ensure the PHP version is supported
91try {
b405a44f 92 ApplicationUtils::checkPHPVersion('7.1', PHP_VERSION);
93bf0918 93} catch (Exception $exc) {
d1e2f8e5 94 header('Content-Type: text/plain; charset=utf-8');
2e28269b 95 echo $exc->getMessage();
d1e2f8e5
V
96 exit;
97}
98
b3e1f92e 99define('SHAARLI_VERSION', ApplicationUtils::getVersion(__DIR__ .'/'. ApplicationUtils::$VERSION_FILE));
b786c883 100
06b6660a
A
101// Force cookie path (but do not change lifetime)
102$cookie = session_get_cookie_params();
103$cookiedir = '';
104if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
105 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
106}
107// Set default cookie expiration and path.
108session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
109// Set session parameters on server side.
06b6660a
A
110// Use cookies to store session.
111ini_set('session.use_cookies', 1);
112// Force cookies for session (phpsessionID forbidden in URL).
113ini_set('session.use_only_cookies', 1);
114// Prevent PHP form using sessionID in URL if cookies are disabled.
115ini_set('session.use_trans_sid', false);
116
06b6660a
A
117session_name('shaarli');
118// Start session if needed (Some server auto-start sessions).
f6380409 119if (session_status() == PHP_SESSION_NONE) {
06b6660a
A
120 session_start();
121}
122
68bc2135 123// Regenerate session ID if invalid or not defined in cookie.
fd7d8461 124if (isset($_COOKIE['shaarli']) && !SessionManager::checkId($_COOKIE['shaarli'])) {
68bc2135
V
125 session_regenerate_id(true);
126 $_COOKIE['shaarli'] = session_id();
127}
128
278d9ee2 129$conf = new ConfigManager();
cf92b4dd
A
130
131// In dev mode, throw exception on any warning
132if ($conf->get('dev.debug', false)) {
133 // See all errors (for debugging only)
134 error_reporting(-1);
135
136 set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
137 throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
138 });
139}
140
ebd650c0 141$sessionManager = new SessionManager($_SESSION, $conf);
b49a04f7 142$loginManager = new LoginManager($conf, $sessionManager);
c689e108 143$loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
84742084 144$clientIpId = client_ip_id($_SERVER);
12266213 145
b7c412d4
A
146// LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
147if (! defined('LC_MESSAGES')) {
148 define('LC_MESSAGES', LC_COLLATE);
149}
150
12266213
A
151// Sniff browser language and set date format accordingly.
152if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
153 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
154}
155
156new Languages(setlocale(LC_MESSAGES, 0), $conf);
157
7f179985 158$conf->setEmpty('general.timezone', date_default_timezone_get());
cf92b4dd 159$conf->setEmpty('general.title', t('Shared bookmarks on '). escape(index_url($_SERVER)));
adc4aee8 160RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
894a3c4b 161RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
45034273 162
278d9ee2 163$pluginManager = new PluginManager($conf);
da10377b 164$pluginManager->load($conf->get('general.enabled_plugins'));
6fc14d53 165
da10377b 166date_default_timezone_set($conf->get('general.timezone', 'UTC'));
d93d51b2 167
45034273
SS
168ob_start(); // Output buffering for the page cache.
169
45034273
SS
170// Prevent caching on client side or proxy: (yes, it's ugly)
171header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
172header("Cache-Control: no-store, no-cache, must-revalidate");
173header("Cache-Control: post-check=0, pre-check=0", false);
174header("Pragma: no-cache");
175
278d9ee2 176if (! is_file($conf->getConfigFileExt())) {
2e28269b 177 // Ensure Shaarli has proper access to its resources
278d9ee2 178 $errors = ApplicationUtils::checkResourcePermissions($conf);
2e28269b
V
179
180 if ($errors != array()) {
12266213 181 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
2e28269b
V
182
183 foreach ($errors as $error) {
184 $message .= '<li>'.$error.'</li>';
185 }
186 $message .= '</ul>';
187
188 header('Content-Type: text/html; charset=utf-8');
189 echo $message;
190 exit;
191 }
192
193 // Display the installation form if no existing config is found
cad4251a 194 install($conf, $sessionManager, $loginManager);
50c9a12e 195}
8a80e4fe 196
c689e108 197$loginManager->checkLoginState($_COOKIE, $clientIpId);
45034273 198
278d9ee2 199/**
89ccc83b 200 * Adapter function to ensure compatibility with third-party templates
278d9ee2 201 *
89ccc83b
V
202 * @see https://github.com/shaarli/Shaarli/pull/1086
203 *
204 * @return bool true when the user is logged in, false otherwise
278d9ee2 205 */
45034273
SS
206function isLoggedIn()
207{
63ea23c2
V
208 global $loginManager;
209 return $loginManager->isLoggedIn();
45034273
SS
210}
211
63ea23c2 212
45034273
SS
213// ------------------------------------------------------------------------------------------
214// Process login form: Check if login/password is correct.
db45a36a 215if (isset($_POST['login'])) {
44acf706
V
216 if (! $loginManager->canLogin($_SERVER)) {
217 die(t('I said: NO. You are banned for the moment. Go away.'));
218 }
278d9ee2 219 if (isset($_POST['password'])
ebd650c0 220 && $sessionManager->checkToken($_POST['token'])
84742084 221 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
44acf706 222 ) {
44acf706
V
223 $loginManager->handleSuccessfulLogin($_SERVER);
224
51f0128c
V
225 $cookiedir = '';
226 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
ad6c27b7 227 // Note: Never forget the trailing slash on the cookie path!
51f0128c 228 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
45034273 229 }
51f0128c
V
230
231 if (!empty($_POST['longlastingsession'])) {
232 // Keep the session cookie even after the browser closes
233 $sessionManager->setStaySignedIn(true);
234 $expirationTime = $sessionManager->extendSession();
235
236 setcookie(
c689e108
V
237 $loginManager::$STAY_SIGNED_IN_COOKIE,
238 $loginManager->getStaySignedInToken(),
51f0128c
V
239 $expirationTime,
240 WEB_PATH
241 );
51f0128c
V
242 } else {
243 // Standard session expiration (=when browser closes)
244 $expirationTime = 0;
45034273 245 }
f4c84ad7 246
51f0128c 247 // Send cookie with the new expiration date to the browser
09390a50 248 session_destroy();
51f0128c 249 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
09390a50 250 session_start();
51f0128c
V
251 session_regenerate_id(true);
252
45034273 253 // Optional redirect after login:
5fbabbb9 254 if (isset($_GET['post'])) {
9e4cc28e 255 $uri = './?post='. urlencode($_GET['post']);
0b04f797 256 foreach (array('description', 'source', 'title', 'tags') as $param) {
5fbabbb9
A
257 if (!empty($_GET[$param])) {
258 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
259 }
260 }
261 header('Location: '. $uri);
262 exit;
263 }
264
265 if (isset($_GET['edit_link'])) {
9e4cc28e 266 header('Location: ./?edit_link='. escape($_GET['edit_link']));
5fbabbb9
A
267 exit;
268 }
269
270 if (isset($_POST['returnurl'])) {
271 // Prevent loops over login screen.
9e4cc28e 272 if (strpos($_POST['returnurl'], '/login') === false) {
e15f08d7 273 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
5fbabbb9
A
274 exit;
275 }
45034273 276 }
9e4cc28e 277 header('Location: ./?');
93bf0918 278 exit;
44acf706
V
279 } else {
280 $loginManager->handleFailedLogin($_SERVER);
9e4cc28e 281 $redir = '?username='. urlencode($_POST['login']);
5fbabbb9 282 if (isset($_GET['post'])) {
85c4bdc2 283 $redir .= '&post=' . urlencode($_GET['post']);
0b04f797 284 foreach (array('description', 'source', 'title', 'tags') as $param) {
5fbabbb9
A
285 if (!empty($_GET[$param])) {
286 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
287 }
288 }
289 }
12266213 290 // Redirect to login screen.
9e4cc28e 291 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'./login'.$redir.'\';</script>';
45034273
SS
292 exit;
293 }
294}
295
45034273
SS
296// ------------------------------------------------------------------------------------------
297// Token management for XSRF protection
298// Token should be used in any form which acts on data (create,update,delete,import...).
93bf0918
V
299if (!isset($_SESSION['tokens'])) {
300 $_SESSION['tokens']=array(); // Token are attached to the session.
301}
45034273 302
278d9ee2 303/**
cf92b4dd
A
304 * Daily RSS feed: 1 RSS entry per day giving all the bookmarks on that day.
305 * Gives the last 7 days (which have bookmarks).
278d9ee2
A
306 * This RSS feed cannot be filtered.
307 *
cf92b4dd
A
308 * @param BookmarkServiceInterface $bookmarkService
309 * @param ConfigManager $conf Configuration Manager instance
310 * @param LoginManager $loginManager LoginManager instance
278d9ee2 311 */
cf92b4dd 312function showDailyRSS($bookmarkService, $conf, $loginManager)
93bf0918 313{
45034273 314 // Cache system
5046bcb6 315 $query = $_SERVER['QUERY_STRING'];
01e48f26 316 $cache = new CachedPage(
684e662a 317 $conf->get('config.PAGE_CACHE'),
482d67bd 318 page_url($_SERVER),
93bf0918 319 startsWith($query, 'do=dailyrss') && !$loginManager->isLoggedIn()
01e48f26 320 );
f3b8f9f0
A
321 $cached = $cache->cachedVersion();
322 if (!empty($cached)) {
323 echo $cached;
324 exit;
325 }
9f15ca9e 326
cf92b4dd 327 /* Some Shaarlies may have very few bookmarks, so we need to look
01878a75 328 back in time until we have enough days ($nb_of_days).
45034273 329 */
f3b8f9f0 330 $nb_of_days = 7; // We take 7 days.
684e662a 331 $today = date('Ymd');
f3b8f9f0
A
332 $days = array();
333
cf92b4dd
A
334 foreach ($bookmarkService->search() as $bookmark) {
335 $day = $bookmark->getCreated()->format('Ymd'); // Extract day (without time)
01878a75 336 if (strcmp($day, $today) < 0) {
f3b8f9f0
A
337 if (empty($days[$day])) {
338 $days[$day] = array();
339 }
cf92b4dd 340 $days[$day][] = $bookmark;
f3b8f9f0
A
341 }
342
343 if (count($days) > $nb_of_days) {
344 break; // Have we collected enough days?
45034273 345 }
45034273 346 }
bb8f712d 347
45034273
SS
348 // Build the RSS feed.
349 header('Content-Type: application/rss+xml; charset=utf-8');
482d67bd 350 $pageaddr = escape(index_url($_SERVER));
45034273 351 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
f3b8f9f0 352 echo '<channel>';
da10377b 353 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
f3b8f9f0 354 echo '<link>'. $pageaddr .'</link>';
cf92b4dd 355 echo '<description>Daily shared bookmarks</description>';
f3b8f9f0
A
356 echo '<language>en-en</language>';
357 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL;
358
a39acb25 359 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
cf92b4dd
A
360 $formatter = $factory->getFormatter();
361 $formatter->addContextData('index_url', index_url($_SERVER));
f3b8f9f0 362 // For each day.
cf92b4dd
A
363 /** @var Bookmark[] $bookmarks */
364 foreach ($days as $day => $bookmarks) {
365 $formattedBookmarks = [];
366 $dayDate = DateTime::createFromFormat(Bookmark::LINK_DATE_FORMAT, $day.'_000000');
482d67bd 367 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
bb8f712d 368
45034273 369 // We pre-format some fields for proper output.
cf92b4dd
A
370 foreach ($bookmarks as $key => $bookmark) {
371 $formattedBookmarks[$key] = $formatter->format($bookmark);
372 // This page is a bit specific, we need raw description to calculate the length
373 $formattedBookmarks[$key]['formatedDescription'] = $formattedBookmarks[$key]['description'];
374 $formattedBookmarks[$key]['description'] = $bookmark->getDescription();
375
376 if ($bookmark->isNote()) {
377 $link['url'] = index_url($_SERVER) . $bookmark->getUrl(); // make permalink URL absolute
f3b8f9f0 378 }
45034273 379 }
f3b8f9f0 380
45034273 381 // Then build the HTML for this day:
cf92b4dd 382 $tpl = new RainTPL();
da10377b 383 $tpl->assign('title', $conf->get('general.title'));
205a4277 384 $tpl->assign('daydate', $dayDate->getTimestamp());
f3b8f9f0 385 $tpl->assign('absurl', $absurl);
cf92b4dd 386 $tpl->assign('links', $formattedBookmarks);
205a4277 387 $tpl->assign('rssdate', escape($dayDate->format(DateTime::RSS)));
894a3c4b 388 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
bf3c9934 389 $tpl->assign('index_url', $pageaddr);
724f1e32 390 $html = $tpl->draw('dailyrss', true);
45034273 391
f3b8f9f0 392 echo $html . PHP_EOL;
bb8f712d 393 }
482d67bd 394 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
bb8f712d 395
45034273
SS
396 $cache->cache(ob_get_contents());
397 ob_end_flush();
398 exit;
399}
400
278d9ee2
A
401/**
402 * Renders the linklist
403 *
cf92b4dd
A
404 * @param pageBuilder $PAGE pageBuilder instance.
405 * @param BookmarkServiceInterface $linkDb instance.
406 * @param ConfigManager $conf Configuration Manager instance.
407 * @param PluginManager $pluginManager Plugin Manager instance.
278d9ee2 408 */
cf92b4dd 409function showLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager)
93bf0918 410{
cf92b4dd 411 buildLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager);
6fc14d53
A
412 $PAGE->renderPage('linklist');
413}
414
278d9ee2
A
415/**
416 * Render HTML page (according to URL parameters and user rights)
417 *
cf92b4dd
A
418 * @param ConfigManager $conf Configuration Manager instance.
419 * @param PluginManager $pluginManager Plugin Manager instance,
420 * @param BookmarkServiceInterface $bookmarkService
421 * @param History $history instance
422 * @param SessionManager $sessionManager SessionManager instance
423 * @param LoginManager $loginManager LoginManager instance
278d9ee2 424 */
cf92b4dd 425function renderPage($conf, $pluginManager, $bookmarkService, $history, $sessionManager, $loginManager)
45034273 426{
b0428aa9 427 $pageCacheManager = new PageCacheManager($conf->get('resource.page_cache'));
510377d2 428 $updater = new Updater(
cf92b4dd
A
429 UpdaterUtils::read_updates_file($conf->get('resource.updates')),
430 $bookmarkService,
278d9ee2 431 $conf,
cf92b4dd 432 $loginManager->isLoggedIn()
510377d2
A
433 );
434 try {
435 $newUpdates = $updater->update();
436 if (! empty($newUpdates)) {
cf92b4dd 437 UpdaterUtils::write_updates_file(
894a3c4b 438 $conf->get('resource.updates'),
510377d2
A
439 $updater->getDoneUpdates()
440 );
b0428aa9
A
441
442 $pageCacheManager->invalidateCaches();
510377d2 443 }
93bf0918 444 } catch (Exception $e) {
510377d2
A
445 die($e->getMessage());
446 }
447
cf92b4dd
A
448 $PAGE = new PageBuilder($conf, $_SESSION, $bookmarkService, $sessionManager->generateToken(), $loginManager->isLoggedIn());
449 $PAGE->assign('linkcount', $bookmarkService->count(BookmarkFilter::$ALL));
450 $PAGE->assign('privateLinkcount', $bookmarkService->count(BookmarkFilter::$PRIVATE));
7fde6de1 451 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
6fc14d53
A
452
453 // Determine which page will be rendered.
454 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
63ea23c2 455 $targetPage = Router::findPage($query, $_GET, $loginManager->isLoggedIn());
6fc14d53 456
93bf0918 457 if (// if the user isn't logged in
63ea23c2 458 !$loginManager->isLoggedIn() &&
27e21231
WE
459 // and Shaarli doesn't have public content...
460 $conf->get('privacy.hide_public_links') &&
461 // and is configured to enforce the login
462 $conf->get('privacy.force_login') &&
463 // and the current page isn't already the login page
464 $targetPage !== Router::$PAGE_LOGIN &&
465 // and the user is not requesting a feed (which would lead to a different content-type as expected)
466 $targetPage !== Router::$PAGE_FEED_ATOM &&
467 $targetPage !== Router::$PAGE_FEED_RSS
468 ) {
469 // force current page to be the login page
470 $targetPage = Router::$PAGE_LOGIN;
471 }
472
6fc14d53
A
473 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
474 // Then assign generated data to RainTPL.
475 $common_hooks = array(
fea5db7a 476 'includes',
6fc14d53
A
477 'header',
478 'footer',
6fc14d53 479 );
278d9ee2 480
93bf0918 481 foreach ($common_hooks as $name) {
6fc14d53 482 $plugin_data = array();
93bf0918
V
483 $pluginManager->executeHooks(
484 'render_' . $name,
485 $plugin_data,
6fc14d53
A
486 array(
487 'target' => $targetPage,
63ea23c2 488 'loggedin' => $loginManager->isLoggedIn()
6fc14d53
A
489 )
490 );
491 $PAGE->assign('plugins_' . $name, $plugin_data);
492 }
493
45034273 494 // -------- Display login form.
93bf0918 495 if ($targetPage == Router::$PAGE_LOGIN) {
6c50a6cc 496 header('Location: ./login');
45034273
SS
497 exit;
498 }
499 // -------- User wants to logout.
93bf0918 500 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) {
8e47af2b 501 header('Location: ./logout');
45034273
SS
502 exit;
503 }
504
505 // -------- Picture wall
93bf0918 506 if ($targetPage == Router::$PAGE_PICWALL) {
485b168a 507 header('Location: ./picture-wall');
45034273
SS
508 exit;
509 }
510
511 // -------- Tag cloud
93bf0918 512 if ($targetPage == Router::$PAGE_TAGCLOUD) {
c266a89d 513 header('Location: ./tag-cloud');
bb8f712d 514 exit;
45034273
SS
515 }
516
49cc8e5d 517 // -------- Tag list
93bf0918 518 if ($targetPage == Router::$PAGE_TAGLIST) {
60ae2412 519 header('Location: ./tag-list');
aa4797ba
A
520 exit;
521 }
522
38603b24
A
523 // Daily page.
524 if ($targetPage == Router::$PAGE_DAILY) {
69e29ff6
A
525 header('Location: ./daily');
526 exit;
38603b24
A
527 }
528
82e36802
A
529 // ATOM and RSS feed.
530 if ($targetPage == Router::$PAGE_FEED_ATOM || $targetPage == Router::$PAGE_FEED_RSS) {
531 $feedType = $targetPage == Router::$PAGE_FEED_RSS ? FeedBuilder::$FEED_RSS : FeedBuilder::$FEED_ATOM;
532 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
533
534 // Cache system
535 $query = $_SERVER['QUERY_STRING'];
536 $cache = new CachedPage(
894a3c4b 537 $conf->get('resource.page_cache'),
82e36802 538 page_url($_SERVER),
93bf0918 539 startsWith($query, 'do='. $targetPage) && !$loginManager->isLoggedIn()
82e36802
A
540 );
541 $cached = $cache->cachedVersion();
5f143b72 542 if (!empty($cached)) {
82e36802
A
543 echo $cached;
544 exit;
545 }
69c474b9 546
a39acb25 547 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
82e36802 548 // Generate data.
cf92b4dd
A
549 $feedGenerator = new FeedBuilder(
550 $bookmarkService,
e26e2060 551 $factory->getFormatter(),
cf92b4dd
A
552 $feedType,
553 $_SERVER,
554 $_GET,
555 $loginManager->isLoggedIn()
556 );
82e36802 557 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0)));
63ea23c2 558 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
894a3c4b 559 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
82e36802
A
560 $data = $feedGenerator->buildData();
561
562 // Process plugin hook.
82e36802 563 $pluginManager->executeHooks('render_feed', $data, array(
63ea23c2 564 'loggedin' => $loginManager->isLoggedIn(),
82e36802
A
565 'target' => $targetPage,
566 ));
567
568 // Render the template.
569 $PAGE->assignAll($data);
570 $PAGE->renderPage('feed.'. $feedType);
571 $cache->cache(ob_get_contents());
572 ob_end_flush();
573 exit;
e67712ba
A
574 }
575
18e67967 576 // Display opensearch plugin (XML)
8f8113b9
A
577 if ($targetPage == Router::$PAGE_OPENSEARCH) {
578 header('Content-Type: application/xml; charset=utf-8');
579 $PAGE->assign('serverurl', index_url($_SERVER));
580 $PAGE->renderPage('opensearch');
581 exit;
582 }
583
45034273 584 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
93bf0918 585 if (isset($_GET['addtag'])) {
45034273 586 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
93bf0918
V
587 if (empty($_SERVER['HTTP_REFERER'])) {
588 // In case browser does not send HTTP_REFERER
589 header('Location: ?searchtags='.urlencode($_GET['addtag']));
590 exit;
591 }
592 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
732e683b 593
775803a0
A
594 // Prevent redirection loop
595 if (isset($params['addtag'])) {
596 unset($params['addtag']);
597 }
598
732e683b
FE
599 // Check if this tag is already in the search query and ignore it if it is.
600 // Each tag is always separated by a space
6ac95d9c
A
601 if (isset($params['searchtags'])) {
602 $current_tags = explode(' ', $params['searchtags']);
603 } else {
604 $current_tags = array();
605 }
732e683b
FE
606 $addtag = true;
607 foreach ($current_tags as $value) {
608 if ($value === $_GET['addtag']) {
609 $addtag = false;
610 break;
611 }
612 }
613 // Append the tag if necessary
614 if (empty($params['searchtags'])) {
615 $params['searchtags'] = trim($_GET['addtag']);
93bf0918 616 } elseif ($addtag) {
732e683b
FE
617 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
618 }
619
9d9f6d75
V
620 // We also remove page (keeping the same page has no sense, since the
621 // results are different)
622 unset($params['page']);
623
45034273
SS
624 header('Location: ?'.http_build_query($params));
625 exit;
626 }
627
628 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
775803a0 629 if (isset($_GET['removetag'])) {
45034273 630 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
775803a0
A
631 if (empty($_SERVER['HTTP_REFERER'])) {
632 header('Location: ?');
633 exit;
634 }
635
636 // In case browser does not send HTTP_REFERER
637 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
638
639 // Prevent redirection loop
640 if (isset($params['removetag'])) {
641 unset($params['removetag']);
642 }
643
644 if (isset($params['searchtags'])) {
822bffce 645 $tags = explode(' ', $params['searchtags']);
2c75f8e7
A
646 // Remove value from array $tags.
647 $tags = array_diff($tags, array($_GET['removetag']));
93bf0918 648 $params['searchtags'] = implode(' ', $tags);
2c75f8e7
A
649
650 if (empty($params['searchtags'])) {
775803a0 651 unset($params['searchtags']);
775803a0 652 }
2c75f8e7 653
9d9f6d75
V
654 // We also remove page (keeping the same page has no sense, since
655 // the results are different)
656 unset($params['page']);
45034273
SS
657 }
658 header('Location: ?'.http_build_query($params));
659 exit;
660 }
661
cf92b4dd 662 // -------- User wants to change the number of bookmarks per page (linksperpage=...)
775803a0
A
663 if (isset($_GET['linksperpage'])) {
664 if (is_numeric($_GET['linksperpage'])) {
665 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
666 }
667
8bbf02e0
A
668 if (! empty($_SERVER['HTTP_REFERER'])) {
669 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
670 } else {
671 $location = '?';
672 }
673 header('Location: '. $location);
45034273
SS
674 exit;
675 }
bb8f712d 676
cf92b4dd 677 // -------- User wants to see only private bookmarks (toggle)
9d4736a3 678 if (isset($_GET['visibility'])) {
9d4736a3 679 if ($_GET['visibility'] === 'private') {
d2f6d909
A
680 // Visibility not set or not already private, set private, otherwise reset it
681 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
cf92b4dd 682 // See only private bookmarks
d2f6d909
A
683 $_SESSION['visibility'] = 'private';
684 } else {
685 unset($_SESSION['visibility']);
686 }
d2d4f993 687 } elseif ($_GET['visibility'] === 'public') {
d2f6d909 688 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
cf92b4dd 689 // See only public bookmarks
d2f6d909
A
690 $_SESSION['visibility'] = 'public';
691 } else {
692 unset($_SESSION['visibility']);
693 }
45034273 694 }
775803a0 695
8bbf02e0 696 if (! empty($_SERVER['HTTP_REFERER'])) {
9d4736a3 697 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
8bbf02e0
A
698 } else {
699 $location = '?';
700 }
701 header('Location: '. $location);
45034273
SS
702 exit;
703 }
704
cf92b4dd 705 // -------- User wants to see only untagged bookmarks (toggle)
f210d94f 706 if (isset($_GET['untaggedonly'])) {
c4925c1f 707 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
f210d94f
LC
708
709 if (! empty($_SERVER['HTTP_REFERER'])) {
710 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
711 } else {
712 $location = '?';
713 }
714 header('Location: '. $location);
715 exit;
716 }
717
45034273 718 // -------- Handle other actions allowed for non-logged in users:
93bf0918 719 if (!$loginManager->isLoggedIn()) {
ad6c27b7 720 // User tries to post new link but is not logged in:
45034273 721 // Show login screen, then redirect to ?post=...
93bf0918 722 if (isset($_GET['post'])) {
0b04f797 723 header( // Redirect to login page, then back to post link.
72caf4e8 724 'Location: ./login?post='.urlencode($_GET['post']).
0b04f797 725 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
726 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
727 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
728 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
729 );
45034273
SS
730 exit;
731 }
aedc912d 732
cf92b4dd 733 showLinkList($PAGE, $bookmarkService, $conf, $pluginManager, $loginManager);
5fbabbb9 734 if (isset($_GET['edit_link'])) {
72caf4e8 735 header('Location: ./login?edit_link='. escape($_GET['edit_link']));
5fbabbb9
A
736 exit;
737 }
738
ad6c27b7 739 exit; // Never remove this one! All operations below are reserved for logged in user.
45034273
SS
740 }
741
742 // -------- All other functions are reserved for the registered user:
743
744 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
93bf0918 745 if ($targetPage == Router::$PAGE_TOOLS) {
a3130d2c 746 $data = [
6fc14d53 747 'pageabsaddr' => index_url($_SERVER),
a3130d2c
A
748 'sslenabled' => is_https($_SERVER),
749 ];
6fc14d53
A
750 $pluginManager->executeHooks('render_tools', $data);
751
752 foreach ($data as $key => $value) {
753 $PAGE->assign($key, $value);
754 }
755
980efd6c 756 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
757 $PAGE->renderPage('tools');
758 exit;
759 }
760
761 // -------- User wants to change his/her password.
93bf0918 762 if ($targetPage == Router::$PAGE_CHANGEPASSWORD) {
894a3c4b 763 if ($conf->get('security.open_shaarli')) {
12266213 764 die(t('You are not supposed to change a password on an Open Shaarli.'));
684e662a
A
765 }
766
93bf0918
V
767 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) {
768 if (!$sessionManager->checkToken($_POST['token'])) {
769 die(t('Wrong token.')); // Go away!
770 }
45034273
SS
771
772 // Make sure old password is correct.
9d9f6d75
V
773 $oldhash = sha1(
774 $_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt')
775 );
776 if ($oldhash != $conf->get('credentials.hash')) {
777 echo '<script>alert("'
778 . t('The old password is not correct.')
bee33239 779 .'");document.location=\'./?do=changepasswd\';</script>';
ebd650c0 780 exit;
12266213 781 }
45034273 782 // Save new password
684e662a 783 // Salt renders rainbow-tables attacks useless.
da10377b 784 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
9d9f6d75
V
785 $conf->set(
786 'credentials.hash',
787 sha1(
788 $_POST['setpassword']
789 . $conf->get('credentials.login')
790 . $conf->get('credentials.salt')
791 )
792 );
dd484b90 793 try {
63ea23c2 794 $conf->write($loginManager->isLoggedIn());
93bf0918 795 } catch (Exception $e) {
dd484b90
A
796 error_log(
797 'ERROR while writing config file after changing password.' . PHP_EOL .
798 $e->getMessage()
799 );
800
801 // TODO: do not handle exceptions/errors in JS.
bee33239 802 echo '<script>alert("'. $e->getMessage() .'");document.location=\'./?do=tools\';</script>';
dd484b90
A
803 exit;
804 }
bee33239 805 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'./?do=tools\';</script>';
45034273 806 exit;
93bf0918
V
807 } else {
808 // show the change password form.
980efd6c 809 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
810 $PAGE->renderPage('changepassword');
811 exit;
812 }
813 }
814
815 // -------- User wants to change configuration
93bf0918
V
816 if ($targetPage == Router::$PAGE_CONFIGURE) {
817 if (!empty($_POST['title'])) {
ebd650c0 818 if (!$sessionManager->checkToken($_POST['token'])) {
12266213 819 die(t('Wrong token.')); // Go away!
12ff86c9 820 }
45034273 821 $tz = 'UTC';
12ff86c9
A
822 if (!empty($_POST['continent']) && !empty($_POST['city'])
823 && isTimeZoneValid($_POST['continent'], $_POST['city'])
824 ) {
825 $tz = $_POST['continent'] . '/' . $_POST['city'];
826 }
da10377b 827 $conf->set('general.timezone', $tz);
7f179985
A
828 $conf->set('general.title', escape($_POST['title']));
829 $conf->set('general.header_link', escape($_POST['titleLink']));
6a487252 830 $conf->set('general.retrieve_description', !empty($_POST['retrieveDescription']));
adc4aee8 831 $conf->set('resource.theme', escape($_POST['theme']));
da10377b 832 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
894a3c4b
A
833 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
834 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
835 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
836 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
76be95e1 837 $conf->set('api.enabled', !empty($_POST['enableApi']));
cbfdcff2 838 $conf->set('api.secret', escape($_POST['apiSecret']));
cf92b4dd
A
839 $conf->set('formatter', escape($_POST['formatter']));
840
841 if (! empty($_POST['language'])) {
842 $conf->set('translation.language', escape($_POST['language']));
843 }
f39580c6 844
b302b3c5 845 $thumbnailsMode = extension_loaded('gd') ? $_POST['enableThumbnails'] : Thumbnailer::MODE_NONE;
7b4fea0e
A
846 if ($thumbnailsMode !== Thumbnailer::MODE_NONE
847 && $thumbnailsMode !== $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE)
848 ) {
28f26524 849 $_SESSION['warnings'][] = t(
9d9f6d75 850 'You have enabled or changed thumbnails mode. '
bee33239 851 .'<a href="./?do=thumbs_update">Please synchronize them</a>.'
28f26524
A
852 );
853 }
b302b3c5 854 $conf->set('thumbnails.mode', $thumbnailsMode);
f39580c6 855
dd484b90 856 try {
63ea23c2 857 $conf->write($loginManager->isLoggedIn());
4306b184 858 $history->updateSettings();
b0428aa9 859 $pageCacheManager->invalidateCaches();
93bf0918 860 } catch (Exception $e) {
dd484b90
A
861 error_log(
862 'ERROR while writing config file after configuration update.' . PHP_EOL .
863 $e->getMessage()
864 );
865
866 // TODO: do not handle exceptions/errors in JS.
bee33239 867 echo '<script>alert("'. $e->getMessage() .'");document.location=\'./?do=configure\';</script>';
dd484b90
A
868 exit;
869 }
bee33239 870 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'./?do=configure\';</script>';
45034273 871 exit;
93bf0918
V
872 } else {
873 // Show the configuration form.
da10377b 874 $PAGE->assign('title', $conf->get('general.title'));
adc4aee8 875 $PAGE->assign('theme', $conf->get('resource.theme'));
a0df0651 876 $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl')));
cf92b4dd 877 $PAGE->assign('formatter_available', ['default', 'markdown']);
ae3aa968
A
878 list($continents, $cities) = generateTimeZoneData(
879 timezone_identifiers_list(),
880 $conf->get('general.timezone')
881 );
882 $PAGE->assign('continents', $continents);
883 $PAGE->assign('cities', $cities);
6a487252 884 $PAGE->assign('retrieve_description', $conf->get('general.retrieve_description'));
894a3c4b 885 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
2e193ad3 886 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
894a3c4b
A
887 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
888 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
889 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
cbfdcff2
A
890 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
891 $PAGE->assign('api_secret', $conf->get('api.secret'));
f39580c6 892 $PAGE->assign('languages', Languages::getAvailableLanguages());
787faa42 893 $PAGE->assign('gd_enabled', extension_loaded('gd'));
b302b3c5 894 $PAGE->assign('thumbnails_mode', $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE));
980efd6c 895 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
896 $PAGE->renderPage('configure');
897 exit;
898 }
899 }
900
901 // -------- User wants to rename a tag or delete it
93bf0918 902 if ($targetPage == Router::$PAGE_CHANGETAG) {
6a6aa2b9 903 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
aa4797ba 904 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
980efd6c 905 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
906 $PAGE->renderPage('changetag');
907 exit;
908 }
6a6aa2b9 909
ebd650c0 910 if (!$sessionManager->checkToken($_POST['token'])) {
12266213 911 die(t('Wrong token.'));
6a6aa2b9 912 }
45034273 913
4fa9a3c5 914 $toTag = isset($_POST['totag']) ? escape($_POST['totag']) : null;
cf92b4dd
A
915 $fromTag = escape($_POST['fromtag']);
916 $count = 0;
917 $bookmarks = $bookmarkService->search(['searchtags' => $fromTag], BookmarkFilter::$ALL, true);
918 foreach ($bookmarks as $bookmark) {
919 if ($toTag) {
920 $bookmark->renameTag($fromTag, $toTag);
921 } else {
922 $bookmark->deleteTag($fromTag);
923 }
924 $bookmarkService->set($bookmark, false);
925 $history->updateLink($bookmark);
926 $count++;
45034273 927 }
cf92b4dd 928 $bookmarkService->save();
3b67b222 929 $delete = empty($_POST['totag']);
bee33239 930 $redirect = $delete ? './do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
d99aef53 931 $alert = $delete
cf92b4dd
A
932 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d bookmarks.', $count), $count)
933 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d bookmarks.', $count), $count);
d99aef53
A
934 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
935 exit;
45034273
SS
936 }
937
ad6c27b7 938 // -------- User wants to add a link without using the bookmarklet: Show form.
93bf0918 939 if ($targetPage == Router::$PAGE_ADDLINK) {
980efd6c 940 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
941 $PAGE->renderPage('addlink');
942 exit;
943 }
944
945 // -------- User clicked the "Save" button when editing a link: Save link to database.
93bf0918 946 if (isset($_POST['save_edit'])) {
5a23950c 947 // Go away!
ebd650c0 948 if (! $sessionManager->checkToken($_POST['token'])) {
12266213 949 die(t('Wrong token.'));
5a23950c 950 }
01878a75
A
951
952 // lf_id should only be present if the link exists.
cf92b4dd
A
953 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : null;
954 if ($id && $bookmarkService->exists($id)) {
01878a75 955 // Edit
cf92b4dd 956 $bookmark = $bookmarkService->get($id);
01878a75
A
957 } else {
958 // New link
cf92b4dd 959 $bookmark = new Bookmark();
c27f2f36 960 }
5a23950c 961
cf92b4dd
A
962 $bookmark->setTitle($_POST['lf_title']);
963 $bookmark->setDescription($_POST['lf_description']);
964 $bookmark->setUrl($_POST['lf_url'], $conf->get('security.allowed_protocols'));
965 $bookmark->setPrivate(isset($_POST['lf_private']));
966 $bookmark->setTagsString($_POST['lf_tags']);
6fc14d53 967
a8e7da01 968 if ($conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE
cf92b4dd 969 && ! $bookmark->isNote()
a8e7da01 970 ) {
1b93137e 971 $thumbnailer = new Thumbnailer($conf);
cf92b4dd 972 $bookmark->setThumbnail($thumbnailer->get($bookmark->getUrl()));
1b93137e 973 }
cf92b4dd 974 $bookmarkService->addOrSet($bookmark, false);
1b93137e 975
cf92b4dd 976 // To preserve backward compatibility with 3rd parties, plugins still use arrays
a39acb25 977 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
cf92b4dd
A
978 $formatter = $factory->getFormatter('raw');
979 $data = $formatter->format($bookmark);
980 $pluginManager->executeHooks('save_link', $data);
6fc14d53 981
cf92b4dd
A
982 $bookmark->fromArray($data);
983 $bookmarkService->set($bookmark);
45034273
SS
984
985 // If we are called from the bookmarklet, we must close the popup:
d01c2342
A
986 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
987 echo '<script>self.close();</script>';
988 exit;
989 }
990
fd50e14c 991 $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?';
775803a0 992 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
5a23950c 993 // Scroll to the link which has been edited.
cf92b4dd 994 $location .= '#' . $bookmark->getShortUrl();
5a23950c
A
995 // After saving the link, redirect to the page the user was on.
996 header('Location: '. $location);
45034273
SS
997 exit;
998 }
999
ad6c27b7 1000 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
93bf0918 1001 if ($targetPage == Router::$PAGE_DELETELINK) {
ebd650c0 1002 if (! $sessionManager->checkToken($_GET['token'])) {
12266213 1003 die(t('Wrong token.'));
f4ebd5fe 1004 }
01878a75 1005
a74f52a8
WE
1006 $ids = trim($_GET['lf_linkdate']);
1007 if (strpos($ids, ' ') !== false) {
1008 // multiple, space-separated ids provided
cf92b4dd
A
1009 $ids = array_values(array_filter(
1010 preg_split('/\s+/', escape($ids)),
1011 function ($item) {
1012 return $item !== '';
1013 }
1014 ));
29a837f3 1015 } else {
a74f52a8 1016 // only a single id provided
cf92b4dd 1017 $shortUrl = $bookmarkService->get($ids)->getShortUrl();
a74f52a8
WE
1018 $ids = [$ids];
1019 }
1020 // assert at least one id is given
93bf0918 1021 if (!count($ids)) {
a74f52a8 1022 die('no id provided');
29a837f3 1023 }
a39acb25 1024 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
cf92b4dd 1025 $formatter = $factory->getFormatter('raw');
29a837f3
A
1026 foreach ($ids as $id) {
1027 $id = (int) escape($id);
cf92b4dd
A
1028 $bookmark = $bookmarkService->get($id);
1029 $data = $formatter->format($bookmark);
1030 $pluginManager->executeHooks('delete_link', $data);
1031 $bookmarkService->remove($bookmark, false);
29a837f3 1032 }
cf92b4dd 1033 $bookmarkService->save();
45034273
SS
1034
1035 // If we are called from the bookmarklet, we must close the popup:
93bf0918
V
1036 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1037 echo '<script>self.close();</script>';
1038 exit;
1039 }
95e5add4
A
1040
1041 $location = '?';
1042 if (isset($_SERVER['HTTP_REFERER'])) {
1043 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1044 $location = generateLocation(
93bf0918
V
1045 $_SERVER['HTTP_REFERER'],
1046 $_SERVER['HTTP_HOST'],
cf92b4dd 1047 ['delete_link', 'edit_link', ! empty($shortUrl) ? $shortUrl : null]
95e5add4 1048 );
d528433d 1049 }
1050
1051 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
45034273
SS
1052 exit;
1053 }
1054
8d03f705
A
1055 // -------- User clicked either "Set public" or "Set private" bulk operation
1056 if ($targetPage == Router::$PAGE_CHANGE_VISIBILITY) {
1057 if (! $sessionManager->checkToken($_GET['token'])) {
1058 die(t('Wrong token.'));
1059 }
1060
1061 $ids = trim($_GET['ids']);
1062 if (strpos($ids, ' ') !== false) {
1063 // multiple, space-separated ids provided
1064 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1065 } else {
1066 // only a single id provided
1067 $ids = [$ids];
1068 }
1069
1070 // assert at least one id is given
1071 if (!count($ids)) {
1072 die('no id provided');
1073 }
1074 // assert that the visibility is valid
1075 if (!isset($_GET['newVisibility']) || !in_array($_GET['newVisibility'], ['public', 'private'])) {
1076 die('invalid visibility');
1077 } else {
1078 $private = $_GET['newVisibility'] === 'private';
1079 }
a39acb25 1080 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
cf92b4dd 1081 $formatter = $factory->getFormatter('raw');
8d03f705
A
1082 foreach ($ids as $id) {
1083 $id = (int) escape($id);
cf92b4dd
A
1084 $bookmark = $bookmarkService->get($id);
1085 $bookmark->setPrivate($private);
1086
1087 // To preserve backward compatibility with 3rd parties, plugins still use arrays
1088 $data = $formatter->format($bookmark);
1089 $pluginManager->executeHooks('save_link', $data);
1090 $bookmark->fromArray($data);
1091
1092 $bookmarkService->set($bookmark);
8d03f705 1093 }
cf92b4dd 1094 $bookmarkService->save();
8d03f705
A
1095
1096 $location = '?';
1097 if (isset($_SERVER['HTTP_REFERER'])) {
1098 $location = generateLocation(
1099 $_SERVER['HTTP_REFERER'],
1100 $_SERVER['HTTP_HOST']
1101 );
1102 }
1103 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
45034273
SS
1104 exit;
1105 }
1106
1107 // -------- User clicked the "EDIT" button on a link: Display link edit form.
93bf0918 1108 if (isset($_GET['edit_link'])) {
01878a75 1109 $id = (int) escape($_GET['edit_link']);
cf92b4dd
A
1110 try {
1111 $link = $bookmarkService->get($id); // Read database
1112 } catch (BookmarkNotFoundException $e) {
1113 // Link not found in database.
93bf0918
V
1114 header('Location: ?');
1115 exit;
cf92b4dd
A
1116 }
1117
a39acb25 1118 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
cf92b4dd
A
1119 $formatter = $factory->getFormatter('raw');
1120 $formattedLink = $formatter->format($link);
a39acb25
A
1121 $tags = $bookmarkService->bookmarksCountPerTag();
1122 if ($conf->get('formatter') === 'markdown') {
1123 $tags[BookmarkMarkdownFormatter::NO_MD_TAG] = 1;
1124 }
6fc14d53 1125 $data = array(
cf92b4dd 1126 'link' => $formattedLink,
6fc14d53 1127 'link_is_new' => false,
6fc14d53 1128 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
a39acb25 1129 'tags' => $tags,
6fc14d53
A
1130 );
1131 $pluginManager->executeHooks('render_editlink', $data);
1132
1133 foreach ($data as $key => $value) {
1134 $PAGE->assign($key, $value);
1135 }
1136
980efd6c 1137 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1138 $PAGE->renderPage('editlink');
1139 exit;
1140 }
1141
1142 // -------- User want to post a new link: Display link edit form.
d9d776af 1143 if (isset($_GET['post'])) {
ce7b0b64 1144 $url = cleanup_url($_GET['post']);
45034273
SS
1145
1146 $link_is_new = false;
9e1724f1 1147 // Check if URL is not already in database (in this case, we will edit the existing link)
cf92b4dd
A
1148 $bookmark = $bookmarkService->findByUrl($url);
1149 if (! $bookmark) {
9e1724f1 1150 $link_is_new = true;
9e1724f1 1151 // Get title if it was provided in URL (by the bookmarklet).
739dc243 1152 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
9e1724f1 1153 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
739dc243
A
1154 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1155 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1156 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
9d9f6d75
V
1157
1158 // If this is an HTTP(S) link, we try go get the page to extract
1159 // the title (otherwise we will to straight to the edit form.)
ef591e7e 1160 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
6a487252 1161 $retrieveDescription = $conf->get('general.retrieve_description');
451314eb 1162 // Short timeout to keep the application responsive
d65342e3 1163 // The callback will fill $charset and $title with data from the downloaded page.
4ff3ed1c
A
1164 get_http_response(
1165 $url,
4ff3ed1c 1166 $conf->get('general.download_timeout', 30),
8d2cac1b 1167 $conf->get('general.download_max_size', 4194304),
6a487252 1168 get_curl_download_callback($charset, $title, $description, $tags, $retrieveDescription)
4ff3ed1c 1169 );
d65342e3
A
1170 if (! empty($title) && strtolower($charset) != 'utf-8') {
1171 $title = mb_convert_encoding($title, 'utf-8', $charset);
9e1724f1 1172 }
45034273 1173 }
1557cefb 1174
9e1724f1 1175 if ($url == '') {
f39580c6 1176 $title = $conf->get('general.default_note_title', t('Note: '));
27646ca5 1177 }
ce7b0b64
A
1178 $url = escape($url);
1179 $title = escape($title);
1557cefb 1180
cf92b4dd 1181 $link = [
9e1724f1 1182 'title' => $title,
ef591e7e 1183 'url' => $url,
9e1724f1
A
1184 'description' => $description,
1185 'tags' => $tags,
807cade6 1186 'private' => $private,
cf92b4dd 1187 ];
01878a75 1188 } else {
a39acb25
A
1189 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
1190 $formatter = $factory->getFormatter('raw');
cf92b4dd 1191 $link = $formatter->format($bookmark);
45034273
SS
1192 }
1193
a39acb25
A
1194 $tags = $bookmarkService->bookmarksCountPerTag();
1195 if ($conf->get('formatter') === 'markdown') {
1196 $tags[BookmarkMarkdownFormatter::NO_MD_TAG] = 1;
1197 }
cf92b4dd 1198 $data = [
6fc14d53
A
1199 'link' => $link,
1200 'link_is_new' => $link_is_new,
6fc14d53
A
1201 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1202 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
a39acb25 1203 'tags' => $tags,
cdbc8180 1204 'default_private_links' => $conf->get('privacy.default_private_links', false),
cf92b4dd 1205 ];
6fc14d53
A
1206 $pluginManager->executeHooks('render_editlink', $data);
1207
1208 foreach ($data as $key => $value) {
1209 $PAGE->assign($key, $value);
1210 }
1211
980efd6c 1212 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1213 $PAGE->renderPage('editlink');
1214 exit;
1215 }
1216
4154c25b 1217 if ($targetPage == Router::$PAGE_PINLINK) {
cf92b4dd 1218 if (! isset($_GET['id']) || !$bookmarkService->exists($_GET['id'])) {
4154c25b
A
1219 // FIXME! Use a proper error system.
1220 $msg = t('Invalid link ID provided');
1221 echo '<script>alert("'. $msg .'");document.location=\''. index_url($_SERVER) .'\';</script>';
1222 exit;
1223 }
1224 if (! $sessionManager->checkToken($_GET['token'])) {
1225 die('Wrong token.');
1226 }
1227
cf92b4dd
A
1228 $link = $bookmarkService->get($_GET['id']);
1229 $link->setSticky(! $link->isSticky());
1230 $bookmarkService->set($link);
4154c25b
A
1231 header('Location: '.index_url($_SERVER));
1232 exit;
1233 }
1234
cd5327be 1235 if ($targetPage == Router::$PAGE_EXPORT) {
cf92b4dd 1236 // Export bookmarks as a Netscape Bookmarks file
bb4a23aa 1237
cd5327be 1238 if (empty($_GET['selection'])) {
980efd6c 1239 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1240 $PAGE->renderPage('export');
1241 exit;
1242 }
45034273 1243
cd5327be
V
1244 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1245 $selection = $_GET['selection'];
bb4a23aa
V
1246 if (isset($_GET['prepend_note_url'])) {
1247 $prependNoteUrl = $_GET['prepend_note_url'];
1248 } else {
1249 $prependNoteUrl = false;
1250 }
1251
cd5327be 1252 try {
a39acb25 1253 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
e26e2060 1254 $formatter = $factory->getFormatter('raw');
cd5327be
V
1255 $PAGE->assign(
1256 'links',
bb4a23aa 1257 NetscapeBookmarkUtils::filterAndFormat(
cf92b4dd
A
1258 $bookmarkService,
1259 $formatter,
bb4a23aa
V
1260 $selection,
1261 $prependNoteUrl,
1262 index_url($_SERVER)
1263 )
cd5327be
V
1264 );
1265 } catch (Exception $exc) {
1266 header('Content-Type: text/plain; charset=utf-8');
1267 echo $exc->getMessage();
1268 exit;
45034273 1269 }
cd5327be
V
1270 $now = new DateTime();
1271 header('Content-Type: text/html; charset=utf-8');
1272 header(
1273 'Content-disposition: attachment; filename=bookmarks_'
cf92b4dd 1274 .$selection.'_'.$now->format(Bookmark::LINK_DATE_FORMAT).'.html'
cd5327be
V
1275 );
1276 $PAGE->assign('date', $now->format(DateTime::RFC822));
1277 $PAGE->assign('eol', PHP_EOL);
1278 $PAGE->assign('selection', $selection);
1279 $PAGE->renderPage('export.bookmarks');
1280 exit;
45034273
SS
1281 }
1282
a973afea
V
1283 if ($targetPage == Router::$PAGE_IMPORT) {
1284 // Upload a Netscape bookmark dump to import its contents
1285
1286 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1287 // Show import dialog
6a19124a
A
1288 $PAGE->assign(
1289 'maxfilesize',
1290 get_max_upload_size(
1291 ini_get('post_max_size'),
1292 ini_get('upload_max_filesize'),
1293 false
1294 )
1295 );
1296 $PAGE->assign(
1297 'maxfilesizeHuman',
1298 get_max_upload_size(
1299 ini_get('post_max_size'),
1300 ini_get('upload_max_filesize'),
1301 true
1302 )
1303 );
980efd6c 1304 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
a973afea 1305 $PAGE->renderPage('import');
45034273
SS
1306 exit;
1307 }
45034273 1308
a973afea
V
1309 // Import bookmarks from an uploaded file
1310 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1311 // The file is too big or some form field may be missing.
12266213
A
1312 $msg = sprintf(
1313 t(
1314 'The file you are trying to upload is probably bigger than what this webserver can accept'
1315 .' (%s). Please upload in smaller chunks.'
1316 ),
1317 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1318 );
bee33239 1319 echo '<script>alert("'. $msg .'");document.location=\'./?do='.Router::$PAGE_IMPORT .'\';</script>';
a973afea
V
1320 exit;
1321 }
ebd650c0 1322 if (! $sessionManager->checkToken($_POST['token'])) {
a973afea
V
1323 die('Wrong token.');
1324 }
1325 $status = NetscapeBookmarkUtils::import(
1326 $_POST,
1327 $_FILES,
cf92b4dd 1328 $bookmarkService,
4306b184
A
1329 $conf,
1330 $history
a973afea 1331 );
bee33239 1332 echo '<script>alert("'.$status.'");document.location=\'./?do='
a973afea 1333 .Router::$PAGE_IMPORT .'\';</script>';
45034273
SS
1334 exit;
1335 }
1336
dea0ba28
A
1337 // Plugin administration page
1338 if ($targetPage == Router::$PAGE_PLUGINSADMIN) {
1339 $pluginMeta = $pluginManager->getPluginsMeta();
1340
1341 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
93bf0918
V
1342 $enabledPlugins = array_filter($pluginMeta, function ($v) {
1343 return $v['order'] !== false;
1344 });
dea0ba28 1345 // Load parameters.
684e662a 1346 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
dea0ba28
A
1347 uasort(
1348 $enabledPlugins,
93bf0918
V
1349 function ($a, $b) {
1350 return $a['order'] - $b['order'];
1351 }
dea0ba28 1352 );
93bf0918
V
1353 $disabledPlugins = array_filter($pluginMeta, function ($v) {
1354 return $v['order'] === false;
1355 });
dea0ba28
A
1356
1357 $PAGE->assign('enabledPlugins', $enabledPlugins);
1358 $PAGE->assign('disabledPlugins', $disabledPlugins);
980efd6c 1359 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
dea0ba28
A
1360 $PAGE->renderPage('pluginsadmin');
1361 exit;
1362 }
1363
1364 // Plugin administration form action
1365 if ($targetPage == Router::$PAGE_SAVE_PLUGINSADMIN) {
1366 try {
1367 if (isset($_POST['parameters_form'])) {
a5a0c039 1368 $pluginManager->executeHooks('save_plugin_parameters', $_POST);
dea0ba28
A
1369 unset($_POST['parameters_form']);
1370 foreach ($_POST as $param => $value) {
684e662a 1371 $conf->set('plugins.'. $param, escape($value));
dea0ba28 1372 }
93bf0918 1373 } else {
da10377b 1374 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
dea0ba28 1375 }
63ea23c2 1376 $conf->write($loginManager->isLoggedIn());
b86aeccf 1377 $history->updateSettings();
93bf0918 1378 } catch (Exception $e) {
dea0ba28
A
1379 error_log(
1380 'ERROR while saving plugin configuration:.' . PHP_EOL .
1381 $e->getMessage()
1382 );
1383
1384 // TODO: do not handle exceptions/errors in JS.
9d9f6d75
V
1385 echo '<script>alert("'
1386 . $e->getMessage()
bee33239 1387 .'");document.location=\'./?do='
9d9f6d75
V
1388 . Router::$PAGE_PLUGINSADMIN
1389 .'\';</script>';
dea0ba28
A
1390 exit;
1391 }
bee33239 1392 header('Location: ./?do='. Router::$PAGE_PLUGINSADMIN);
dea0ba28
A
1393 exit;
1394 }
1395
986a5210
A
1396 // Get a fresh token
1397 if ($targetPage == Router::$GET_TOKEN) {
1398 header('Content-Type:text/plain');
cf92b4dd 1399 echo $sessionManager->generateToken();
986a5210
A
1400 exit;
1401 }
1402
28f26524
A
1403 // -------- Thumbnails Update
1404 if ($targetPage == Router::$PAGE_THUMBS_UPDATE) {
1405 $ids = [];
cf92b4dd 1406 foreach ($bookmarkService->search() as $bookmark) {
28f26524 1407 // A note or not HTTP(S)
cf92b4dd 1408 if ($bookmark->isNote() || ! startsWith(strtolower($bookmark->getUrl()), 'http')) {
28f26524
A
1409 continue;
1410 }
cf92b4dd 1411 $ids[] = $bookmark->getId();
28f26524
A
1412 }
1413 $PAGE->assign('ids', $ids);
7b4fea0e 1414 $PAGE->assign('pagetitle', t('Thumbnails update') .' - '. $conf->get('general.title', 'Shaarli'));
28f26524
A
1415 $PAGE->renderPage('thumbnails');
1416 exit;
1417 }
1418
1419 // -------- Single Thumbnail Update
1420 if ($targetPage == Router::$AJAX_THUMB_UPDATE) {
1421 if (! isset($_POST['id']) || ! ctype_digit($_POST['id'])) {
1422 http_response_code(400);
1423 exit;
1424 }
1425 $id = (int) $_POST['id'];
cf92b4dd 1426 if (! $bookmarkService->exists($id)) {
28f26524
A
1427 http_response_code(404);
1428 exit;
1429 }
1430 $thumbnailer = new Thumbnailer($conf);
cf92b4dd
A
1431 $bookmark = $bookmarkService->get($id);
1432 $bookmark->setThumbnail($thumbnailer->get($bookmark->getUrl()));
1433 $bookmarkService->set($bookmark);
28f26524 1434
a39acb25 1435 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
cf92b4dd 1436 echo json_encode($factory->getFormatter('raw')->format($bookmark));
28f26524
A
1437 exit;
1438 }
1439
cf92b4dd
A
1440 // -------- Otherwise, simply display search form and bookmarks:
1441 showLinkList($PAGE, $bookmarkService, $conf, $pluginManager, $loginManager);
45034273
SS
1442 exit;
1443}
1444
528a6f8a 1445/**
cf92b4dd 1446 * Template for the list of bookmarks (<div id="linklist">)
528a6f8a
A
1447 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1448 *
cf92b4dd
A
1449 * @param pageBuilder $PAGE pageBuilder instance.
1450 * @param BookmarkServiceInterface $linkDb LinkDB instance.
1451 * @param ConfigManager $conf Configuration Manager instance.
1452 * @param PluginManager $pluginManager Plugin Manager instance.
1453 * @param LoginManager $loginManager LoginManager instance
528a6f8a 1454 */
cf92b4dd 1455function buildLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager)
45034273 1456{
a39acb25 1457 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
cf92b4dd
A
1458 $formatter = $factory->getFormatter();
1459
528a6f8a 1460 // Used in templates
7d86f40b
A
1461 if (isset($_GET['searchtags'])) {
1462 if (! empty($_GET['searchtags'])) {
1463 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1464 } else {
1465 $searchtags = false;
1466 }
1467 } else {
1468 $searchtags = '';
1469 }
b3051a6a 1470 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
822bffce 1471
528a6f8a
A
1472 // Smallhash filter
1473 if (! empty($_SERVER['QUERY_STRING'])
1474 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1475 try {
cf92b4dd
A
1476 $linksToDisplay = $linkDb->findByHash($_SERVER['QUERY_STRING']);
1477 } catch (BookmarkNotFoundException $e) {
528a6f8a 1478 $PAGE->render404($e->getMessage());
45034273
SS
1479 exit;
1480 }
528a6f8a 1481 } else {
cf92b4dd 1482 // Filter bookmarks according search parameters.
4869d535 1483 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : null;
7d86f40b
A
1484 $request = [
1485 'searchtags' => $searchtags,
1486 'searchterm' => $searchterm,
1487 ];
cf92b4dd 1488 $linksToDisplay = $linkDb->search($request, $visibility, false, !empty($_SESSION['untaggedonly']));
45034273
SS
1489 }
1490
1491 // ---- Handle paging.
822bffce
A
1492 $keys = array();
1493 foreach ($linksToDisplay as $key => $value) {
1494 $keys[] = $key;
1495 }
45034273 1496
45034273 1497 // Select articles according to paging.
822bffce
A
1498 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1499 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1500 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1501 $page = $page < 1 ? 1 : $page;
1502 $page = $page > $pagecount ? $pagecount : $page;
1503 // Start index.
1504 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1505 $end = $i + $_SESSION['LINKS_PER_PAGE'];
1b93137e 1506
b302b3c5
A
1507 $thumbnailsEnabled = $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE;
1508 if ($thumbnailsEnabled) {
1b93137e
A
1509 $thumbnailer = new Thumbnailer($conf);
1510 }
1511
822bffce 1512 $linkDisp = array();
93bf0918 1513 while ($i<$end && $i<count($keys)) {
cf92b4dd 1514 $link = $formatter->format($linksToDisplay[$keys[$i]]);
1b93137e 1515
b5c368b8 1516 // Logged in, thumbnails enabled, not a note,
1b93137e 1517 // and (never retrieved yet or no valid cache file)
cf92b4dd
A
1518 if ($loginManager->isLoggedIn()
1519 && $thumbnailsEnabled
1520 && !$linksToDisplay[$keys[$i]]->isNote()
1521 && $linksToDisplay[$keys[$i]]->getThumbnail() !== false
1522 && ! is_file($linksToDisplay[$keys[$i]]->getThumbnail())
1b93137e 1523 ) {
cf92b4dd
A
1524 $linksToDisplay[$keys[$i]]->setThumbnail($thumbnailer->get($link['url']));
1525 $linkDb->set($linksToDisplay[$keys[$i]], false);
1b93137e 1526 $updateDB = true;
cf92b4dd 1527 $link['thumbnail'] = $linksToDisplay[$keys[$i]]->getThumbnail();
1b93137e
A
1528 }
1529
822bffce 1530 // Check for both signs of a note: starting with ? and 7 chars long.
cf92b4dd
A
1531// if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
1532// $link['url'] = index_url($_SERVER) . $link['url'];
1533// }
d33c5d4c 1534
45034273
SS
1535 $linkDisp[$keys[$i]] = $link;
1536 $i++;
1537 }
bb8f712d 1538
1b93137e
A
1539 // If we retrieved new thumbnails, we update the database.
1540 if (!empty($updateDB)) {
cf92b4dd 1541 $linkDb->save();
1b93137e
A
1542 }
1543
45034273 1544 // Compute paging navigation
7d86f40b 1545 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
c51fae92 1546 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
822bffce
A
1547 $previous_page_url = '';
1548 if ($i != count($keys)) {
c51fae92 1549 $previous_page_url = '?page=' . ($page+1) . $searchtermUrl . $searchtagsUrl;
822bffce
A
1550 }
1551 $next_page_url='';
1552 if ($page>1) {
c51fae92 1553 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
822bffce 1554 }
45034273 1555
45034273 1556 // Fill all template fields.
6fc14d53 1557 $data = array(
6fc14d53
A
1558 'previous_page_url' => $previous_page_url,
1559 'next_page_url' => $next_page_url,
1560 'page_current' => $page,
1561 'page_max' => $pagecount,
1562 'result_count' => count($linksToDisplay),
c51fae92
A
1563 'search_term' => $searchterm,
1564 'search_tags' => $searchtags,
9d4736a3 1565 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
6fc14d53 1566 'links' => $linkDisp,
6fc14d53 1567 );
97ef33bb
A
1568
1569 // If there is only a single link, we change on-the-fly the title of the page.
1570 if (count($linksToDisplay) == 1) {
cf92b4dd 1571 $data['pagetitle'] = $linksToDisplay[$keys[0]]->getTitle() .' - '. $conf->get('general.title');
980efd6c
A
1572 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1573 $data['pagetitle'] = t('Search: ');
1574 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1575 $bracketWrap = function ($tag) {
1576 return '['. $tag .']';
1577 };
1578 $data['pagetitle'] .= ! empty($searchtags)
1579 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1580 : '';
1581 $data['pagetitle'] .= '- '. $conf->get('general.title');
18cca483 1582 }
6fc14d53 1583
63ea23c2 1584 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
6fc14d53
A
1585
1586 foreach ($data as $key => $value) {
1587 $PAGE->assign($key, $value);
1588 }
1589
45034273
SS
1590 return;
1591}
1592
278d9ee2
A
1593/**
1594 * Installation
1595 * This function should NEVER be called if the file data/config.php exists.
1596 *
ebd650c0
V
1597 * @param ConfigManager $conf Configuration Manager instance.
1598 * @param SessionManager $sessionManager SessionManager instance
cad4251a 1599 * @param LoginManager $loginManager LoginManager instance
278d9ee2 1600 */
93bf0918
V
1601function install($conf, $sessionManager, $loginManager)
1602{
45034273 1603 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
93bf0918
V
1604 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
1605 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
1606 }
45034273 1607
f37664a2
SS
1608
1609 // This part makes sure sessions works correctly.
1610 // (Because on some hosts, session.save_path may not be set correctly,
1611 // or we may not have write access to it.)
9d9f6d75
V
1612 if (isset($_GET['test_session'])
1613 && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
12266213
A
1614 // Step 2: Check if data in session is correct.
1615 $msg = t(
1616 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1617 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1618 'and that you have write access to it.<br>'.
1619 'It currently points to %s.<br>'.
1620 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1621 'or any custom hostname without a dot causes cookie storage to fail. '.
1622 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1623 );
1624 $msg = sprintf($msg, session_save_path());
1625 echo $msg;
1626 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
f37664a2
SS
1627 die;
1628 }
93bf0918
V
1629 if (!isset($_SESSION['session_tested'])) {
1630 // Step 1 : Try to store data in session and reload page.
f37664a2 1631 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
482d67bd 1632 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
f37664a2 1633 }
93bf0918
V
1634 if (isset($_GET['test_session'])) {
1635 // Step 3: Sessions are OK. Remove test parameter from URL.
482d67bd 1636 header('Location: '.index_url($_SERVER));
f37664a2
SS
1637 }
1638
1639
93bf0918 1640 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
45034273 1641 $tz = 'UTC';
12ff86c9
A
1642 if (!empty($_POST['continent']) && !empty($_POST['city'])
1643 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1644 ) {
1645 $tz = $_POST['continent'].'/'.$_POST['city'];
d1e2f8e5 1646 }
da10377b 1647 $conf->set('general.timezone', $tz);
684e662a 1648 $login = $_POST['setlogin'];
da10377b 1649 $conf->set('credentials.login', $login);
684e662a 1650 $salt = sha1(uniqid('', true) .'_'. mt_rand());
da10377b
A
1651 $conf->set('credentials.salt', $salt);
1652 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
684e662a 1653 if (!empty($_POST['title'])) {
7f179985 1654 $conf->set('general.title', escape($_POST['title']));
684e662a 1655 } else {
cf92b4dd 1656 $conf->set('general.title', 'Shared bookmarks on '.escape(index_url($_SERVER)));
684e662a 1657 }
f39580c6 1658 $conf->set('translation.language', escape($_POST['language']));
894a3c4b 1659 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
cbfdcff2
A
1660 $conf->set('api.enabled', !empty($_POST['enableApi']));
1661 $conf->set(
1662 'api.secret',
1663 generate_api_secret(
e3a430ba
A
1664 $conf->get('credentials.login'),
1665 $conf->get('credentials.salt')
cbfdcff2
A
1666 )
1667 );
dd484b90 1668 try {
684e662a 1669 // Everything is ok, let's create config file.
63ea23c2 1670 $conf->write($loginManager->isLoggedIn());
93bf0918 1671 } catch (Exception $e) {
dd484b90 1672 error_log(
93bf0918 1673 'ERROR while writing config file after installation.' . PHP_EOL .
dd484b90 1674 $e->getMessage()
93bf0918 1675 );
dd484b90
A
1676
1677 // TODO: do not handle exceptions/errors in JS.
1678 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1679 exit;
1680 }
cf92b4dd
A
1681
1682 $history = new History($conf->get('resource.history'));
1683 $bookmarkService = new BookmarkFileService($conf, $history, true);
1684 if ($bookmarkService->count() === 0) {
1685 $bookmarkService->initialize();
1686 }
1687
9d9f6d75
V
1688 echo '<script>alert('
1689 .'"Shaarli is now configured. '
cf92b4dd 1690 .'Please enter your login/password and start shaaring your bookmarks!"'
9e4cc28e 1691 .');document.location=\'./login\';</script>';
45034273
SS
1692 exit;
1693 }
1694
28f26524 1695 $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
ae3aa968
A
1696 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1697 $PAGE->assign('continents', $continents);
1698 $PAGE->assign('cities', $cities);
f39580c6 1699 $PAGE->assign('languages', Languages::getAvailableLanguages());
45034273
SS
1700 $PAGE->renderPage('install');
1701 exit;
1702}
1703
684e662a 1704if (!isset($_SESSION['LINKS_PER_PAGE'])) {
da10377b 1705 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
684e662a 1706}
18e67967 1707
3b67b222
A
1708try {
1709 $history = new History($conf->get('resource.history'));
93bf0918 1710} catch (Exception $e) {
3b67b222
A
1711 die($e->getMessage());
1712}
1713
cf92b4dd
A
1714$linkDb = new BookmarkFileService($conf, $history, $loginManager->isLoggedIn());
1715
1716if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) {
1717 showDailyRSS($linkDb, $conf, $loginManager);
1718 exit;
1719}
18e67967 1720
8e47af2b 1721$containerBuilder = new ContainerBuilder($conf, $sessionManager, $loginManager, WEB_PATH);
6c50a6cc
A
1722$container = $containerBuilder->build();
1723$app = new App($container);
18e67967
A
1724
1725// REST API routes
93bf0918 1726$app->group('/api/v1', function () {
68016e37 1727 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
20433ea7
A
1728 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
1729 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
1730 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
1731 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
1732 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
d3f42ca4
A
1733
1734 $this->get('/tags', '\Shaarli\Api\Controllers\Tags:getTags')->setName('getTags');
1735 $this->get('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:getTag')->setName('getTag');
1736 $this->put('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:putTag')->setName('putTag');
1737 $this->delete('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:deleteTag')->setName('deleteTag');
1738
18d2d3ae 1739 $this->get('/history', '\Shaarli\Api\Controllers\HistoryController:getHistory')->setName('getHistory');
465b1c40 1740})->add('\Shaarli\Api\ApiMiddleware');
18e67967 1741
6c50a6cc
A
1742$app->group('', function () {
1743 $this->get('/login', '\Shaarli\Front\Controller\LoginController:index')->setName('login');
b0428aa9 1744 $this->get('/logout', '\Shaarli\Front\Controller\LogoutController:index')->setName('logout');
485b168a 1745 $this->get('/picture-wall', '\Shaarli\Front\Controller\PictureWallController:index')->setName('picwall');
3772298e 1746 $this->get('/tag-cloud', '\Shaarli\Front\Controller\TagCloudController:cloud')->setName('tagcloud');
60ae2412 1747 $this->get('/tag-list', '\Shaarli\Front\Controller\TagCloudController:list')->setName('taglist');
69e29ff6
A
1748 $this->get('/daily', '\Shaarli\Front\Controller\DailyController:index')->setName('daily');
1749
03340c18 1750 $this->get('/add-tag/{newTag}', '\Shaarli\Front\Controller\TagController:addTag')->setName('add-tag');
6c50a6cc
A
1751})->add('\Shaarli\Front\ShaarliMiddleware');
1752
18e67967 1753$response = $app->run(true);
5d9bc40d 1754
18e67967 1755// Hack to make Slim and Shaarli router work together:
16e3d006
A
1756// If a Slim route isn't found and NOT API call, we call renderPage().
1757if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
18e67967
A
1758 // We use UTF-8 for proper international characters handling.
1759 header('Content-Type: text/html; charset=utf-8');
44acf706 1760 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
18e67967 1761} else {
5d9bc40d
A
1762 $response = $response
1763 ->withHeader('Access-Control-Allow-Origin', '*')
1764 ->withHeader(
1765 'Access-Control-Allow-Headers',
1766 'X-Requested-With, Content-Type, Accept, Origin, Authorization'
1767 )
1768 ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
18e67967
A
1769 $app->respond($response);
1770}