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