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