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