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