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