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