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