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