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