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