]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - index.php
Refactor client session hijacking protection
[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"
cc8f572b
WE
51 ."- https://shaarli.readthedocs.io/en/master/Server-requirements/\n"
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';
12266213 78use \Shaarli\Languages;
a0df0651 79use \Shaarli\ThemeUtils;
3c66e564 80use \Shaarli\Config\ConfigManager;
44acf706 81use \Shaarli\LoginManager;
ebd650c0 82use \Shaarli\SessionManager;
ca74886f 83
d1e2f8e5
V
84// Ensure the PHP version is supported
85try {
3947bbb0 86 ApplicationUtils::checkPHPVersion('5.5', PHP_VERSION);
2e28269b 87} catch(Exception $exc) {
d1e2f8e5 88 header('Content-Type: text/plain; charset=utf-8');
2e28269b 89 echo $exc->getMessage();
d1e2f8e5
V
90 exit;
91}
92
b3e1f92e 93define('SHAARLI_VERSION', ApplicationUtils::getVersion(__DIR__ .'/'. ApplicationUtils::$VERSION_FILE));
b786c883 94
06b6660a
A
95// Force cookie path (but do not change lifetime)
96$cookie = session_get_cookie_params();
97$cookiedir = '';
98if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
99 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
100}
101// Set default cookie expiration and path.
102session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
103// Set session parameters on server side.
104// If the user does not access any page within this time, his/her session is considered expired.
105define('INACTIVITY_TIMEOUT', 3600); // in seconds.
106// Use cookies to store session.
107ini_set('session.use_cookies', 1);
108// Force cookies for session (phpsessionID forbidden in URL).
109ini_set('session.use_only_cookies', 1);
110// Prevent PHP form using sessionID in URL if cookies are disabled.
111ini_set('session.use_trans_sid', false);
112
06b6660a
A
113session_name('shaarli');
114// Start session if needed (Some server auto-start sessions).
115if (session_id() == '') {
116 session_start();
117}
118
68bc2135 119// Regenerate session ID if invalid or not defined in cookie.
fd7d8461 120if (isset($_COOKIE['shaarli']) && !SessionManager::checkId($_COOKIE['shaarli'])) {
68bc2135
V
121 session_regenerate_id(true);
122 $_COOKIE['shaarli'] = session_id();
123}
124
278d9ee2 125$conf = new ConfigManager();
44acf706 126$loginManager = new LoginManager($GLOBALS, $conf);
ebd650c0 127$sessionManager = new SessionManager($_SESSION, $conf);
12266213 128
b7c412d4
A
129// LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
130if (! defined('LC_MESSAGES')) {
131 define('LC_MESSAGES', LC_COLLATE);
132}
133
12266213
A
134// Sniff browser language and set date format accordingly.
135if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
136 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
137}
138
139new Languages(setlocale(LC_MESSAGES, 0), $conf);
140
7f179985 141$conf->setEmpty('general.timezone', date_default_timezone_get());
12266213 142$conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
adc4aee8 143RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
894a3c4b 144RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
45034273 145
278d9ee2 146$pluginManager = new PluginManager($conf);
da10377b 147$pluginManager->load($conf->get('general.enabled_plugins'));
6fc14d53 148
da10377b 149date_default_timezone_set($conf->get('general.timezone', 'UTC'));
d93d51b2 150
45034273
SS
151ob_start(); // Output buffering for the page cache.
152
45034273
SS
153// Prevent caching on client side or proxy: (yes, it's ugly)
154header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
155header("Cache-Control: no-store, no-cache, must-revalidate");
156header("Cache-Control: post-check=0, pre-check=0", false);
157header("Pragma: no-cache");
158
278d9ee2 159if (! is_file($conf->getConfigFileExt())) {
2e28269b 160 // Ensure Shaarli has proper access to its resources
278d9ee2 161 $errors = ApplicationUtils::checkResourcePermissions($conf);
2e28269b
V
162
163 if ($errors != array()) {
12266213 164 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
2e28269b
V
165
166 foreach ($errors as $error) {
167 $message .= '<li>'.$error.'</li>';
168 }
169 $message .= '</ul>';
170
171 header('Content-Type: text/html; charset=utf-8');
172 echo $message;
173 exit;
174 }
175
176 // Display the installation form if no existing config is found
ebd650c0 177 install($conf, $sessionManager);
50c9a12e 178}
8a80e4fe 179
ae00595b 180// a token depending of deployment salt, user password, and the current ip
da10377b 181define('STAY_SIGNED_IN_TOKEN', sha1($conf->get('credentials.hash') . $_SERVER['REMOTE_ADDR'] . $conf->get('credentials.salt')));
8a80e4fe 182
278d9ee2
A
183/**
184 * Checking session state (i.e. is the user still logged in)
185 *
186 * @param ConfigManager $conf The configuration manager.
187 *
188 * @return bool: true if the user is logged in, false otherwise.
189 */
190function setup_login_state($conf)
191{
a544b113
WE
192 if ($conf->get('security.open_shaarli')) {
193 return true;
194 }
195 $userIsLoggedIn = false; // By default, we do not consider the user as logged in;
196 $loginFailure = false; // If set to true, every attempt to authenticate the user will fail. This indicates that an important condition isn't met.
197 if (! $conf->exists('credentials.login')) {
198 $userIsLoggedIn = false; // Shaarli is not configured yet.
199 $loginFailure = true;
200 }
201 if (isset($_COOKIE['shaarli_staySignedIn']) &&
202 $_COOKIE['shaarli_staySignedIn']===STAY_SIGNED_IN_TOKEN &&
203 !$loginFailure)
204 {
205 fillSessionInfo($conf);
206 $userIsLoggedIn = true;
207 }
208 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
209 if (empty($_SESSION['uid'])
88110550 210 || ($conf->get('security.session_protection_disabled') === false && $_SESSION['ip'] != client_ip_id($_SERVER))
684e662a 211 || time() >= $_SESSION['expires_on'])
a544b113
WE
212 {
213 logout();
214 $userIsLoggedIn = false;
215 $loginFailure = true;
216 }
217 if (!empty($_SESSION['longlastingsession'])) {
218 $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // In case of "Stay signed in" checked.
219 }
220 else {
221 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Standard session expiration date.
222 }
223 if (!$loginFailure) {
224 $userIsLoggedIn = true;
225 }
226
227 return $userIsLoggedIn;
ff69d87e 228}
278d9ee2 229$userIsLoggedIn = setup_login_state($conf);
45034273 230
45034273
SS
231// ------------------------------------------------------------------------------------------
232// Session management
45034273 233
278d9ee2
A
234/**
235 * Load user session.
236 *
237 * @param ConfigManager $conf Configuration Manager instance.
238 */
239function fillSessionInfo($conf)
240{
a544b113 241 $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid)
88110550 242 $_SESSION['ip'] = client_ip_id($_SERVER);
a544b113
WE
243 $_SESSION['username']= $conf->get('credentials.login');
244 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration.
ae00595b
CH
245}
246
278d9ee2
A
247/**
248 * Check that user/password is correct.
249 *
250 * @param string $login Username
251 * @param string $password User password
252 * @param ConfigManager $conf Configuration Manager instance.
253 *
254 * @return bool: authentication successful or not.
255 */
256function check_auth($login, $password, $conf)
45034273 257{
da10377b
A
258 $hash = sha1($password . $login . $conf->get('credentials.salt'));
259 if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash'))
45034273 260 { // Login/password is correct.
a544b113 261 fillSessionInfo($conf);
894a3c4b 262 logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login successful');
278d9ee2 263 return true;
45034273 264 }
894a3c4b 265 logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login failed for user '.$login);
278d9ee2 266 return false;
45034273
SS
267}
268
269// Returns true if the user is logged in.
270function isLoggedIn()
271{
ff69d87e
FE
272 global $userIsLoggedIn;
273 return $userIsLoggedIn;
45034273
SS
274}
275
276// Force logout.
ff69d87e
FE
277function logout() {
278 if (isset($_SESSION)) {
279 unset($_SESSION['uid']);
280 unset($_SESSION['ip']);
281 unset($_SESSION['username']);
9d4736a3 282 unset($_SESSION['visibility']);
f210d94f 283 unset($_SESSION['untaggedonly']);
ff69d87e
FE
284 }
285 setcookie('shaarli_staySignedIn', FALSE, 0, WEB_PATH);
ae00595b 286}
45034273 287
45034273
SS
288// ------------------------------------------------------------------------------------------
289// Process login form: Check if login/password is correct.
290if (isset($_POST['login']))
291{
44acf706
V
292 if (! $loginManager->canLogin($_SERVER)) {
293 die(t('I said: NO. You are banned for the moment. Go away.'));
294 }
278d9ee2 295 if (isset($_POST['password'])
ebd650c0 296 && $sessionManager->checkToken($_POST['token'])
278d9ee2 297 && (check_auth($_POST['login'], $_POST['password'], $conf))
44acf706
V
298 ) {
299 // Login/password is OK.
300 $loginManager->handleSuccessfulLogin($_SERVER);
301
45034273 302 // If user wants to keep the session cookie even after the browser closes:
44acf706 303 if (!empty($_POST['longlastingsession'])) {
a544b113
WE
304 $_SESSION['longlastingsession'] = 31536000; // (31536000 seconds = 1 year)
305 $expiration = time() + $_SESSION['longlastingsession']; // calculate relative cookie expiration (1 year from now)
306 setcookie('shaarli_staySignedIn', STAY_SIGNED_IN_TOKEN, $expiration, WEB_PATH);
307 $_SESSION['expires_on'] = $expiration; // Set session expiration on server-side.
2d9fab88
SS
308
309 $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
2f32d074 310 session_set_cookie_params($_SESSION['longlastingsession'],$cookiedir,$_SERVER['SERVER_NAME']); // Set session cookie expiration on client side
ad6c27b7 311 // Note: Never forget the trailing slash on the cookie path!
45034273
SS
312 session_regenerate_id(true); // Send cookie with new expiration date to browser.
313 }
314 else // Standard session expiration (=when browser closes)
315 {
2d9fab88 316 $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
2f32d074 317 session_set_cookie_params(0,$cookiedir,$_SERVER['SERVER_NAME']); // 0 means "When browser closes"
45034273
SS
318 session_regenerate_id(true);
319 }
f4c84ad7 320
45034273 321 // Optional redirect after login:
5fbabbb9
A
322 if (isset($_GET['post'])) {
323 $uri = '?post='. urlencode($_GET['post']);
0b04f797 324 foreach (array('description', 'source', 'title', 'tags') as $param) {
5fbabbb9
A
325 if (!empty($_GET[$param])) {
326 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
327 }
328 }
329 header('Location: '. $uri);
330 exit;
331 }
332
333 if (isset($_GET['edit_link'])) {
334 header('Location: ?edit_link='. escape($_GET['edit_link']));
335 exit;
336 }
337
338 if (isset($_POST['returnurl'])) {
339 // Prevent loops over login screen.
340 if (strpos($_POST['returnurl'], 'do=login') === false) {
e15f08d7 341 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
5fbabbb9
A
342 exit;
343 }
45034273
SS
344 }
345 header('Location: ?'); exit;
44acf706
V
346 } else {
347 $loginManager->handleFailedLogin($_SERVER);
65c002ca 348 $redir = '&username='. urlencode($_POST['login']);
5fbabbb9 349 if (isset($_GET['post'])) {
85c4bdc2 350 $redir .= '&post=' . urlencode($_GET['post']);
0b04f797 351 foreach (array('description', 'source', 'title', 'tags') as $param) {
5fbabbb9
A
352 if (!empty($_GET[$param])) {
353 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
354 }
355 }
356 }
12266213
A
357 // Redirect to login screen.
358 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
45034273
SS
359 exit;
360 }
361}
362
45034273
SS
363// ------------------------------------------------------------------------------------------
364// Token management for XSRF protection
365// Token should be used in any form which acts on data (create,update,delete,import...).
366if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
367
278d9ee2
A
368/**
369 * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
370 * Gives the last 7 days (which have links).
371 * This RSS feed cannot be filtered.
372 *
373 * @param ConfigManager $conf Configuration Manager instance.
374 */
375function showDailyRSS($conf) {
45034273 376 // Cache system
5046bcb6 377 $query = $_SERVER['QUERY_STRING'];
01e48f26 378 $cache = new CachedPage(
684e662a 379 $conf->get('config.PAGE_CACHE'),
482d67bd 380 page_url($_SERVER),
01e48f26
V
381 startsWith($query,'do=dailyrss') && !isLoggedIn()
382 );
f3b8f9f0
A
383 $cached = $cache->cachedVersion();
384 if (!empty($cached)) {
385 echo $cached;
386 exit;
387 }
9f15ca9e 388
f3b8f9f0
A
389 // If cached was not found (or not usable), then read the database and build the response:
390 // Read links from database (and filter private links if used it not logged in).
9f15ca9e 391 $LINKSDB = new LinkDB(
894a3c4b 392 $conf->get('resource.datastore'),
02ad8fb6 393 isLoggedIn(),
894a3c4b
A
394 $conf->get('privacy.hide_public_links'),
395 $conf->get('redirector.url'),
396 $conf->get('redirector.encode_url')
9f15ca9e 397 );
bb8f712d 398
45034273 399 /* Some Shaarlies may have very few links, so we need to look
01878a75 400 back in time until we have enough days ($nb_of_days).
45034273 401 */
f3b8f9f0 402 $nb_of_days = 7; // We take 7 days.
684e662a 403 $today = date('Ymd');
f3b8f9f0
A
404 $days = array();
405
d592daea
A
406 foreach ($LINKSDB as $link) {
407 $day = $link['created']->format('Ymd'); // Extract day (without time)
01878a75 408 if (strcmp($day, $today) < 0) {
f3b8f9f0
A
409 if (empty($days[$day])) {
410 $days[$day] = array();
411 }
d592daea 412 $days[$day][] = $link;
f3b8f9f0
A
413 }
414
415 if (count($days) > $nb_of_days) {
416 break; // Have we collected enough days?
45034273 417 }
45034273 418 }
bb8f712d 419
45034273
SS
420 // Build the RSS feed.
421 header('Content-Type: application/rss+xml; charset=utf-8');
482d67bd 422 $pageaddr = escape(index_url($_SERVER));
45034273 423 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
f3b8f9f0 424 echo '<channel>';
da10377b 425 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
f3b8f9f0
A
426 echo '<link>'. $pageaddr .'</link>';
427 echo '<description>Daily shared links</description>';
428 echo '<language>en-en</language>';
429 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL;
430
431 // For each day.
d592daea 432 foreach ($days as $day => $links) {
205a4277 433 $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
482d67bd 434 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
bb8f712d 435
45034273 436 // We pre-format some fields for proper output.
d592daea 437 foreach ($links as &$link) {
fd08b50a
A
438 $link['formatedDescription'] = format_description(
439 $link['description'],
440 $conf->get('redirector.url'),
441 $conf->get('redirector.encode_url')
442 );
d592daea
A
443 $link['thumbnail'] = thumbnail($conf, $link['url']);
444 $link['timestamp'] = $link['created']->getTimestamp();
445 if (startsWith($link['url'], '?')) {
446 $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
f3b8f9f0 447 }
45034273 448 }
f3b8f9f0 449
45034273 450 // Then build the HTML for this day:
bb8f712d 451 $tpl = new RainTPL;
da10377b 452 $tpl->assign('title', $conf->get('general.title'));
205a4277 453 $tpl->assign('daydate', $dayDate->getTimestamp());
f3b8f9f0
A
454 $tpl->assign('absurl', $absurl);
455 $tpl->assign('links', $links);
205a4277 456 $tpl->assign('rssdate', escape($dayDate->format(DateTime::RSS)));
894a3c4b 457 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
724f1e32 458 $html = $tpl->draw('dailyrss', true);
45034273 459
f3b8f9f0 460 echo $html . PHP_EOL;
bb8f712d 461 }
482d67bd 462 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
bb8f712d 463
45034273
SS
464 $cache->cache(ob_get_contents());
465 ob_end_flush();
466 exit;
467}
468
38603b24
A
469/**
470 * Show the 'Daily' page.
471 *
278d9ee2
A
472 * @param PageBuilder $pageBuilder Template engine wrapper.
473 * @param LinkDB $LINKSDB LinkDB instance.
474 * @param ConfigManager $conf Configuration Manager instance.
475 * @param PluginManager $pluginManager Plugin Manager instane.
38603b24 476 */
278d9ee2 477function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager)
45034273 478{
5a0045be
WE
479 $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
480 if (isset($_GET['day'])) {
481 $day = $_GET['day'];
482 }
bb8f712d 483
45034273 484 $days = $LINKSDB->days();
5a0045be
WE
485 $i = array_search($day, $days);
486 if ($i === false && count($days)) {
487 // no links for day, but at least one day with links
488 $i = count($days) - 1;
489 $day = $days[$i];
45034273 490 }
5a0045be
WE
491 $previousday = '';
492 $nextday = '';
45034273 493
5a0045be
WE
494 if ($i !== false) {
495 if ($i >= 1) {
496 $previousday=$days[$i - 1];
497 }
498 if ($i < count($days) - 1) {
499 $nextday = $days[$i + 1];
500 }
501 }
9186ab95 502 try {
528a6f8a 503 $linksToDisplay = $LINKSDB->filterDay($day);
9186ab95
V
504 } catch (Exception $exc) {
505 error_log($exc);
d1e2f8e5 506 $linksToDisplay = array();
9186ab95
V
507 }
508
45034273 509 // We pre-format some fields for proper output.
5a0045be 510 foreach($linksToDisplay as $key => $link) {
dd62b9ba
SS
511 $taglist = explode(' ',$link['tags']);
512 uasort($taglist, 'strcasecmp');
513 $linksToDisplay[$key]['taglist']=$taglist;
fd08b50a
A
514 $linksToDisplay[$key]['formatedDescription'] = format_description(
515 $link['description'],
516 $conf->get('redirector.url'),
517 $conf->get('redirector.encode_url')
518 );
278d9ee2 519 $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
01878a75 520 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
45034273 521 }
bb8f712d 522
50142efd 523 $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
524 $data = array(
525 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
526 'linksToDisplay' => $linksToDisplay,
527 'day' => $dayDate->getTimestamp(),
528 'dayDate' => $dayDate,
529 'previousday' => $previousday,
530 'nextday' => $nextday,
531 );
532
533 /* Hook is called before column construction so that plugins don't have
534 to deal with columns. */
535 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => isLoggedIn()));
536
45034273 537 /* We need to spread the articles on 3 columns.
ad6c27b7 538 I did not want to use a JavaScript lib like http://masonry.desandro.com/
bb8f712d 539 so I manually spread entries with a simple method: I roughly evaluate the
45034273
SS
540 height of a div according to title and description length.
541 */
5a0045be
WE
542 $columns = array(array(), array(), array()); // Entries to display, for each column.
543 $fill = array(0, 0, 0); // Rough estimate of columns fill.
50142efd 544 foreach($data['linksToDisplay'] as $key => $link) {
45034273
SS
545 // Roughly estimate length of entry (by counting characters)
546 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
547 // Description: 836 characters gives roughly 342 pixel height.
ad6c27b7 548 // This is not perfect, but it's usually OK.
5a0045be
WE
549 $length = strlen($link['title']) + (342 * strlen($link['description'])) / 836;
550 if ($link['thumbnail']) {
551 $length += 100; // 1 thumbnails roughly takes 100 pixels height.
552 }
45034273 553 // Then put in column which is the less filled:
5a0045be
WE
554 $smallest = min($fill); // find smallest value in array.
555 $index = array_search($smallest, $fill); // find index of this smallest value.
556 array_push($columns[$index], $link); // Put entry in this column.
557 $fill[$index] += $length;
45034273 558 }
38603b24 559
50142efd 560 $data['cols'] = $columns;
6fc14d53
A
561
562 foreach ($data as $key => $value) {
38603b24 563 $pageBuilder->assign($key, $value);
6fc14d53
A
564 }
565
980efd6c 566 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
38603b24 567 $pageBuilder->renderPage('daily');
45034273
SS
568 exit;
569}
570
278d9ee2
A
571/**
572 * Renders the linklist
573 *
574 * @param pageBuilder $PAGE pageBuilder instance.
575 * @param LinkDB $LINKSDB LinkDB instance.
576 * @param ConfigManager $conf Configuration Manager instance.
577 * @param PluginManager $pluginManager Plugin Manager instance.
578 */
579function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager) {
580 buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager); // Compute list of links to display
6fc14d53
A
581 $PAGE->renderPage('linklist');
582}
583
278d9ee2
A
584/**
585 * Render HTML page (according to URL parameters and user rights)
586 *
ebd650c0
V
587 * @param ConfigManager $conf Configuration Manager instance.
588 * @param PluginManager $pluginManager Plugin Manager instance,
589 * @param LinkDB $LINKSDB
590 * @param History $history instance
591 * @param SessionManager $sessionManager SessionManager instance
44acf706 592 * @param LoginManager $loginManager LoginManager instance
278d9ee2 593 */
44acf706 594function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
45034273 595{
510377d2 596 $updater = new Updater(
894a3c4b 597 read_updates_file($conf->get('resource.updates')),
510377d2 598 $LINKSDB,
278d9ee2 599 $conf,
510377d2
A
600 isLoggedIn()
601 );
602 try {
603 $newUpdates = $updater->update();
604 if (! empty($newUpdates)) {
605 write_updates_file(
894a3c4b 606 $conf->get('resource.updates'),
510377d2
A
607 $updater->getDoneUpdates()
608 );
609 }
610 }
611 catch(Exception $e) {
612 die($e->getMessage());
613 }
614
ebd650c0 615 $PAGE = new PageBuilder($conf, $LINKSDB, $sessionManager->generateToken());
141a86c5
A
616 $PAGE->assign('linkcount', count($LINKSDB));
617 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
7fde6de1 618 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
6fc14d53
A
619
620 // Determine which page will be rendered.
621 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
622 $targetPage = Router::findPage($query, $_GET, isLoggedIn());
623
27e21231
WE
624 if (
625 // if the user isn't logged in
626 !isLoggedIn() &&
627 // and Shaarli doesn't have public content...
628 $conf->get('privacy.hide_public_links') &&
629 // and is configured to enforce the login
630 $conf->get('privacy.force_login') &&
631 // and the current page isn't already the login page
632 $targetPage !== Router::$PAGE_LOGIN &&
633 // and the user is not requesting a feed (which would lead to a different content-type as expected)
634 $targetPage !== Router::$PAGE_FEED_ATOM &&
635 $targetPage !== Router::$PAGE_FEED_RSS
636 ) {
637 // force current page to be the login page
638 $targetPage = Router::$PAGE_LOGIN;
639 }
640
6fc14d53
A
641 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
642 // Then assign generated data to RainTPL.
643 $common_hooks = array(
fea5db7a 644 'includes',
6fc14d53
A
645 'header',
646 'footer',
6fc14d53 647 );
278d9ee2 648
6fc14d53
A
649 foreach($common_hooks as $name) {
650 $plugin_data = array();
651 $pluginManager->executeHooks('render_' . $name, $plugin_data,
652 array(
653 'target' => $targetPage,
654 'loggedin' => isLoggedIn()
655 )
656 );
657 $PAGE->assign('plugins_' . $name, $plugin_data);
658 }
659
45034273 660 // -------- Display login form.
6fc14d53 661 if ($targetPage == Router::$PAGE_LOGIN)
45034273 662 {
894a3c4b 663 if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
85c4bdc2
A
664 if (isset($_GET['username'])) {
665 $PAGE->assign('username', escape($_GET['username']));
666 }
5f85fcd8 667 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
2e07e775
WE
668 // add default state of the 'remember me' checkbox
669 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
44acf706 670 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
980efd6c 671 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
672 $PAGE->renderPage('loginform');
673 exit;
674 }
675 // -------- User wants to logout.
5046bcb6 676 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
45034273 677 {
894a3c4b 678 invalidateCaches($conf->get('resource.page_cache'));
45034273
SS
679 logout();
680 header('Location: ?');
681 exit;
682 }
683
684 // -------- Picture wall
6fc14d53 685 if ($targetPage == Router::$PAGE_PICWALL)
45034273 686 {
ad6c27b7 687 // Optionally filter the results:
528a6f8a 688 $links = $LINKSDB->filterSearch($_GET);
822bffce 689 $linksToDisplay = array();
45034273
SS
690
691 // Get only links which have a thumbnail.
692 foreach($links as $link)
693 {
d592daea 694 $permalink='?'.$link['shorturl'];
278d9ee2 695 $thumb=lazyThumbnail($conf, $link['url'],$permalink);
45034273
SS
696 if ($thumb!='') // Only output links which have a thumbnail.
697 {
698 $link['thumbnail']=$thumb; // Thumbnail HTML code.
45034273
SS
699 $linksToDisplay[]=$link; // Add to array.
700 }
701 }
f3db3774 702
6fc14d53 703 $data = array(
6fc14d53
A
704 'linksToDisplay' => $linksToDisplay,
705 );
706 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => isLoggedIn()));
707
708 foreach ($data as $key => $value) {
709 $PAGE->assign($key, $value);
710 }
711
980efd6c 712 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
713 $PAGE->renderPage('picwall');
714 exit;
715 }
716
717 // -------- Tag cloud
6fc14d53 718 if ($targetPage == Router::$PAGE_TAGCLOUD)
45034273 719 {
9d4736a3 720 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
aa4797ba 721 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
6ccd0b21 722 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
a037ac69 723
45034273
SS
724 // We sort tags alphabetically, then choose a font size according to count.
725 // First, find max value.
f1e96a06
A
726 $maxcount = 0;
727 foreach ($tags as $value) {
728 $maxcount = max($maxcount, $value);
729 }
730
f32ec5fb 731 alphabetical_sort($tags, false, true);
f1e96a06 732
b0128609
A
733 $tagList = array();
734 foreach($tags as $key => $value) {
49cc8e5d
LC
735 if (in_array($key, $filteringTags)) {
736 continue;
737 }
b0128609
A
738 // Tag font size scaling:
739 // default 15 and 30 logarithm bases affect scaling,
740 // 22 and 6 are arbitrary font sizes for max and min sizes.
741 $size = log($value, 15) / log($maxcount, 30) * 2.2 + 0.8;
742 $tagList[$key] = array(
743 'count' => $value,
744 'size' => number_format($size, 2, '.', ''),
745 );
45034273 746 }
6fc14d53 747
980efd6c 748 $searchTags = implode(' ', escape($filteringTags));
6fc14d53 749 $data = array(
980efd6c 750 'search_tags' => $searchTags,
6fc14d53
A
751 'tags' => $tagList,
752 );
753 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => isLoggedIn()));
754
755 foreach ($data as $key => $value) {
756 $PAGE->assign($key, $value);
757 }
758
980efd6c
A
759 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
760 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
5893529c 761 $PAGE->renderPage('tag.cloud');
bb8f712d 762 exit;
45034273
SS
763 }
764
49cc8e5d 765 // -------- Tag list
aa4797ba
A
766 if ($targetPage == Router::$PAGE_TAGLIST)
767 {
9d4736a3 768 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
aa4797ba
A
769 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
770 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
49cc8e5d
LC
771 foreach ($filteringTags as $tag) {
772 if (array_key_exists($tag, $tags)) {
773 unset($tags[$tag]);
774 }
775 }
aa4797ba
A
776
777 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
778 alphabetical_sort($tags, false, true);
779 }
780
980efd6c 781 $searchTags = implode(' ', escape($filteringTags));
aa4797ba 782 $data = [
980efd6c 783 'search_tags' => $searchTags,
aa4797ba
A
784 'tags' => $tags,
785 ];
786 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => isLoggedIn()]);
787
788 foreach ($data as $key => $value) {
789 $PAGE->assign($key, $value);
790 }
791
980efd6c
A
792 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
793 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
aa4797ba
A
794 $PAGE->renderPage('tag.list');
795 exit;
796 }
797
38603b24
A
798 // Daily page.
799 if ($targetPage == Router::$PAGE_DAILY) {
278d9ee2 800 showDaily($PAGE, $LINKSDB, $conf, $pluginManager);
38603b24
A
801 }
802
82e36802
A
803 // ATOM and RSS feed.
804 if ($targetPage == Router::$PAGE_FEED_ATOM || $targetPage == Router::$PAGE_FEED_RSS) {
805 $feedType = $targetPage == Router::$PAGE_FEED_RSS ? FeedBuilder::$FEED_RSS : FeedBuilder::$FEED_ATOM;
806 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
807
808 // Cache system
809 $query = $_SERVER['QUERY_STRING'];
810 $cache = new CachedPage(
894a3c4b 811 $conf->get('resource.page_cache'),
82e36802
A
812 page_url($_SERVER),
813 startsWith($query,'do='. $targetPage) && !isLoggedIn()
814 );
815 $cached = $cache->cachedVersion();
5f143b72 816 if (!empty($cached)) {
82e36802
A
817 echo $cached;
818 exit;
819 }
69c474b9 820
82e36802
A
821 // Generate data.
822 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, isLoggedIn());
823 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0)));
894a3c4b
A
824 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !isLoggedIn());
825 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
82e36802
A
826 $data = $feedGenerator->buildData();
827
828 // Process plugin hook.
82e36802
A
829 $pluginManager->executeHooks('render_feed', $data, array(
830 'loggedin' => isLoggedIn(),
831 'target' => $targetPage,
832 ));
833
834 // Render the template.
835 $PAGE->assignAll($data);
836 $PAGE->renderPage('feed.'. $feedType);
837 $cache->cache(ob_get_contents());
838 ob_end_flush();
839 exit;
e67712ba
A
840 }
841
18e67967 842 // Display opensearch plugin (XML)
8f8113b9
A
843 if ($targetPage == Router::$PAGE_OPENSEARCH) {
844 header('Content-Type: application/xml; charset=utf-8');
845 $PAGE->assign('serverurl', index_url($_SERVER));
846 $PAGE->renderPage('opensearch');
847 exit;
848 }
849
45034273
SS
850 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
851 if (isset($_GET['addtag']))
852 {
853 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
854 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER
855 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
732e683b 856
775803a0
A
857 // Prevent redirection loop
858 if (isset($params['addtag'])) {
859 unset($params['addtag']);
860 }
861
732e683b
FE
862 // Check if this tag is already in the search query and ignore it if it is.
863 // Each tag is always separated by a space
6ac95d9c
A
864 if (isset($params['searchtags'])) {
865 $current_tags = explode(' ', $params['searchtags']);
866 } else {
867 $current_tags = array();
868 }
732e683b
FE
869 $addtag = true;
870 foreach ($current_tags as $value) {
871 if ($value === $_GET['addtag']) {
872 $addtag = false;
873 break;
874 }
875 }
876 // Append the tag if necessary
877 if (empty($params['searchtags'])) {
878 $params['searchtags'] = trim($_GET['addtag']);
879 }
d2d4f993 880 elseif ($addtag) {
732e683b
FE
881 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
882 }
883
45034273
SS
884 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
885 header('Location: ?'.http_build_query($params));
886 exit;
887 }
888
889 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
775803a0 890 if (isset($_GET['removetag'])) {
45034273 891 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
775803a0
A
892 if (empty($_SERVER['HTTP_REFERER'])) {
893 header('Location: ?');
894 exit;
895 }
896
897 // In case browser does not send HTTP_REFERER
898 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
899
900 // Prevent redirection loop
901 if (isset($params['removetag'])) {
902 unset($params['removetag']);
903 }
904
905 if (isset($params['searchtags'])) {
822bffce 906 $tags = explode(' ', $params['searchtags']);
2c75f8e7
A
907 // Remove value from array $tags.
908 $tags = array_diff($tags, array($_GET['removetag']));
909 $params['searchtags'] = implode(' ',$tags);
910
911 if (empty($params['searchtags'])) {
775803a0 912 unset($params['searchtags']);
775803a0 913 }
2c75f8e7 914
45034273
SS
915 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
916 }
917 header('Location: ?'.http_build_query($params));
918 exit;
919 }
920
921 // -------- User wants to change the number of links per page (linksperpage=...)
775803a0
A
922 if (isset($_GET['linksperpage'])) {
923 if (is_numeric($_GET['linksperpage'])) {
924 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
925 }
926
8bbf02e0
A
927 if (! empty($_SERVER['HTTP_REFERER'])) {
928 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
929 } else {
930 $location = '?';
931 }
932 header('Location: '. $location);
45034273
SS
933 exit;
934 }
bb8f712d 935
45034273 936 // -------- User wants to see only private links (toggle)
9d4736a3 937 if (isset($_GET['visibility'])) {
9d4736a3 938 if ($_GET['visibility'] === 'private') {
d2f6d909
A
939 // Visibility not set or not already private, set private, otherwise reset it
940 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
941 // See only private links
942 $_SESSION['visibility'] = 'private';
943 } else {
944 unset($_SESSION['visibility']);
945 }
d2d4f993 946 } elseif ($_GET['visibility'] === 'public') {
d2f6d909
A
947 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
948 // See only public links
949 $_SESSION['visibility'] = 'public';
950 } else {
951 unset($_SESSION['visibility']);
952 }
45034273 953 }
775803a0 954
8bbf02e0 955 if (! empty($_SERVER['HTTP_REFERER'])) {
9d4736a3 956 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
8bbf02e0
A
957 } else {
958 $location = '?';
959 }
960 header('Location: '. $location);
45034273
SS
961 exit;
962 }
963
f210d94f
LC
964 // -------- User wants to see only untagged links (toggle)
965 if (isset($_GET['untaggedonly'])) {
c4925c1f 966 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
f210d94f
LC
967
968 if (! empty($_SERVER['HTTP_REFERER'])) {
969 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
970 } else {
971 $location = '?';
972 }
973 header('Location: '. $location);
974 exit;
975 }
976
45034273
SS
977 // -------- Handle other actions allowed for non-logged in users:
978 if (!isLoggedIn())
979 {
ad6c27b7 980 // User tries to post new link but is not logged in:
45034273
SS
981 // Show login screen, then redirect to ?post=...
982 if (isset($_GET['post']))
983 {
0b04f797 984 header( // Redirect to login page, then back to post link.
985 'Location: ?do=login&post='.urlencode($_GET['post']).
986 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
987 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
988 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
989 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
990 );
45034273
SS
991 exit;
992 }
aedc912d 993
278d9ee2 994 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
5fbabbb9
A
995 if (isset($_GET['edit_link'])) {
996 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
997 exit;
998 }
999
ad6c27b7 1000 exit; // Never remove this one! All operations below are reserved for logged in user.
45034273
SS
1001 }
1002
1003 // -------- All other functions are reserved for the registered user:
1004
1005 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
6fc14d53 1006 if ($targetPage == Router::$PAGE_TOOLS)
45034273 1007 {
a3130d2c 1008 $data = [
6fc14d53 1009 'pageabsaddr' => index_url($_SERVER),
a3130d2c
A
1010 'sslenabled' => is_https($_SERVER),
1011 ];
6fc14d53
A
1012 $pluginManager->executeHooks('render_tools', $data);
1013
1014 foreach ($data as $key => $value) {
1015 $PAGE->assign($key, $value);
1016 }
1017
980efd6c 1018 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1019 $PAGE->renderPage('tools');
1020 exit;
1021 }
1022
1023 // -------- User wants to change his/her password.
6fc14d53 1024 if ($targetPage == Router::$PAGE_CHANGEPASSWORD)
45034273 1025 {
894a3c4b 1026 if ($conf->get('security.open_shaarli')) {
12266213 1027 die(t('You are not supposed to change a password on an Open Shaarli.'));
684e662a
A
1028 }
1029
45034273
SS
1030 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
1031 {
ebd650c0 1032 if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away!
45034273
SS
1033
1034 // Make sure old password is correct.
da10377b 1035 $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
12266213
A
1036 if ($oldhash!= $conf->get('credentials.hash')) {
1037 echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>';
ebd650c0 1038 exit;
12266213 1039 }
45034273 1040 // Save new password
684e662a 1041 // Salt renders rainbow-tables attacks useless.
da10377b
A
1042 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
1043 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt')));
dd484b90 1044 try {
684e662a 1045 $conf->write(isLoggedIn());
dd484b90
A
1046 }
1047 catch(Exception $e) {
1048 error_log(
1049 'ERROR while writing config file after changing password.' . PHP_EOL .
1050 $e->getMessage()
1051 );
1052
1053 // TODO: do not handle exceptions/errors in JS.
1054 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
1055 exit;
1056 }
12266213 1057 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
45034273
SS
1058 exit;
1059 }
1060 else // show the change password form.
1061 {
980efd6c 1062 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1063 $PAGE->renderPage('changepassword');
1064 exit;
1065 }
1066 }
1067
1068 // -------- User wants to change configuration
6fc14d53 1069 if ($targetPage == Router::$PAGE_CONFIGURE)
45034273
SS
1070 {
1071 if (!empty($_POST['title']) )
1072 {
ebd650c0 1073 if (!$sessionManager->checkToken($_POST['token'])) {
12266213 1074 die(t('Wrong token.')); // Go away!
12ff86c9 1075 }
45034273 1076 $tz = 'UTC';
12ff86c9
A
1077 if (!empty($_POST['continent']) && !empty($_POST['city'])
1078 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1079 ) {
1080 $tz = $_POST['continent'] . '/' . $_POST['city'];
1081 }
da10377b 1082 $conf->set('general.timezone', $tz);
7f179985
A
1083 $conf->set('general.title', escape($_POST['title']));
1084 $conf->set('general.header_link', escape($_POST['titleLink']));
adc4aee8 1085 $conf->set('resource.theme', escape($_POST['theme']));
da10377b 1086 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
894a3c4b
A
1087 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
1088 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1089 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1090 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
76be95e1 1091 $conf->set('api.enabled', !empty($_POST['enableApi']));
cbfdcff2 1092 $conf->set('api.secret', escape($_POST['apiSecret']));
f39580c6
A
1093 $conf->set('translation.language', escape($_POST['language']));
1094
dd484b90 1095 try {
684e662a 1096 $conf->write(isLoggedIn());
4306b184 1097 $history->updateSettings();
adc4aee8 1098 invalidateCaches($conf->get('resource.page_cache'));
dd484b90
A
1099 }
1100 catch(Exception $e) {
1101 error_log(
1102 'ERROR while writing config file after configuration update.' . PHP_EOL .
1103 $e->getMessage()
1104 );
1105
1106 // TODO: do not handle exceptions/errors in JS.
684e662a 1107 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
dd484b90
A
1108 exit;
1109 }
12266213 1110 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
45034273
SS
1111 exit;
1112 }
1113 else // Show the configuration form.
1114 {
da10377b 1115 $PAGE->assign('title', $conf->get('general.title'));
adc4aee8 1116 $PAGE->assign('theme', $conf->get('resource.theme'));
a0df0651 1117 $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl')));
ae3aa968
A
1118 list($continents, $cities) = generateTimeZoneData(
1119 timezone_identifiers_list(),
1120 $conf->get('general.timezone')
1121 );
1122 $PAGE->assign('continents', $continents);
1123 $PAGE->assign('cities', $cities);
894a3c4b 1124 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
2e193ad3 1125 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
894a3c4b
A
1126 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1127 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1128 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
cbfdcff2
A
1129 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1130 $PAGE->assign('api_secret', $conf->get('api.secret'));
f39580c6
A
1131 $PAGE->assign('languages', Languages::getAvailableLanguages());
1132 $PAGE->assign('language', $conf->get('translation.language'));
980efd6c 1133 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1134 $PAGE->renderPage('configure');
1135 exit;
1136 }
1137 }
1138
1139 // -------- User wants to rename a tag or delete it
6fc14d53 1140 if ($targetPage == Router::$PAGE_CHANGETAG)
45034273 1141 {
6a6aa2b9 1142 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
aa4797ba 1143 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
980efd6c 1144 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1145 $PAGE->renderPage('changetag');
1146 exit;
1147 }
6a6aa2b9 1148
ebd650c0 1149 if (!$sessionManager->checkToken($_POST['token'])) {
12266213 1150 die(t('Wrong token.'));
6a6aa2b9 1151 }
45034273 1152
3b67b222 1153 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), escape($_POST['totag']));
d99aef53 1154 $LINKSDB->save($conf->get('resource.page_cache'));
3b67b222
A
1155 foreach ($alteredLinks as $link) {
1156 $history->updateLink($link);
45034273 1157 }
3b67b222 1158 $delete = empty($_POST['totag']);
d99aef53 1159 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
f39580c6 1160 $count = count($alteredLinks);
d99aef53 1161 $alert = $delete
f39580c6
A
1162 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d links.', $count), $count)
1163 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d links.', $count), $count);
d99aef53
A
1164 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1165 exit;
45034273
SS
1166 }
1167
ad6c27b7 1168 // -------- User wants to add a link without using the bookmarklet: Show form.
6fc14d53 1169 if ($targetPage == Router::$PAGE_ADDLINK)
45034273 1170 {
980efd6c 1171 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1172 $PAGE->renderPage('addlink');
1173 exit;
1174 }
1175
1176 // -------- User clicked the "Save" button when editing a link: Save link to database.
1177 if (isset($_POST['save_edit']))
1178 {
5a23950c 1179 // Go away!
ebd650c0 1180 if (! $sessionManager->checkToken($_POST['token'])) {
12266213 1181 die(t('Wrong token.'));
5a23950c 1182 }
01878a75
A
1183
1184 // lf_id should only be present if the link exists.
b712ab0a 1185 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
01878a75
A
1186 // Linkdate is kept here to:
1187 // - use the same permalink for notes as they're displayed when creating them
1188 // - let users hack creation date of their posts
cc8f572b 1189 // See: https://shaarli.readthedocs.io/en/master/Various-hacks/#changing-the-timestamp-for-a-shaare
01878a75
A
1190 $linkdate = escape($_POST['lf_linkdate']);
1191 if (isset($LINKSDB[$id])) {
1192 // Edit
d592daea 1193 $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
01878a75 1194 $updated = new DateTime();
826c6af7 1195 $shortUrl = $LINKSDB[$id]['shorturl'];
4306b184 1196 $new = false;
01878a75
A
1197 } else {
1198 // New link
d592daea 1199 $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
01878a75 1200 $updated = null;
826c6af7 1201 $shortUrl = link_small_hash($created, $id);
4306b184 1202 $new = true;
01878a75
A
1203 }
1204
5a23950c
A
1205 // Remove multiple spaces.
1206 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
ce354bf1
A
1207 // Remove first '-' char in tags.
1208 $tags = preg_replace('/(^| )\-/', '$1', $tags);
5a23950c
A
1209 // Remove duplicates.
1210 $tags = implode(' ', array_unique(explode(' ', $tags)));
9646b7da 1211
c27f2f36
A
1212 if (empty(trim($_POST['lf_url']))) {
1213 $_POST['lf_url'] = '?' . smallHash($linkdate . $id);
1214 }
86ceea05 1215 $url = whitelist_protocols(trim($_POST['lf_url']), $conf->get('security.allowed_protocols'));
5a23950c
A
1216
1217 $link = array(
01878a75 1218 'id' => $id,
5a23950c
A
1219 'title' => trim($_POST['lf_title']),
1220 'url' => $url,
ed853da7 1221 'description' => $_POST['lf_description'],
5a23950c 1222 'private' => (isset($_POST['lf_private']) ? 1 : 0),
01878a75 1223 'created' => $created,
9646b7da 1224 'updated' => $updated,
d592daea 1225 'tags' => str_replace(',', ' ', $tags),
826c6af7 1226 'shorturl' => $shortUrl,
5a23950c 1227 );
01878a75 1228
5a23950c
A
1229 // If title is empty, use the URL as title.
1230 if ($link['title'] == '') {
1231 $link['title'] = $link['url'];
1232 }
6fc14d53
A
1233
1234 $pluginManager->executeHooks('save_link', $link);
1235
01878a75 1236 $LINKSDB[$id] = $link;
f21abf32 1237 $LINKSDB->save($conf->get('resource.page_cache'));
4306b184
A
1238 if ($new) {
1239 $history->addLink($link);
1240 } else {
1241 $history->updateLink($link);
1242 }
45034273
SS
1243
1244 // If we are called from the bookmarklet, we must close the popup:
d01c2342
A
1245 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1246 echo '<script>self.close();</script>';
1247 exit;
1248 }
1249
fd50e14c 1250 $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?';
775803a0 1251 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
5a23950c 1252 // Scroll to the link which has been edited.
d592daea 1253 $location .= '#' . $link['shorturl'];
5a23950c
A
1254 // After saving the link, redirect to the page the user was on.
1255 header('Location: '. $location);
45034273
SS
1256 exit;
1257 }
1258
1259 // -------- User clicked the "Cancel" button when editing a link.
1260 if (isset($_POST['cancel_edit']))
1261 {
b712ab0a
A
1262 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1263 if (! isset($LINKSDB[$id])) {
1264 header('Location: ?');
1265 }
ad6c27b7 1266 // If we are called from the bookmarklet, we must close the popup:
d33c5d4c 1267 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
b712ab0a 1268 $link = $LINKSDB[$id];
45034273 1269 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
01878a75 1270 // Scroll to the link which has been edited.
d592daea 1271 $returnurl .= '#'. $link['shorturl'];
775803a0 1272 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
45034273
SS
1273 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1274 exit;
1275 }
1276
ad6c27b7 1277 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
f4ebd5fe 1278 if ($targetPage == Router::$PAGE_DELETELINK)
45034273 1279 {
ebd650c0 1280 if (! $sessionManager->checkToken($_GET['token'])) {
12266213 1281 die(t('Wrong token.'));
f4ebd5fe 1282 }
01878a75 1283
a74f52a8
WE
1284 $ids = trim($_GET['lf_linkdate']);
1285 if (strpos($ids, ' ') !== false) {
1286 // multiple, space-separated ids provided
1287 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
29a837f3 1288 } else {
a74f52a8
WE
1289 // only a single id provided
1290 $ids = [$ids];
1291 }
1292 // assert at least one id is given
1293 if(!count($ids)){
1294 die('no id provided');
29a837f3
A
1295 }
1296 foreach ($ids as $id) {
1297 $id = (int) escape($id);
1298 $link = $LINKSDB[$id];
1299 $pluginManager->executeHooks('delete_link', $link);
1300 unset($LINKSDB[$id]);
1301 }
f4ebd5fe 1302 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
4306b184 1303 $history->deleteLink($link);
45034273
SS
1304
1305 // If we are called from the bookmarklet, we must close the popup:
d33c5d4c 1306 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
95e5add4
A
1307
1308 $location = '?';
1309 if (isset($_SERVER['HTTP_REFERER'])) {
1310 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1311 $location = generateLocation(
1312 $_SERVER['HTTP_REFERER'],
1313 $_SERVER['HTTP_HOST'],
1314 ['delete_link', 'edit_link', $link['shorturl']]
1315 );
d528433d 1316 }
1317
1318 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
45034273
SS
1319 exit;
1320 }
1321
1322 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1323 if (isset($_GET['edit_link']))
1324 {
01878a75
A
1325 $id = (int) escape($_GET['edit_link']);
1326 $link = $LINKSDB[$id]; // Read database
45034273 1327 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
d592daea 1328 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
6fc14d53 1329 $data = array(
6fc14d53
A
1330 'link' => $link,
1331 'link_is_new' => false,
6fc14d53 1332 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
6ccd0b21 1333 'tags' => $LINKSDB->linksCountPerTag(),
6fc14d53
A
1334 );
1335 $pluginManager->executeHooks('render_editlink', $data);
1336
1337 foreach ($data as $key => $value) {
1338 $PAGE->assign($key, $value);
1339 }
1340
980efd6c 1341 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1342 $PAGE->renderPage('editlink');
1343 exit;
1344 }
1345
1346 // -------- User want to post a new link: Display link edit form.
d9d776af 1347 if (isset($_GET['post'])) {
ce7b0b64 1348 $url = cleanup_url($_GET['post']);
45034273
SS
1349
1350 $link_is_new = false;
9e1724f1 1351 // Check if URL is not already in database (in this case, we will edit the existing link)
ef591e7e 1352 $link = $LINKSDB->getLinkFromUrl($url);
01878a75 1353 if (! $link)
45034273 1354 {
9e1724f1 1355 $link_is_new = true;
d592daea 1356 $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT));
9e1724f1 1357 // Get title if it was provided in URL (by the bookmarklet).
739dc243 1358 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
9e1724f1 1359 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
739dc243
A
1360 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1361 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1362 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
26c50346 1363 // If this is an HTTP(S) link, we try go get the page to extract the title (otherwise we will to straight to the edit form.)
ef591e7e 1364 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
451314eb 1365 // Short timeout to keep the application responsive
d65342e3 1366 // The callback will fill $charset and $title with data from the downloaded page.
4ff3ed1c
A
1367 get_http_response(
1368 $url,
4ff3ed1c 1369 $conf->get('general.download_timeout', 30),
8d2cac1b 1370 $conf->get('general.download_max_size', 4194304),
4ff3ed1c
A
1371 get_curl_download_callback($charset, $title)
1372 );
d65342e3
A
1373 if (! empty($title) && strtolower($charset) != 'utf-8') {
1374 $title = mb_convert_encoding($title, 'utf-8', $charset);
9e1724f1 1375 }
45034273 1376 }
1557cefb 1377
9e1724f1 1378 if ($url == '') {
d592daea 1379 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
f39580c6 1380 $title = $conf->get('general.default_note_title', t('Note: '));
27646ca5 1381 }
ce7b0b64
A
1382 $url = escape($url);
1383 $title = escape($title);
1557cefb 1384
9e1724f1
A
1385 $link = array(
1386 'linkdate' => $linkdate,
1387 'title' => $title,
ef591e7e 1388 'url' => $url,
9e1724f1
A
1389 'description' => $description,
1390 'tags' => $tags,
807cade6 1391 'private' => $private,
9e1724f1 1392 );
01878a75 1393 } else {
d592daea 1394 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
45034273
SS
1395 }
1396
6fc14d53 1397 $data = array(
6fc14d53
A
1398 'link' => $link,
1399 'link_is_new' => $link_is_new,
6fc14d53
A
1400 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1401 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
6ccd0b21 1402 'tags' => $LINKSDB->linksCountPerTag(),
cdbc8180 1403 'default_private_links' => $conf->get('privacy.default_private_links', false),
6fc14d53
A
1404 );
1405 $pluginManager->executeHooks('render_editlink', $data);
1406
1407 foreach ($data as $key => $value) {
1408 $PAGE->assign($key, $value);
1409 }
1410
980efd6c 1411 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1412 $PAGE->renderPage('editlink');
1413 exit;
1414 }
1415
cd5327be 1416 if ($targetPage == Router::$PAGE_EXPORT) {
bb4a23aa
V
1417 // Export links as a Netscape Bookmarks file
1418
cd5327be 1419 if (empty($_GET['selection'])) {
980efd6c 1420 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1421 $PAGE->renderPage('export');
1422 exit;
1423 }
45034273 1424
cd5327be
V
1425 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1426 $selection = $_GET['selection'];
bb4a23aa
V
1427 if (isset($_GET['prepend_note_url'])) {
1428 $prependNoteUrl = $_GET['prepend_note_url'];
1429 } else {
1430 $prependNoteUrl = false;
1431 }
1432
cd5327be
V
1433 try {
1434 $PAGE->assign(
1435 'links',
bb4a23aa
V
1436 NetscapeBookmarkUtils::filterAndFormat(
1437 $LINKSDB,
1438 $selection,
1439 $prependNoteUrl,
1440 index_url($_SERVER)
1441 )
cd5327be
V
1442 );
1443 } catch (Exception $exc) {
1444 header('Content-Type: text/plain; charset=utf-8');
1445 echo $exc->getMessage();
1446 exit;
45034273 1447 }
cd5327be
V
1448 $now = new DateTime();
1449 header('Content-Type: text/html; charset=utf-8');
1450 header(
1451 'Content-disposition: attachment; filename=bookmarks_'
1452 .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html'
1453 );
1454 $PAGE->assign('date', $now->format(DateTime::RFC822));
1455 $PAGE->assign('eol', PHP_EOL);
1456 $PAGE->assign('selection', $selection);
1457 $PAGE->renderPage('export.bookmarks');
1458 exit;
45034273
SS
1459 }
1460
a973afea
V
1461 if ($targetPage == Router::$PAGE_IMPORT) {
1462 // Upload a Netscape bookmark dump to import its contents
1463
1464 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1465 // Show import dialog
6a19124a
A
1466 $PAGE->assign(
1467 'maxfilesize',
1468 get_max_upload_size(
1469 ini_get('post_max_size'),
1470 ini_get('upload_max_filesize'),
1471 false
1472 )
1473 );
1474 $PAGE->assign(
1475 'maxfilesizeHuman',
1476 get_max_upload_size(
1477 ini_get('post_max_size'),
1478 ini_get('upload_max_filesize'),
1479 true
1480 )
1481 );
980efd6c 1482 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
a973afea 1483 $PAGE->renderPage('import');
45034273
SS
1484 exit;
1485 }
45034273 1486
a973afea
V
1487 // Import bookmarks from an uploaded file
1488 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1489 // The file is too big or some form field may be missing.
12266213
A
1490 $msg = sprintf(
1491 t(
1492 'The file you are trying to upload is probably bigger than what this webserver can accept'
1493 .' (%s). Please upload in smaller chunks.'
1494 ),
1495 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1496 );
1497 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router::$PAGE_IMPORT .'\';</script>';
a973afea
V
1498 exit;
1499 }
ebd650c0 1500 if (! $sessionManager->checkToken($_POST['token'])) {
a973afea
V
1501 die('Wrong token.');
1502 }
1503 $status = NetscapeBookmarkUtils::import(
1504 $_POST,
1505 $_FILES,
1506 $LINKSDB,
4306b184
A
1507 $conf,
1508 $history
a973afea
V
1509 );
1510 echo '<script>alert("'.$status.'");document.location=\'?do='
1511 .Router::$PAGE_IMPORT .'\';</script>';
45034273
SS
1512 exit;
1513 }
1514
dea0ba28
A
1515 // Plugin administration page
1516 if ($targetPage == Router::$PAGE_PLUGINSADMIN) {
1517 $pluginMeta = $pluginManager->getPluginsMeta();
1518
1519 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1520 $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; });
1521 // Load parameters.
684e662a 1522 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
dea0ba28
A
1523 uasort(
1524 $enabledPlugins,
1525 function($a, $b) { return $a['order'] - $b['order']; }
1526 );
1527 $disabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] === false; });
1528
1529 $PAGE->assign('enabledPlugins', $enabledPlugins);
1530 $PAGE->assign('disabledPlugins', $disabledPlugins);
980efd6c 1531 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
dea0ba28
A
1532 $PAGE->renderPage('pluginsadmin');
1533 exit;
1534 }
1535
1536 // Plugin administration form action
1537 if ($targetPage == Router::$PAGE_SAVE_PLUGINSADMIN) {
1538 try {
1539 if (isset($_POST['parameters_form'])) {
1540 unset($_POST['parameters_form']);
1541 foreach ($_POST as $param => $value) {
684e662a 1542 $conf->set('plugins.'. $param, escape($value));
dea0ba28
A
1543 }
1544 }
1545 else {
da10377b 1546 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
dea0ba28 1547 }
684e662a 1548 $conf->write(isLoggedIn());
b86aeccf 1549 $history->updateSettings();
dea0ba28
A
1550 }
1551 catch (Exception $e) {
1552 error_log(
1553 'ERROR while saving plugin configuration:.' . PHP_EOL .
1554 $e->getMessage()
1555 );
1556
1557 // TODO: do not handle exceptions/errors in JS.
59edea42 1558 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router::$PAGE_PLUGINSADMIN .'\';</script>';
dea0ba28
A
1559 exit;
1560 }
1561 header('Location: ?do='. Router::$PAGE_PLUGINSADMIN);
1562 exit;
1563 }
1564
986a5210
A
1565 // Get a fresh token
1566 if ($targetPage == Router::$GET_TOKEN) {
1567 header('Content-Type:text/plain');
ebd650c0 1568 echo $sessionManager->generateToken($conf);
986a5210
A
1569 exit;
1570 }
1571
45034273 1572 // -------- Otherwise, simply display search form and links:
278d9ee2 1573 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager);
45034273
SS
1574 exit;
1575}
1576
528a6f8a
A
1577/**
1578 * Template for the list of links (<div id="linklist">)
1579 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1580 *
278d9ee2
A
1581 * @param pageBuilder $PAGE pageBuilder instance.
1582 * @param LinkDB $LINKSDB LinkDB instance.
1583 * @param ConfigManager $conf Configuration Manager instance.
1584 * @param PluginManager $pluginManager Plugin Manager instance.
528a6f8a 1585 */
278d9ee2 1586function buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager)
45034273 1587{
528a6f8a 1588 // Used in templates
7d86f40b
A
1589 if (isset($_GET['searchtags'])) {
1590 if (! empty($_GET['searchtags'])) {
1591 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1592 } else {
1593 $searchtags = false;
1594 }
1595 } else {
1596 $searchtags = '';
1597 }
b3051a6a 1598 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
822bffce 1599
528a6f8a
A
1600 // Smallhash filter
1601 if (! empty($_SERVER['QUERY_STRING'])
1602 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1603 try {
1604 $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
1605 } catch (LinkNotFoundException $e) {
1606 $PAGE->render404($e->getMessage());
45034273
SS
1607 exit;
1608 }
528a6f8a
A
1609 } else {
1610 // Filter links according search parameters.
9d4736a3 1611 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
7d86f40b
A
1612 $request = [
1613 'searchtags' => $searchtags,
1614 'searchterm' => $searchterm,
1615 ];
f210d94f 1616 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
45034273
SS
1617 }
1618
1619 // ---- Handle paging.
822bffce
A
1620 $keys = array();
1621 foreach ($linksToDisplay as $key => $value) {
1622 $keys[] = $key;
1623 }
45034273 1624
97ef33bb 1625
45034273
SS
1626
1627 // Select articles according to paging.
822bffce
A
1628 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1629 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1630 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1631 $page = $page < 1 ? 1 : $page;
1632 $page = $page > $pagecount ? $pagecount : $page;
1633 // Start index.
1634 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1635 $end = $i + $_SESSION['LINKS_PER_PAGE'];
1636 $linkDisp = array();
45034273
SS
1637 while ($i<$end && $i<count($keys))
1638 {
1639 $link = $linksToDisplay[$keys[$i]];
fd08b50a
A
1640 $link['description'] = format_description(
1641 $link['description'],
1642 $conf->get('redirector.url'),
1643 $conf->get('redirector.encode_url')
1644 );
822bffce
A
1645 $classLi = ($i % 2) != 0 ? '' : 'publicLinkHightLight';
1646 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
01878a75 1647 $link['timestamp'] = $link['created']->getTimestamp();
9646b7da 1648 if (! empty($link['updated'])) {
01878a75 1649 $link['updated_timestamp'] = $link['updated']->getTimestamp();
9646b7da
A
1650 } else {
1651 $link['updated_timestamp'] = '';
1652 }
b3051a6a 1653 $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY);
a5752e77 1654 uasort($taglist, 'strcasecmp');
822bffce 1655 $link['taglist'] = $taglist;
822bffce
A
1656 // Check for both signs of a note: starting with ? and 7 chars long.
1657 if ($link['url'][0] === '?' &&
1658 strlen($link['url']) === 7) {
1659 $link['url'] = index_url($_SERVER) . $link['url'];
b47f515a 1660 }
d33c5d4c 1661
45034273
SS
1662 $linkDisp[$keys[$i]] = $link;
1663 $i++;
1664 }
bb8f712d 1665
45034273 1666 // Compute paging navigation
7d86f40b 1667 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
c51fae92 1668 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
822bffce
A
1669 $previous_page_url = '';
1670 if ($i != count($keys)) {
c51fae92 1671 $previous_page_url = '?page=' . ($page+1) . $searchtermUrl . $searchtagsUrl;
822bffce
A
1672 }
1673 $next_page_url='';
1674 if ($page>1) {
c51fae92 1675 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
822bffce 1676 }
45034273 1677
45034273 1678 // Fill all template fields.
6fc14d53 1679 $data = array(
6fc14d53
A
1680 'previous_page_url' => $previous_page_url,
1681 'next_page_url' => $next_page_url,
1682 'page_current' => $page,
1683 'page_max' => $pagecount,
1684 'result_count' => count($linksToDisplay),
c51fae92
A
1685 'search_term' => $searchterm,
1686 'search_tags' => $searchtags,
9d4736a3 1687 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
894a3c4b 1688 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
6fc14d53 1689 'links' => $linkDisp,
6fc14d53 1690 );
97ef33bb
A
1691
1692 // If there is only a single link, we change on-the-fly the title of the page.
1693 if (count($linksToDisplay) == 1) {
1694 $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
980efd6c
A
1695 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1696 $data['pagetitle'] = t('Search: ');
1697 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1698 $bracketWrap = function ($tag) {
1699 return '['. $tag .']';
1700 };
1701 $data['pagetitle'] .= ! empty($searchtags)
1702 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1703 : '';
1704 $data['pagetitle'] .= '- '. $conf->get('general.title');
18cca483 1705 }
6fc14d53 1706
6fc14d53
A
1707 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => isLoggedIn()));
1708
1709 foreach ($data as $key => $value) {
1710 $PAGE->assign($key, $value);
1711 }
1712
45034273
SS
1713 return;
1714}
1715
278d9ee2
A
1716/**
1717 * Compute the thumbnail for a link.
1718 *
1719 * With a link to the original URL.
1720 * Understands various services (youtube.com...)
1721 * Input: $url = URL for which the thumbnail must be found.
1722 * $href = if provided, this URL will be followed instead of $url
1723 * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
1724 * Some of them may be missing.
1725 * Return an empty array if no thumbnail available.
1726 *
1727 * @param ConfigManager $conf Configuration Manager instance.
1728 * @param string $url
1729 * @param string|bool $href
1730 *
1731 * @return array
1732 */
1733function computeThumbnail($conf, $url, $href = false)
45034273 1734{
894a3c4b 1735 if (!$conf->get('thumbnail.enable_thumbnails')) return array();
45034273
SS
1736 if ($href==false) $href=$url;
1737
1738 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
ad6c27b7 1739 // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
45034273
SS
1740 // ^^^^^^^^^^^ ^^^^^^^^^^^
1741 $domain = parse_url($url,PHP_URL_HOST);
1742 if ($domain=='youtube.com' || $domain=='www.youtube.com')
1743 {
1744 parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract video ID and get thumbnail
1a663a0f 1745 if (!empty($params['v'])) return array('src'=>'https://img.youtube.com/vi/'.$params['v'].'/default.jpg',
45034273
SS
1746 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
1747 }
1748 if ($domain=='youtu.be') // Youtube short links
1749 {
1750 $path = parse_url($url,PHP_URL_PATH);
1a663a0f 1751 return array('src'=>'https://img.youtube.com/vi'.$path.'/default.jpg',
bb8f712d 1752 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
45034273
SS
1753 }
1754 if ($domain=='pix.toile-libre.org') // pix.toile-libre.org image hosting
1755 {
1756 parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract image filename.
1757 if (!empty($params) && !empty($params['img'])) return array('src'=>'http://pix.toile-libre.org/upload/thumb/'.urlencode($params['img']),
bb8f712d
KT
1758 'href'=>$href,'style'=>'max-width:120px; max-height:150px','alt'=>'pix.toile-libre.org thumbnail');
1759 }
1760
45034273
SS
1761 if ($domain=='imgur.com')
1762 {
1763 $path = parse_url($url,PHP_URL_PATH);
1764 if (startsWith($path,'/a/')) return array(); // Thumbnails for albums are not available.
1a663a0f 1765 if (startsWith($path,'/r/')) return array('src'=>'https://i.imgur.com/'.basename($path).'s.jpg',
45034273 1766 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1a663a0f 1767 if (startsWith($path,'/gallery/')) return array('src'=>'https://i.imgur.com'.substr($path,8).'s.jpg',
45034273
SS
1768 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1769
1a663a0f 1770 if (substr_count($path,'/')==1) return array('src'=>'https://i.imgur.com/'.substr($path,1).'s.jpg',
45034273
SS
1771 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1772 }
1773 if ($domain=='i.imgur.com')
1774 {
1775 $pi = pathinfo(parse_url($url,PHP_URL_PATH));
1a663a0f 1776 if (!empty($pi['filename'])) return array('src'=>'https://i.imgur.com/'.$pi['filename'].'s.jpg',
45034273
SS
1777 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
1778 }
1779 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
1780 {
1781 if (strpos($url,'dailymotion.com/video/')!==false)
1782 {
1783 $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
1784 return array('src'=>$thumburl,
1785 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'DailyMotion thumbnail');
1786 }
1787 }
1788 if (endsWith($domain,'.imageshack.us'))
1789 {
1790 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1791 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1792 {
1793 $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
1794 return array('src'=>$thumburl,
1795 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'imageshack.us thumbnail');
1796 }
1797 }
1798
1799 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1800 // So we deport the thumbnail generation in order not to slow down page generation
1801 // (and we also cache the thumbnail)
1802
894a3c4b 1803 if (! $conf->get('thumbnail.enable_localcache')) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
45034273
SS
1804
1805 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
1806 || $domain=='vimeo.com'
1807 || $domain=='ted.com' || endsWith($domain,'.ted.com')
1808 || $domain=='xkcd.com' || endsWith($domain,'.xkcd.com')
1809 )
1810 {
1811 if ($domain=='vimeo.com')
ad6c27b7 1812 { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
45034273
SS
1813 $path = parse_url($url,PHP_URL_PATH);
1814 if (!preg_match('!/\d+.+?!',$path)) return array(); // This is not a single video URL.
1815 }
1816 if ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
ad6c27b7 1817 { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
45034273
SS
1818 $path = parse_url($url,PHP_URL_PATH);
1819 if (!preg_match('!/\d+.+?!',$path)) return array();
1820 }
1821 if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
ad6c27b7 1822 { // Make sure this TED URL points to a video (/talks/...)
45034273
SS
1823 $path = parse_url($url,PHP_URL_PATH);
1824 if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
1825 }
da10377b 1826 $sign = hash_hmac('sha256', $url, $conf->get('credentials.salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
482d67bd 1827 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
45034273
SS
1828 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
1829 }
1830
1831 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1832 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1833 // But using the extension will do.
1834 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1835 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1836 {
da10377b 1837 $sign = hash_hmac('sha256', $url, $conf->get('credentials.salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
482d67bd 1838 return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
bb8f712d 1839 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
45034273
SS
1840 }
1841 return array(); // No thumbnail.
1842
1843}
1844
1845
1846// Returns the HTML code to display a thumbnail for a link
1847// with a link to the original URL.
1848// Understands various services (youtube.com...)
ad6c27b7 1849// Input: $url = URL for which the thumbnail must be found.
45034273
SS
1850// $href = if provided, this URL will be followed instead of $url
1851// Returns '' if no thumbnail available.
1852function thumbnail($url,$href=false)
1853{
278d9ee2
A
1854 // FIXME!
1855 global $conf;
1856 $t = computeThumbnail($conf, $url,$href);
45034273 1857 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
bb8f712d 1858
5f85fcd8
A
1859 $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"';
1860 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1861 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1862 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1863 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
45034273
SS
1864 $html.='></a>';
1865 return $html;
1866}
1867
45034273
SS
1868// Returns the HTML code to display a thumbnail for a link
1869// for the picture wall (using lazy image loading)
1870// Understands various services (youtube.com...)
ad6c27b7 1871// Input: $url = URL for which the thumbnail must be found.
45034273
SS
1872// $href = if provided, this URL will be followed instead of $url
1873// Returns '' if no thumbnail available.
278d9ee2 1874function lazyThumbnail($conf, $url,$href=false)
45034273 1875{
278d9ee2
A
1876 // FIXME!
1877 global $conf;
1878 $t = computeThumbnail($conf, $url,$href);
45034273
SS
1879 if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
1880
5f85fcd8 1881 $html='<a href="'.escape($t['href']).'">';
bb8f712d 1882
34047d23 1883 // Lazy image
5f85fcd8 1884 $html.='<img class="b-lazy" src="#" data-src="'.escape($t['src']).'"';
858c5c2b 1885
5f85fcd8
A
1886 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1887 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1888 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1889 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
45034273 1890 $html.='>';
bb8f712d 1891
ad6c27b7 1892 // No-JavaScript fallback.
5f85fcd8
A
1893 $html.='<noscript><img src="'.escape($t['src']).'"';
1894 if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
1895 if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
1896 if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
1897 if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
45034273 1898 $html.='></noscript></a>';
bb8f712d 1899
45034273
SS
1900 return $html;
1901}
1902
1903
278d9ee2
A
1904/**
1905 * Installation
1906 * This function should NEVER be called if the file data/config.php exists.
1907 *
ebd650c0
V
1908 * @param ConfigManager $conf Configuration Manager instance.
1909 * @param SessionManager $sessionManager SessionManager instance
278d9ee2 1910 */
ebd650c0 1911function install($conf, $sessionManager) {
45034273 1912 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
f6a6ca0a 1913 if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
45034273 1914
f37664a2
SS
1915
1916 // This part makes sure sessions works correctly.
1917 // (Because on some hosts, session.save_path may not be set correctly,
1918 // or we may not have write access to it.)
1919 if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working'))
12266213
A
1920 {
1921 // Step 2: Check if data in session is correct.
1922 $msg = t(
1923 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1924 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1925 'and that you have write access to it.<br>'.
1926 'It currently points to %s.<br>'.
1927 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1928 'or any custom hostname without a dot causes cookie storage to fail. '.
1929 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1930 );
1931 $msg = sprintf($msg, session_save_path());
1932 echo $msg;
1933 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
f37664a2
SS
1934 die;
1935 }
1936 if (!isset($_SESSION['session_tested']))
1937 { // Step 1 : Try to store data in session and reload page.
1938 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
482d67bd 1939 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
f37664a2
SS
1940 }
1941 if (isset($_GET['test_session']))
ad6c27b7 1942 { // Step 3: Sessions are OK. Remove test parameter from URL.
482d67bd 1943 header('Location: '.index_url($_SERVER));
f37664a2
SS
1944 }
1945
1946
45034273
SS
1947 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1948 {
1949 $tz = 'UTC';
12ff86c9
A
1950 if (!empty($_POST['continent']) && !empty($_POST['city'])
1951 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1952 ) {
1953 $tz = $_POST['continent'].'/'.$_POST['city'];
d1e2f8e5 1954 }
da10377b 1955 $conf->set('general.timezone', $tz);
684e662a 1956 $login = $_POST['setlogin'];
da10377b 1957 $conf->set('credentials.login', $login);
684e662a 1958 $salt = sha1(uniqid('', true) .'_'. mt_rand());
da10377b
A
1959 $conf->set('credentials.salt', $salt);
1960 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
684e662a 1961 if (!empty($_POST['title'])) {
7f179985 1962 $conf->set('general.title', escape($_POST['title']));
684e662a 1963 } else {
da10377b 1964 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
684e662a 1965 }
f39580c6 1966 $conf->set('translation.language', escape($_POST['language']));
894a3c4b 1967 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
cbfdcff2
A
1968 $conf->set('api.enabled', !empty($_POST['enableApi']));
1969 $conf->set(
1970 'api.secret',
1971 generate_api_secret(
e3a430ba
A
1972 $conf->get('credentials.login'),
1973 $conf->get('credentials.salt')
cbfdcff2
A
1974 )
1975 );
dd484b90 1976 try {
684e662a
A
1977 // Everything is ok, let's create config file.
1978 $conf->write(isLoggedIn());
dd484b90
A
1979 }
1980 catch(Exception $e) {
1981 error_log(
1982 'ERROR while writing config file after installation.' . PHP_EOL .
1983 $e->getMessage()
1984 );
1985
1986 // TODO: do not handle exceptions/errors in JS.
1987 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1988 exit;
1989 }
fe16b01e 1990 echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
45034273
SS
1991 exit;
1992 }
1993
ebd650c0 1994 $PAGE = new PageBuilder($conf, null, $sessionManager->generateToken());
ae3aa968
A
1995 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1996 $PAGE->assign('continents', $continents);
1997 $PAGE->assign('cities', $cities);
f39580c6 1998 $PAGE->assign('languages', Languages::getAvailableLanguages());
45034273
SS
1999 $PAGE->renderPage('install');
2000 exit;
2001}
2002
278d9ee2
A
2003/**
2004 * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
2005 * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
2006 * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
2007 * This function is called by passing the URL:
2008 * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
2009 * [URL] is the URL of the link (e.g. a flickr page)
2010 * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
2011 * The function below will fetch the image from the webservice and store it in the cache.
2012 *
2013 * @param ConfigManager $conf Configuration Manager instance,
2014 */
2015function genThumbnail($conf)
45034273
SS
2016{
2017 // Make sure the parameters in the URL were generated by us.
da10377b 2018 $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt'));
ad6c27b7 2019 if ($sign!=$_GET['hmac']) die('Naughty boy!');
45034273 2020
894a3c4b 2021 $cacheDir = $conf->get('resource.thumbnails_cache', 'cache');
45034273
SS
2022 // Let's see if we don't already have the image for this URL in the cache.
2023 $thumbname=hash('sha1',$_GET['url']).'.jpg';
684e662a 2024 if (is_file($cacheDir .'/'. $thumbname))
45034273
SS
2025 { // We have the thumbnail, just serve it:
2026 header('Content-Type: image/jpeg');
684e662a 2027 echo file_get_contents($cacheDir .'/'. $thumbname);
45034273
SS
2028 return;
2029 }
2030 // We may also serve a blank image (if service did not respond)
2031 $blankname=hash('sha1',$_GET['url']).'.gif';
684e662a 2032 if (is_file($cacheDir .'/'. $blankname))
45034273
SS
2033 {
2034 header('Content-Type: image/gif');
684e662a 2035 echo file_get_contents($cacheDir .'/'. $blankname);
45034273
SS
2036 return;
2037 }
2038
2039 // Otherwise, generate the thumbnail.
2040 $url = $_GET['url'];
2041 $domain = parse_url($url,PHP_URL_HOST);
2042
2043 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
2044 {
ad6c27b7 2045 // Crude replacement to handle new flickr domain policy (They prefer www. now)
45034273
SS
2046 $url = str_replace('http://flickr.com/','http://www.flickr.com/',$url);
2047
2048 // Is this a link to an image, or to a flickr page ?
2049 $imageurl='';
5046bcb6 2050 if (endsWith(parse_url($url, PHP_URL_PATH), '.jpg'))
ad6c27b7 2051 { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
45034273
SS
2052 preg_match('!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
2053 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
2054 }
ad6c27b7 2055 else // This is a flickr page (html)
45034273 2056 {
451314eb 2057 // Get the flickr html page.
1557cefb 2058 list($headers, $content) = get_http_response($url, 20);
451314eb 2059 if (strpos($headers[0], '200 OK') !== false)
45034273 2060 {
ad6c27b7 2061 // flickr now nicely provides the URL of the thumbnail in each flickr page.
1557cefb 2062 preg_match('!<link rel=\"image_src\" href=\"(.+?)\"!', $content, $matches);
45034273
SS
2063 if (!empty($matches[1])) $imageurl=$matches[1];
2064
2065 // In albums (and some other pages), the link rel="image_src" is not provided,
2066 // but flickr provides:
2067 // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
2068 if ($imageurl=='')
2069 {
1557cefb 2070 preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!', $content, $matches);
45034273
SS
2071 if (!empty($matches[1])) $imageurl=$matches[1];
2072 }
2073 }
2074 }
2075
2076 if ($imageurl!='')
2077 { // Let's download the image.
451314eb 2078 // Image is 240x120, so 10 seconds to download should be enough.
1557cefb 2079 list($headers, $content) = get_http_response($imageurl, 10);
451314eb 2080 if (strpos($headers[0], '200 OK') !== false) {
1557cefb 2081 // Save image to cache.
684e662a 2082 file_put_contents($cacheDir .'/'. $thumbname, $content);
45034273 2083 header('Content-Type: image/jpeg');
1557cefb 2084 echo $content;
45034273
SS
2085 return;
2086 }
2087 }
2088 }
2089
2090 elseif ($domain=='vimeo.com' )
2091 {
2092 // This is more complex: we have to perform a HTTP request, then parse the result.
ad6c27b7 2093 // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
45034273 2094 $vid = substr(parse_url($url,PHP_URL_PATH),1);
1557cefb 2095 list($headers, $content) = get_http_response('https://vimeo.com/api/v2/video/'.escape($vid).'.php', 5);
451314eb 2096 if (strpos($headers[0], '200 OK') !== false) {
1557cefb 2097 $t = unserialize($content);
45034273
SS
2098 $imageurl = $t[0]['thumbnail_medium'];
2099 // Then we download the image and serve it to our client.
1557cefb 2100 list($headers, $content) = get_http_response($imageurl, 10);
451314eb 2101 if (strpos($headers[0], '200 OK') !== false) {
1557cefb 2102 // Save image to cache.
684e662a 2103 file_put_contents($cacheDir .'/'. $thumbname, $content);
45034273 2104 header('Content-Type: image/jpeg');
1557cefb 2105 echo $content;
45034273
SS
2106 return;
2107 }
2108 }
2109 }
2110
2111 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
2112 {
2113 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
2114 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
2115 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
1557cefb 2116 list($headers, $content) = get_http_response($url, 5);
451314eb 2117 if (strpos($headers[0], '200 OK') !== false) {
45034273 2118 // Extract the link to the thumbnail
1557cefb 2119 preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!', $content, $matches);
45034273
SS
2120 if (!empty($matches[1]))
2121 { // Let's download the image.
2122 $imageurl=$matches[1];
451314eb 2123 // No control on image size, so wait long enough
1557cefb 2124 list($headers, $content) = get_http_response($imageurl, 20);
451314eb 2125 if (strpos($headers[0], '200 OK') !== false) {
684e662a 2126 $filepath = $cacheDir .'/'. $thumbname;
1557cefb 2127 file_put_contents($filepath, $content); // Save image to cache.
45034273
SS
2128 if (resizeImage($filepath))
2129 {
2130 header('Content-Type: image/jpeg');
2131 echo file_get_contents($filepath);
2132 return;
2133 }
2134 }
2135 }
2136 }
2137 }
bb8f712d 2138
45034273
SS
2139 elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
2140 {
2141 // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
2142 // http://xkcd.com/327/
2143 // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
1557cefb 2144 list($headers, $content) = get_http_response($url, 5);
451314eb 2145 if (strpos($headers[0], '200 OK') !== false) {
45034273 2146 // Extract the link to the thumbnail
1557cefb 2147 preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!', $content, $matches);
45034273
SS
2148 if (!empty($matches[1]))
2149 { // Let's download the image.
2150 $imageurl=$matches[1];
451314eb 2151 // No control on image size, so wait long enough
1557cefb 2152 list($headers, $content) = get_http_response($imageurl, 20);
451314eb 2153 if (strpos($headers[0], '200 OK') !== false) {
684e662a 2154 $filepath = $cacheDir.'/'.$thumbname;
1557cefb
A
2155 // Save image to cache.
2156 file_put_contents($filepath, $content);
45034273
SS
2157 if (resizeImage($filepath))
2158 {
2159 header('Content-Type: image/jpeg');
2160 echo file_get_contents($filepath);
2161 return;
2162 }
2163 }
2164 }
2165 }
bb8f712d 2166 }
45034273
SS
2167
2168 else
2169 {
2170 // For all other domains, we try to download the image and make a thumbnail.
451314eb 2171 // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
1557cefb 2172 list($headers, $content) = get_http_response($url, 30);
451314eb 2173 if (strpos($headers[0], '200 OK') !== false) {
684e662a 2174 $filepath = $cacheDir .'/'.$thumbname;
1557cefb
A
2175 // Save image to cache.
2176 file_put_contents($filepath, $content);
45034273
SS
2177 if (resizeImage($filepath))
2178 {
2179 header('Content-Type: image/jpeg');
2180 echo file_get_contents($filepath);
2181 return;
2182 }
2183 }
2184 }
2185
2186
2187 // Otherwise, return an empty image (8x8 transparent gif)
2188 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
684e662a
A
2189 // Also put something in cache so that this URL is not requested twice.
2190 file_put_contents($cacheDir .'/'. $blankname, $blankgif);
45034273
SS
2191 header('Content-Type: image/gif');
2192 echo $blankgif;
2193}
2194
2195// Make a thumbnail of the image (to width: 120 pixels)
2196// Returns true if success, false otherwise.
2197function resizeImage($filepath)
2198{
2199 if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
2200
2201 // Trick: some stupid people rename GIF as JPEG... or else.
2202 // So we really try to open each image type whatever the extension is.
2203 $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
2204 $im=false;
2205 $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
2206 $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
2207 $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
2208 if (!$im) return false; // Unable to open image (corrupted or not an image)
2209 $w = imagesx($im);
2210 $h = imagesy($im);
2211 $ystart = 0; $yheight=$h;
2212 if ($h>$w) { $ystart= ($h/2)-($w/2); $yheight=$w/2; }
2213 $nw = 120; // Desired width
2214 $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
2215 // Resize image:
2216 $im2 = imagecreatetruecolor($nw,$nh);
2217 imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
2218 imageinterlace($im2,true); // For progressive JPEG.
2219 $tempname=$filepath.'_TEMP.jpg';
2220 imagejpeg($im2, $tempname, 90);
2221 imagedestroy($im);
2222 imagedestroy($im2);
9e820906 2223 unlink($filepath);
45034273
SS
2224 rename($tempname,$filepath); // Overwrite original picture with thumbnail.
2225 return true;
2226}
2227
278d9ee2
A
2228if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf); exit; } // Thumbnail generation/cache does not need the link database.
2229if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf); exit; }
684e662a 2230if (!isset($_SESSION['LINKS_PER_PAGE'])) {
da10377b 2231 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
684e662a 2232}
18e67967 2233
3b67b222
A
2234try {
2235 $history = new History($conf->get('resource.history'));
2236} catch(Exception $e) {
2237 die($e->getMessage());
2238}
2239
18e67967
A
2240$linkDb = new LinkDB(
2241 $conf->get('resource.datastore'),
2242 isLoggedIn(),
2243 $conf->get('privacy.hide_public_links'),
2244 $conf->get('redirector.url'),
2245 $conf->get('redirector.encode_url')
2246);
2247
2248$container = new \Slim\Container();
2249$container['conf'] = $conf;
2250$container['plugins'] = $pluginManager;
813849e5 2251$container['history'] = $history;
18e67967
A
2252$app = new \Slim\App($container);
2253
2254// REST API routes
2255$app->group('/api/v1', function() {
68016e37
A
2256 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
2257 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
2258 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
2259 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
cf9181dd 2260 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
0843848c 2261 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
61d40693 2262 $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
465b1c40 2263})->add('\Shaarli\Api\ApiMiddleware');
18e67967
A
2264
2265$response = $app->run(true);
2266// Hack to make Slim and Shaarli router work together:
16e3d006
A
2267// If a Slim route isn't found and NOT API call, we call renderPage().
2268if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
18e67967
A
2269 // We use UTF-8 for proper international characters handling.
2270 header('Content-Type: text/html; charset=utf-8');
44acf706 2271 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
18e67967
A
2272} else {
2273 $app->respond($response);
2274}