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