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