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