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