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