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