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