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