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