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