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