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