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