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