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