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