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