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