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