]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - index.php
Version 0.0.32 beta:
[github/shaarli/Shaarli.git] / index.php
CommitLineData
ef734b5d 1<?php
24e267ca 2// Shaarli 0.0.32 beta - Shaare your links...
ef734b5d
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
4887ceda 7// Requires: php 5.1.x
008d8b95 8// (but autocomplete fields will only work if you have php 5.2.x)
ef734b5d
SS
9// -----------------------------------------------------------------------------------------------
10// User config:
008d8b95
SS
11$GLOBALS['config']['DATADIR'] = 'data'; // Data subdirectory
12$GLOBALS['config']['CONFIG_FILE'] = $GLOBALS['config']['DATADIR'].'/config.php'; // Configuration file (user login/password)
13$GLOBALS['config']['DATASTORE'] = $GLOBALS['config']['DATADIR'].'/datastore.php'; // Data storage file.
14$GLOBALS['config']['LINKS_PER_PAGE'] = 20; // Default links per page.
15$GLOBALS['config']['IPBANS_FILENAME'] = $GLOBALS['config']['DATADIR'].'/ipbans.php'; // File storage for failures and bans.
16$GLOBALS['config']['BAN_AFTER'] = 4; // Ban IP after this many failures.
17$GLOBALS['config']['BAN_DURATION'] = 1800; // Ban duration for IP address after login failures (in seconds) (1800 sec. = 30 minutes)
18$GLOBALS['config']['OPEN_SHAARLI'] = false; // If true, anyone can add/edit/delete links without having to login
19$GLOBALS['config']['HIDE_TIMESTAMPS'] = false; // If true, the moment when links were saved are not shown to users that are not logged in.
20$GLOBALS['config']['ENABLE_THUMBNAILS'] = true; // Enable thumbnails in links.
21$GLOBALS['config']['CACHEDIR'] = 'cache'; // Cache directory for thumbnails for SLOW services (like flickr)
22$GLOBALS['config']['ENABLE_LOCALCACHE'] = true; // Enable Shaarli to store thumbnail in a local cache. Disable to reduce webspace usage.
751aaefe 23$GLOBALS['config']['PUBSUBHUB_URL'] = ''; // PubSubHubbub support. Put an empty string to disable, or put your hub url here to enable.
24e267ca 24 // Note: You must have publisher.php in the same directory as Shaarli index.php
ca201236
SS
25// -----------------------------------------------------------------------------------------------
26// Program config (touch at your own risks !)
008d8b95
SS
27$GLOBALS['config']['UPDATECHECK_FILENAME'] = $GLOBALS['config']['DATADIR'].'/lastupdatecheck.txt'; // For updates check of Shaarli.
28$GLOBALS['config']['UPDATECHECK_INTERVAL'] = 86400 ; // Updates check frequency for Shaarli. 86400 seconds=24 hours
ef4275c5
SS
29ini_set('max_input_time','60'); // High execution time in case of problematic imports/exports.
30ini_set('memory_limit', '128M'); // Try to set max upload file size and read (May not work on some hosts).
31ini_set('post_max_size', '16M');
32ini_set('upload_max_filesize', '16M');
33define('PHPPREFIX','<?php /* '); // Prefix to encapsulate data in php code.
34define('PHPSUFFIX',' */ ?>'); // Suffix to encapsulate data in php code.
4887ceda 35checkphpversion();
4887ceda
SS
36error_reporting(E_ALL^E_WARNING); // See all error except warnings.
37//error_reporting(-1); // See all errors (for debugging only)
24e267ca
SS
38
39include "inc/rain.tpl.class.php"; //include Rain TPL
40raintpl::$tpl_dir = "tpl/"; // template directory
41raintpl::$cache_dir = "tmp/"; // cache directory
42
ef734b5d 43ob_start();
f4aba1ac 44
008d8b95
SS
45// Optionnal config file.
46if (is_file($GLOBALS['config']['DATADIR'].'/options.php')) require($GLOBALS['config']['DATADIR'].'/options.php');
47
ef4275c5 48// In case stupid admin has left magic_quotes enabled in php.ini:
24e267ca 49if (get_magic_quotes_gpc())
ef4275c5
SS
50{
51 function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; }
52 $_POST = array_map('stripslashes_deep', $_POST);
53 $_GET = array_map('stripslashes_deep', $_GET);
54 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
55}
ef734b5d
SS
56// Prevent caching: (yes, it's ugly)
57header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
58header("Cache-Control: no-store, no-cache, must-revalidate");
59header("Cache-Control: post-check=0, pre-check=0", false);
60header("Pragma: no-cache");
24e267ca 61define('shaarli_version','0.0.32 beta');
008d8b95 62if (!is_dir($GLOBALS['config']['DATADIR'])) { mkdir($GLOBALS['config']['DATADIR'],0705); chmod($GLOBALS['config']['DATADIR'],0705); }
24e267ca 63if (!is_file($GLOBALS['config']['DATADIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['DATADIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.
008d8b95
SS
64if ($GLOBALS['config']['ENABLE_LOCALCACHE'])
65{
66 if (!is_dir($GLOBALS['config']['CACHEDIR'])) { mkdir($GLOBALS['config']['CACHEDIR'],0705); chmod($GLOBALS['config']['CACHEDIR'],0705); }
24e267ca 67 if (!is_file($GLOBALS['config']['CACHEDIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['CACHEDIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.
008d8b95
SS
68}
69if (!is_file($GLOBALS['config']['CONFIG_FILE'])) install();
70require $GLOBALS['config']['CONFIG_FILE']; // Read login/password hash into $GLOBALS.
ba0718dc 71// Small protection against dodgy config files:
24e267ca 72if (empty($GLOBALS['title'])) $GLOBALS['title']='Shared links on '.htmlspecialchars(indexUrl());
ba0718dc 73if (empty($GLOBALS['timezone'])) $GLOBALS['timezone']=date_default_timezone_get();
ef734b5d
SS
74autoLocale(); // Sniff browser language and set date format accordingly.
75header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling.
76$LINKSDB=false;
77
24e267ca 78// Check php version
4887ceda
SS
79function checkphpversion()
80{
e6a0ab54 81 if (version_compare(PHP_VERSION, '5.1.0') < 0)
4887ceda 82 {
ca201236 83 header('Content-Type: text/plain; charset=utf-8');
e6a0ab54 84 echo 'Your server supports php '.PHP_VERSION.'. Shaarli requires at last php 5.1.0, and thus cannot run. Sorry.';
ca201236 85 exit;
24e267ca 86 }
e6a0ab54
SS
87}
88
89// Checks if an update is available for Shaarli.
90// (at most once a day, and only for registered user.)
91// Output: '' = no new version.
92// other= the available version.
93function checkUpdate()
94{
95 if (!isLoggedIn()) return ''; // Do not check versions for visitors.
24e267ca 96
e6a0ab54 97 // Get latest version number at most once a day.
008d8b95 98 if (!is_file($GLOBALS['config']['UPDATECHECK_FILENAME']) || (filemtime($GLOBALS['config']['UPDATECHECK_FILENAME'])<time()-($GLOBALS['config']['UPDATECHECK_INTERVAL'])))
e6a0ab54
SS
99 {
100 $version=shaarli_version;
101 list($httpstatus,$headers,$data) = getHTTP('http://sebsauvage.net/files/shaarli_version.txt',2);
6d946e78 102 if (strpos($httpstatus,'200 OK')!==false) $version=$data;
24e267ca 103 // If failed, nevermind. We don't want to bother the user with that.
008d8b95 104 file_put_contents($GLOBALS['config']['UPDATECHECK_FILENAME'],$version); // touch file date
4887ceda 105 }
e6a0ab54 106 // Compare versions:
008d8b95 107 $newestversion=file_get_contents($GLOBALS['config']['UPDATECHECK_FILENAME']);
8e92abac 108 if (version_compare($newestversion,shaarli_version)==1) return $newestversion;
e6a0ab54 109 return '';
4887ceda
SS
110}
111
ef734b5d
SS
112// -----------------------------------------------------------------------------------------------
113// Log to text file
114function logm($message)
115{
f4aba1ac 116 $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."\n";
008d8b95 117 file_put_contents($GLOBALS['config']['DATADIR'].'/log.txt',$t,FILE_APPEND);
ef734b5d
SS
118}
119
99c9c954
SS
120/* Returns the small hash of a string
121 eg. smallHash('20111006_131924') --> yZH23w
122 Small hashes:
123 - are unique (well, as unique as crc32, at last)
124 - are always 6 characters long.
125 - only use the following characters: a-z A-Z 0-9 - _ @
126 - are NOT cryptographically secure (they CAN be forged)
127 In Shaarli, they are used as a tinyurl-like link to individual entries.
24e267ca 128*/
99c9c954
SS
129function smallHash($text)
130{
131 $t = rtrim(base64_encode(hash('crc32',$text,true)),'=');
132 $t = str_replace('+','-',$t); // Get rid of characters which need encoding in URLs.
133 $t = str_replace('/','_',$t);
134 $t = str_replace('=','@',$t);
135 return $t;
136}
137
138// Function inspired from http://www.php.net/manual/en/function.preg-replace.php#85722
139function text2clickable($url)
140{
008d8b95 141 $redir = empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'];
03cd3750 142 return preg_replace('!((?:https?|ftp)://\S+[[:alnum:]]/?)!si','<a href="'.$redir.'$1" rel="nofollow">$1</a>',$url);
99c9c954 143}
24e267ca
SS
144
145// This function inserts &nbsp; where relevant so that multiple spaces are properly displayed in HTML
146// even in the absence of <pre> (This is used in description to keep text formatting)
147function keepMultipleSpaces($text)
148{
149 return str_replace(' ',' &nbsp;',$text);
150
151}
ef734b5d
SS
152// ------------------------------------------------------------------------------------------
153// Sniff browser language to display dates in the right format automatically.
154// (Note that is may not work on your server if the corresponding local is not installed.)
155function autoLocale()
24e267ca 156{
ef734b5d
SS
157 $loc='en_US'; // Default if browser does not send HTTP_ACCEPT_LANGUAGE
158 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) // eg. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
159 { // (It's a bit crude, but it works very well. Prefered language is always presented first.)
160 if (preg_match('/([a-z]{2}(-[a-z]{2})?)/i',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches)) $loc=$matches[1];
161 }
162 setlocale(LC_TIME,$loc); // LC_TIME = Set local for date/time format only.
163}
164
6d946e78 165// ------------------------------------------------------------------------------------------
751aaefe 166// PubSubHubbub protocol support (if enabled) [UNTESTED]
6d946e78
SS
167// (Source: http://aldarone.fr/les-flux-rss-shaarli-et-pubsubhubbub/ )
168if (!empty($GLOBALS['config']['PUBSUBHUB_URL'])) include './publisher.php';
169function pubsubhub()
170{
171 if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
172 {
173 $p = new Publisher($GLOBALS['config']['PUBSUBHUB_URL']);
174 $topic_url = array (
24e267ca
SS
175 indexUrl().'?do=atom',
176 indexUrl().'?do=rss'
6d946e78
SS
177 );
178 $p->publish_update($topic_url);
179 }
180}
181
ef734b5d
SS
182// ------------------------------------------------------------------------------------------
183// Session management
184define('INACTIVITY_TIMEOUT',3600); // (in seconds). If the user does not access any page within this time, his/her session is considered expired.
185ini_set('session.use_cookies', 1); // Use cookies to store session.
186ini_set('session.use_only_cookies', 1); // Force cookies for session (phpsessionID forbidden in URL)
187ini_set('session.use_trans_sid', false); // Prevent php to use sessionID in URL if cookies are disabled.
188session_name('shaarli');
189session_start();
190
191// Returns the IP address of the client (Used to prevent session cookie hijacking.)
192function allIPs()
193{
194 $ip = $_SERVER["REMOTE_ADDR"];
195 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
196 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$ip.'_'.$_SERVER['HTTP_X_FORWARDED_FOR']; }
197 if (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip=$ip.'_'.$_SERVER['HTTP_CLIENT_IP']; }
198 return $ip;
199}
200
201// Check that user/password is correct.
24e267ca 202function check_auth($login,$password)
ef734b5d
SS
203{
204 $hash = sha1($password.$login.$GLOBALS['salt']);
205 if ($login==$GLOBALS['login'] && $hash==$GLOBALS['hash'])
206 { // Login/password is correct.
207 $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // generate unique random number (different than phpsessionid)
208 $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked.
209 $_SESSION['username']=$login;
210 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration.
211 logm('Login successful');
212 return True;
213 }
214 logm('Login failed for user '.$login);
215 return False;
216}
217
218// Returns true if the user is logged in.
219function isLoggedIn()
24e267ca
SS
220{
221 if ($GLOBALS['config']['OPEN_SHAARLI']) return true;
222
ef734b5d
SS
223 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
224 if (empty($_SESSION['uid']) || $_SESSION['ip']!=allIPs() || time()>=$_SESSION['expires_on'])
225 {
226 logout();
227 return false;
228 }
28770b26
SS
229 if (!empty($_SESSION['longlastingsession'])) $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // In case of "Stay signed in" checked.
230 else $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Standard session expiration date.
24e267ca 231
ef734b5d
SS
232 return true;
233}
234
235// Force logout.
ba0718dc 236function logout() { if (isset($_SESSION)) { unset($_SESSION['uid']); unset($_SESSION['ip']); unset($_SESSION['username']);} }
ef734b5d
SS
237
238
239// ------------------------------------------------------------------------------------------
240// Brute force protection system
241// Several consecutive failed logins will ban the IP address for 30 minutes.
008d8b95
SS
242if (!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?>");
243include $GLOBALS['config']['IPBANS_FILENAME'];
ef734b5d
SS
244// Signal a failed login. Will ban the IP if too many failures:
245function ban_loginFailed()
246{
247 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
248 if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0;
249 $gb['FAILURES'][$ip]++;
008d8b95 250 if ($gb['FAILURES'][$ip]>($GLOBALS['config']['BAN_AFTER']-1))
ef734b5d 251 {
008d8b95 252 $gb['BANS'][$ip]=time()+$GLOBALS['config']['BAN_DURATION'];
ef734b5d
SS
253 logm('IP address banned from login');
254 }
255 $GLOBALS['IPBANS'] = $gb;
008d8b95 256 file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
ef734b5d
SS
257}
258
259// Signals a successful login. Resets failed login counter.
260function ban_loginOk()
261{
262 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
263 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
264 $GLOBALS['IPBANS'] = $gb;
008d8b95 265 file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
ef734b5d
SS
266}
267
268// Checks if the user CAN login. If 'true', the user can try to login.
269function ban_canLogin()
270{
271 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
272 if (isset($gb['BANS'][$ip]))
273 {
274 // User is banned. Check if the ban has expired:
24e267ca 275 if ($gb['BANS'][$ip]<=time())
ef734b5d
SS
276 { // Ban expired, user can try to login again.
277 logm('Ban lifted.');
278 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
008d8b95 279 file_put_contents($GLOBALS['config']['IPBANS_FILENAME'], "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
ef734b5d
SS
280 return true; // Ban has expired, user can login.
281 }
282 return false; // User is banned.
283 }
284 return true; // User is not banned.
285}
286
287// ------------------------------------------------------------------------------------------
288// Process login form: Check if login/password is correct.
289if (isset($_POST['login']))
290{
291 if (!ban_canLogin()) die('I said: NO. You are banned for the moment. Go away.');
292 if (isset($_POST['password']) && tokenOk($_POST['token']) && (check_auth($_POST['login'], $_POST['password'])))
293 { // Login/password is ok.
24e267ca 294 ban_loginOk();
28770b26
SS
295 // If user wants to keep the session cookie even after the browser closes:
296 if (!empty($_POST['longlastingsession']))
297 {
298 $_SESSION['longlastingsession']=31536000; // (31536000 seconds = 1 year)
299 $_SESSION['expires_on']=time()+$_SESSION['longlastingsession']; // Set session expiration on server-side.
24e267ca 300 session_set_cookie_params($_SESSION['longlastingsession']); // Set session cookie expiration on client side
28770b26
SS
301 session_regenerate_id(true); // Send cookie with new expiration date to browser.
302 }
303 else // Standard session expiration (=when browser closes)
304 {
305 session_set_cookie_params(0); // 0 means "When browser closes"
24e267ca 306 session_regenerate_id(true);
28770b26 307 }
ef734b5d 308 // Optional redirect after login:
28770b26 309 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; }
eae4f48b 310 if (isset($_POST['returnurl']))
24e267ca 311 {
eae4f48b 312 if (endsWith($_POST['returnurl'],'?do=login')) { header('Location: ?'); exit; } // Prevent loops over login screen.
24e267ca 313 header('Location: '.$_POST['returnurl']); exit;
eae4f48b 314 }
ef734b5d
SS
315 header('Location: ?'); exit;
316 }
317 else
318 {
24e267ca 319 ban_loginFailed();
ef734b5d 320 echo '<script language="JavaScript">alert("Wrong login/password.");document.location=\'?do=login\';</script>'; // Redirect to login screen.
24e267ca 321 exit;
ef734b5d 322 }
24e267ca 323}
ef734b5d
SS
324
325// ------------------------------------------------------------------------------------------
326// Misc utility functions:
327
328// Returns the server URL (including port and http/https), without path.
329// eg. "http://myserver.com:8080"
330// You can append $_SERVER['SCRIPT_NAME'] to get the current script URL.
331function serverUrl()
332{
24e267ca 333 $serverport = ($_SERVER["SERVER_PORT"]=='80' || (!empty($_SERVER['HTTPS']) && $_SERVER["SERVER_PORT"]=='443') ? '' : ':'.$_SERVER["SERVER_PORT"]);
ef734b5d
SS
334 return 'http'.(!empty($_SERVER['HTTPS'])?'s':'').'://'.$_SERVER["SERVER_NAME"].$serverport;
335}
336
24e267ca
SS
337function indexUrl()
338{
339 return serverUrl() . ($_SERVER["SCRIPT_NAME"] == '/index.php' ? '' : $_SERVER["SCRIPT_NAME"]);
340}
341
ef734b5d 342// Convert post_max_size/upload_max_filesize (eg.'16M') parameters to bytes.
24e267ca 343function return_bytes($val)
ef734b5d
SS
344{
345 $val = trim($val); $last=strtolower($val[strlen($val)-1]);
24e267ca 346 switch($last)
ef734b5d
SS
347 {
348 case 'g': $val *= 1024;
349 case 'm': $val *= 1024;
350 case 'k': $val *= 1024;
351 }
352 return $val;
353}
354
355// Try to determine max file size for uploads (POST).
356// Returns an integer (in bytes)
357function getMaxFileSize()
358{
359 $size1 = return_bytes(ini_get('post_max_size'));
360 $size2 = return_bytes(ini_get('upload_max_filesize'));
361 // Return the smaller of two:
362 $maxsize = min($size1,$size2);
363 // FIXME: Then convert back to readable notations ? (eg. 2M instead of 2000000)
364 return $maxsize;
365}
366
367// Tells if a string start with a substring or not.
368function startsWith($haystack,$needle,$case=true)
369{
370 if($case){return (strcmp(substr($haystack, 0, strlen($needle)),$needle)===0);}
371 return (strcasecmp(substr($haystack, 0, strlen($needle)),$needle)===0);
372}
373
374// Tells if a string ends with a substring or not.
375function endsWith($haystack,$needle,$case=true)
376{
377 if($case){return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);}
378 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);
379}
380
381/* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
382 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
383 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
384function linkdate2timestamp($linkdate)
385{
386 $Y=$M=$D=$h=$m=$s=0;
387 $r = sscanf($linkdate,'%4d%2d%2d_%2d%2d%2d',$Y,$M,$D,$h,$m,$s);
388 return mktime($h,$m,$s,$M,$D,$Y);
389}
390
391/* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
392 (used to build the pubDate attribute in RSS feed.) */
393function linkdate2rfc822($linkdate)
394{
395 return date('r',linkdate2timestamp($linkdate)); // 'r' is for RFC822 date format.
396}
397
8e92abac
SS
398/* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a ISO 8601 date.
399 (used to build the updated tags in ATOM feed.) */
400function linkdate2iso8601($linkdate)
401{
402 return date('c',linkdate2timestamp($linkdate)); // 'c' is for ISO 8601 date format.
403}
404
ef734b5d
SS
405/* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a localized date format.
406 (used to display link date on screen)
f4aba1ac 407 The date format is automatically chosen according to locale/languages sniffed from browser headers (see autoLocale()). */
ef734b5d
SS
408function linkdate2locale($linkdate)
409{
410 return utf8_encode(strftime('%c',linkdate2timestamp($linkdate))); // %c is for automatic date format according to locale.
411 // Note that if you use a local which is not installed on your webserver,
412 // the date will not be displayed in the chosen locale, but probably in US notation.
413}
414
415// Parse HTTP response headers and return an associative array.
24e267ca 416function http_parse_headers_shaarli( $headers )
ef734b5d
SS
417{
418 $res=array();
419 foreach($headers as $header)
420 {
421 $i = strpos($header,': ');
6d946e78 422 if ($i!==false)
ef734b5d
SS
423 {
424 $key=substr($header,0,$i);
425 $value=substr($header,$i+2,strlen($header)-$i-2);
426 $res[$key]=$value;
427 }
428 }
429 return $res;
430}
431
432/* GET an URL.
433 Input: $url : url to get (http://...)
434 $timeout : Network timeout (will wait this many seconds for an anwser before giving up).
4887ceda 435 Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK") or error message
ef734b5d
SS
436 [1] = associative array containing HTTP response headers (eg. echo getHTTP($url)[1]['Content-Type'])
437 [2] = data
438 Example: list($httpstatus,$headers,$data) = getHTTP('http://sebauvage.net/');
6d946e78 439 if (strpos($httpstatus,'200 OK')!==false)
ef734b5d
SS
440 echo 'Data type: '.htmlspecialchars($headers['Content-Type']);
441 else
442 echo 'There was an error: '.htmlspecialchars($httpstatus)
443*/
444function getHTTP($url,$timeout=30)
445{
4887ceda
SS
446 try
447 {
448 $options = array('http'=>array('method'=>'GET','timeout' => $timeout)); // Force network timeout
449 $context = stream_context_create($options);
99c9c954 450 $data=file_get_contents($url,false,$context,-1, 4000000); // We download at most 4 Mb from source.
4887ceda
SS
451 if (!$data) { $lasterror=error_get_last(); return array($lasterror['message'],array(),''); }
452 $httpStatus=$http_response_header[0]; // eg. "HTTP/1.1 200 OK"
6d946e78 453 $responseHeaders=http_parse_headers_shaarli($http_response_header);
4887ceda
SS
454 return array($httpStatus,$responseHeaders,$data);
455 }
456 catch (Exception $e) // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
457 {
458 return array($e->getMessage(),'','');
459 }
ef734b5d
SS
460}
461
462// Extract title from an HTML document.
463// (Returns an empty string if not found.)
24e267ca 464function html_extract_title($html)
ef734b5d 465{
24e267ca 466 return preg_match('!<title>(.*?)</title>!is', $html, $matches) ? trim(str_replace("\n",' ', $matches[1])) : '' ;
ef734b5d
SS
467}
468
469// ------------------------------------------------------------------------------------------
470// Token management for XSRF protection
471// Token should be used in any form which acts on data (create,update,delete,import...).
472if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
473
474// Returns a token.
475function getToken()
476{
477 $rnd = sha1(uniqid('',true).'_'.mt_rand()); // We generate a random string.
478 $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
24e267ca 479 return $rnd;
ef734b5d
SS
480}
481
482// Tells if a token is ok. Using this function will destroy the token.
24e267ca 483// true=token is ok.
ef734b5d
SS
484function tokenOk($token)
485{
486 if (isset($_SESSION['tokens'][$token]))
487 {
488 unset($_SESSION['tokens'][$token]); // Token is used: destroy it.
489 return true; // Token is ok.
490 }
491 return false; // Wrong token, or already used.
492}
493
24e267ca
SS
494// ------------------------------------------------------------------------------------------
495/* This class is in charge of building the final page.
496 (This is basically a wrapper around RainTPL which pre-fills some fields.)
497 p = new pageBuilder;
498 p.assign('myfield','myvalue');
499 p.renderPage('mytemplate');
500
501*/
502class pageBuilder
503{
504 private $tpl; // RainTPL template
505 function __construct()
506 {
507 $this->tpl=false;
508 }
509
510 private function initialize()
511 {
512 global $LINKSDB;
513 $this->tpl = new RainTPL;
514 $this->tpl->assign('newversion',checkUpdate());
515 $this->tpl->assign('linkcount',count($LINKSDB));
516 $this->tpl->assign('feedurl',htmlspecialchars(indexUrl()));
517 $searchcrits=''; // Search criteria
518 if (!empty($_GET['searchtags'])) $searchcrits.='&searchtags='.$_GET['searchtags'];
519 elseif (!empty($_GET['searchterm'])) $searchcrits.='&searchterm='.$_GET['searchterm'];
520 $this->tpl->assign('searchcrits',$searchcrits);
521 $this->tpl->assign('source',indexUrl());
522 $this->tpl->assign('version',shaarli_version);
523 $this->tpl->assign('pagetitle','Shaarli');
524 if (!empty($GLOBALS['title'])) $this->tpl->assign('pagetitle',$GLOBALS['title']);
525 if (!empty($GLOBALS['pagetitle'])) $this->tpl->assign('pagetitle',$GLOBALS['pagetitle']);
526 $this->tpl->assign('shaarlititle',empty($GLOBALS['title']) ? 'Shaarli': $GLOBALS['title'] );
527 return;
528 }
529
530 // The following assign() method is basically the same as RainTPL (except that it's lazy)
531 public function assign($what,$where)
532 {
533 if ($this->tpl===false) $this->initialize(); // Lazy initialization
534 $this->tpl->assign($what,$where);
535 }
536
537 // Render a specific page (using a template).
538 // eg. pb.renderPage('picwall')
539 public function renderPage($page)
540 {
541 if ($this->tpl===false) $this->initialize(); // Lazy initialization
542 $this->tpl->draw($page);
543 }
544}
545
ef734b5d
SS
546// ------------------------------------------------------------------------------------------
547/* Data storage for links.
548 This object behaves like an associative array.
549 Example:
550 $mylinks = new linkdb();
551 echo $mylinks['20110826_161819']['title'];
552 foreach($mylinks as $link)
553 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
24e267ca 554
ef734b5d
SS
555 We implement 3 interfaces:
556 - ArrayAccess so that this object behaves like an associative array.
557 - Iterator so that this object can be used in foreach() loops.
558 - Countable interface so that we can do a count() on this object.
559*/
560class linkdb implements Iterator, Countable, ArrayAccess
ef734b5d
SS
561{
562 private $links; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...)
563 private $urls; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
564 private $keys; // List of linkdate keys (for the Iterator interface implementation)
565 private $position; // Position in the $this->keys array. (for the Iterator interface implementation.)
566 private $loggedin; // Is the used logged in ? (used to filter private links)
567
568 // Constructor:
569 function __construct($isLoggedIn)
570 // Input : $isLoggedIn : is the used logged in ?
571 {
572 $this->loggedin = $isLoggedIn;
573 $this->checkdb(); // Make sure data file exists.
574 $this->readdb(); // Then read it.
24e267ca
SS
575 }
576
ef734b5d
SS
577 // ---- Countable interface implementation
578 public function count() { return count($this->links); }
579
580 // ---- ArrayAccess interface implementation
581 public function offsetSet($offset, $value)
582 {
583 if (!$this->loggedin) die('You are not authorized to add a link.');
584 if (empty($value['linkdate']) || empty($value['url'])) die('Internal Error: A link should always have a linkdate and url.');
585 if (empty($offset)) die('You must specify a key.');
586 $this->links[$offset] = $value;
24e267ca 587 $this->urls[$value['url']]=$offset;
ef734b5d
SS
588 }
589 public function offsetExists($offset) { return array_key_exists($offset,$this->links); }
590 public function offsetUnset($offset)
24e267ca 591 {
ef734b5d 592 if (!$this->loggedin) die('You are not authorized to delete a link.');
24e267ca
SS
593 $url = $this->links[$offset]['url']; unset($this->urls[$url]);
594 unset($this->links[$offset]);
ef734b5d
SS
595 }
596 public function offsetGet($offset) { return isset($this->links[$offset]) ? $this->links[$offset] : null; }
24e267ca 597
ef734b5d
SS
598 // ---- Iterator interface implementation
599 function rewind() { $this->keys=array_keys($this->links); rsort($this->keys); $this->position=0; } // Start over for iteration, ordered by date (latest first).
600 function key() { return $this->keys[$this->position]; } // current key
601 function current() { return $this->links[$this->keys[$this->position]]; } // current value
602 function next() { ++$this->position; } // go to next item
603 function valid() { return isset($this->keys[$this->position]); } // Check if current position is valid.
604
605 // ---- Misc methods
606 private function checkdb() // Check if db directory and file exists.
607 {
008d8b95 608 if (!file_exists($GLOBALS['config']['DATASTORE'])) // Create a dummy database for example.
ef734b5d
SS
609 {
610 $this->links = array();
611 $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');
612 $this->links[$link['linkdate']] = $link;
613 $link = array('title'=>'My secret stuff... - Pastebin.com','url'=>'http://pastebin.com/smCEEeSn','description'=>'SShhhh!! I\'m a private link only YOU can see. You can delete me too.','private'=>1,'linkdate'=>'20110914_074522','tags'=>'secretstuff');
24e267ca 614 $this->links[$link['linkdate']] = $link;
008d8b95 615 file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX); // Write database to disk
24e267ca 616 }
ef734b5d 617 }
24e267ca 618
ef734b5d 619 // Read database from disk to memory
24e267ca 620 private function readdb()
ef734b5d
SS
621 {
622 // Read data
008d8b95 623 $this->links=(file_exists($GLOBALS['config']['DATASTORE']) ? unserialize(gzinflate(base64_decode(substr(file_get_contents($GLOBALS['config']['DATASTORE']),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() );
f4aba1ac 624 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
24e267ca 625
ef734b5d
SS
626 // If user is not logged in, filter private links.
627 if (!$this->loggedin)
628 {
629 $toremove=array();
630 foreach($this->links as $link) { if ($link['private']!=0) $toremove[]=$link['linkdate']; }
631 foreach($toremove as $linkdate) { unset($this->links[$linkdate]); }
632 }
24e267ca 633
ef734b5d
SS
634 // Keep the list of the mapping URLs-->linkdate up-to-date.
635 $this->urls=array();
636 foreach($this->links as $link) { $this->urls[$link['url']]=$link['linkdate']; }
637 }
638
24e267ca
SS
639 // Save database from memory to disk.
640 public function savedb()
ef734b5d
SS
641 {
642 if (!$this->loggedin) die('You are not authorized to change the database.');
008d8b95 643 file_put_contents($GLOBALS['config']['DATASTORE'], PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX);
ef734b5d 644 }
24e267ca 645
ef734b5d 646 // Returns the link for a given URL (if it exists). false it does not exist.
24e267ca 647 public function getLinkFromUrl($url)
ef734b5d
SS
648 {
649 if (isset($this->urls[$url])) return $this->links[$this->urls[$url]];
650 return false;
651 }
652
653 // Case insentitive search among links (in url, title and description). Returns filtered list of links.
f4aba1ac 654 // eg. print_r($mydb->filterFulltext('hollandais'));
24e267ca 655 public function filterFulltext($searchterms)
ef734b5d
SS
656 {
657 // FIXME: explode(' ',$searchterms) and perform a AND search.
658 // FIXME: accept double-quotes to search for a string "as is" ?
659 $filtered=array();
660 $s = strtolower($searchterms);
661 foreach($this->links as $l)
24e267ca 662 {
6d946e78
SS
663 $found= (strpos(strtolower($l['title']),$s)!==false)
664 || (strpos(strtolower($l['description']),$s)!==false)
665 || (strpos(strtolower($l['url']),$s)!==false)
666 || (strpos(strtolower($l['tags']),$s)!==false);
ef734b5d
SS
667 if ($found) $filtered[$l['linkdate']] = $l;
668 }
669 krsort($filtered);
670 return $filtered;
671 }
24e267ca 672
ef734b5d
SS
673 // Filter by tag.
674 // You can specify one or more tags (tags can be separated by space or comma).
675 // eg. print_r($mydb->filterTags('linux programming'));
f4aba1ac 676 public function filterTags($tags,$casesensitive=false)
ef734b5d 677 {
f4aba1ac 678 $t = str_replace(',',' ',($casesensitive?$tags:strtolower($tags)));
ef734b5d
SS
679 $searchtags=explode(' ',$t);
680 $filtered=array();
681 foreach($this->links as $l)
24e267ca 682 {
f4aba1ac 683 $linktags = explode(' ',($casesensitive?$l['tags']:strtolower($l['tags'])));
ef734b5d
SS
684 if (count(array_intersect($linktags,$searchtags)) == count($searchtags))
685 $filtered[$l['linkdate']] = $l;
686 }
687 krsort($filtered);
688 return $filtered;
24e267ca
SS
689 }
690
99c9c954
SS
691 // Filter by smallHash.
692 // Only 1 article is returned.
693 public function filterSmallHash($smallHash)
694 {
695 $filtered=array();
696 foreach($this->links as $l)
24e267ca 697 {
99c9c954
SS
698 if ($smallHash==smallHash($l['linkdate'])) // Yes, this is ugly and slow
699 {
700 $filtered[$l['linkdate']] = $l;
701 return $filtered;
702 }
703 }
704 return $filtered;
24e267ca 705 }
ef734b5d 706
44a9d860
SS
707 // Returns the list of all tags
708 // Output: associative array key=tags, value=0
709 public function allTags()
710 {
711 $tags=array();
712 foreach($this->links as $link)
713 foreach(explode(' ',$link['tags']) as $tag)
ca201236
SS
714 if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1);
715 arsort($tags); // Sort tags by usage (most used tag first)
44a9d860 716 return $tags;
24e267ca 717 }
ef734b5d
SS
718}
719
720// ------------------------------------------------------------------------------------------
721// Ouput the last 50 links in RSS 2.0 format.
722function showRSS()
723{
724 global $LINKSDB;
24e267ca 725
ca201236
SS
726 // Optionnaly filter the results:
727 $linksToDisplay=array();
728 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
f4aba1ac 729 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
ca201236 730 else $linksToDisplay = $LINKSDB;
24e267ca 731
02188b06 732 header('Content-Type: application/rss+xml; charset=utf-8');
24e267ca 733 $pageaddr=htmlspecialchars(indexUrl());
ef734b5d 734 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">';
ba0718dc 735 echo '<channel><title>'.htmlspecialchars($GLOBALS['title']).'</title><link>'.$pageaddr.'</link>';
6d946e78
SS
736 echo '<description>Shared links</description><language>en-en</language><copyright>'.$pageaddr.'</copyright>'."\n\n";
737 if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
738 {
739 echo '<!-- PubSubHubbub Discovery -->';
740 echo '<link rel="hub" href="'.htmlspecialchars($GLOBALS['config']['PUBSUBHUB_URL']).'" xmlns="http://www.w3.org/2005/Atom" />';
741 echo '<link rel="self" href="'.htmlspecialchars($pageaddr).'?do=rss" xmlns="http://www.w3.org/2005/Atom" />';
742 echo '<!-- End Of PubSubHubbub Discovery -->';
743 }
ef734b5d 744 $i=0;
ca201236 745 $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys().
ef734b5d
SS
746 while ($i<50 && $i<count($keys))
747 {
ca201236 748 $link = $linksToDisplay[$keys[$i]];
24e267ca 749 $guid = $pageaddr.'?'.smallHash($link['linkdate']);
ef734b5d 750 $rfc822date = linkdate2rfc822($link['linkdate']);
6d946e78
SS
751 $absurl = htmlspecialchars($link['url']);
752 if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute
24e267ca 753 echo '<item><title>'.htmlspecialchars($link['title']).'</title><guid>'.$guid.'</guid><link>'.$absurl.'</link>';
6d946e78
SS
754 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) echo '<pubDate>'.htmlspecialchars($rfc822date)."</pubDate>\n";
755 if ($link['tags']!='') // Adding tags to each RSS entry (as mentioned in RSS specification)
24e267ca 756 {
6d946e78 757 foreach(explode(' ',$link['tags']) as $tag) { echo '<category domain="'.htmlspecialchars($pageaddr).'">'.htmlspecialchars($tag).'</category>'."\n"; }
24e267ca
SS
758 }
759 echo '<description><![CDATA['.nl2br(keepMultipleSpaces(text2clickable(htmlspecialchars($link['description'])))).']]></description>'."\n</item>\n";
ef734b5d
SS
760 $i++;
761 }
762 echo '</channel></rss>';
763 exit;
764}
765
8e92abac
SS
766// ------------------------------------------------------------------------------------------
767// Ouput the last 50 links in ATOM format.
768function showATOM()
769{
770 global $LINKSDB;
24e267ca 771
8e92abac
SS
772 // Optionnaly filter the results:
773 $linksToDisplay=array();
774 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
775 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
776 else $linksToDisplay = $LINKSDB;
24e267ca 777
02188b06 778 header('Content-Type: application/atom+xml; charset=utf-8');
24e267ca 779 $pageaddr=htmlspecialchars(indexUrl());
8e92abac
SS
780 $latestDate = '';
781 $entries='';
782 $i=0;
783 $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys().
784 while ($i<50 && $i<count($keys))
785 {
786 $link = $linksToDisplay[$keys[$i]];
24e267ca 787 $guid = $pageaddr.'?'.smallHash($link['linkdate']);
8e92abac
SS
788 $iso8601date = linkdate2iso8601($link['linkdate']);
789 $latestDate = max($latestDate,$iso8601date);
6d946e78 790 $absurl = htmlspecialchars($link['url']);
24e267ca
SS
791 if (startsWith($absurl,'?')) $absurl=$pageaddr.$absurl; // make permalink URL absolute
792 $entries.='<entry><title>'.htmlspecialchars($link['title']).'</title><link href="'.$absurl.'" /><id>'.$guid.'</id>';
008d8b95 793 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $entries.='<updated>'.htmlspecialchars($iso8601date).'</updated>';
24e267ca 794 $entries.='<summary>'.nl2br(keepMultipleSpaces(text2clickable(htmlspecialchars($link['description']))))."</summary>\n";
6d946e78 795 if ($link['tags']!='') // Adding tags to each ATOM entry (as mentioned in ATOM specification)
24e267ca 796 {
6d946e78
SS
797 foreach(explode(' ',$link['tags']) as $tag)
798 { $entries.='<category scheme="'.htmlspecialchars($pageaddr,ENT_QUOTES).'" term="'.htmlspecialchars($tag,ENT_QUOTES).'" />'."\n"; }
24e267ca
SS
799 }
800 $entries.="</entry>\n";
8e92abac
SS
801 $i++;
802 }
803 $feed='<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">';
804 $feed.='<title>'.htmlspecialchars($GLOBALS['title']).'</title>';
008d8b95 805 if (!$GLOBALS['config']['HIDE_TIMESTAMPS'] || isLoggedIn()) $feed.='<updated>'.htmlspecialchars($latestDate).'</updated>';
6d946e78
SS
806 $feed.='<link rel="self" href="'.htmlspecialchars($pageaddr).'" />';
807 if (!empty($GLOBALS['config']['PUBSUBHUB_URL']))
808 {
809 $feed.='<!-- PubSubHubbub Discovery -->';
810 $feed.='<link rel="hub" href="'.htmlspecialchars($GLOBALS['config']['PUBSUBHUB_URL']).'" />';
811 $feed.='<!-- End Of PubSubHubbub Discovery -->';
812 }
8e92abac
SS
813 $feed.='<author><uri>'.htmlspecialchars($pageaddr).'</uri></author>';
814 $feed.='<id>'.htmlspecialchars($pageaddr).'</id>'."\n\n"; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do.
815 $feed.=$entries;
816 $feed.='</feed>';
817 echo $feed;
818 exit;
819}
820
ef734b5d 821// ------------------------------------------------------------------------------------------
24e267ca 822// Render HTML page (according to URL parameters and user rights)
ef734b5d
SS
823function renderPage()
824{
ef734b5d 825 global $LINKSDB;
24e267ca 826
ef734b5d 827 // -------- Display login form.
24e267ca 828 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=login'))
ef734b5d 829 {
008d8b95 830 if ($GLOBALS['config']['OPEN_SHAARLI']) { header('Location: ?'); exit; } // No need to login for open Shaarli
24e267ca
SS
831 $token=''; if (ban_canLogin()) $token=getToken(); // Do not waste token generation if not useful.
832 $PAGE = new pageBuilder;
833 $PAGE->assign('token',$token);
834 $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER']:''));
835 $PAGE->renderPage('loginform');
ef734b5d
SS
836 exit;
837 }
ef734b5d 838 // -------- User wants to logout.
24e267ca
SS
839 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=logout'))
840 {
841 invalidateCaches();
842 logout();
843 header('Location: ?');
844 exit;
845 }
e6a0ab54 846
2732de7c 847 // -------- Picture wall
24e267ca
SS
848 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=picwall'))
849 {
2732de7c 850 // Optionnaly filter the results:
24e267ca
SS
851 $links=array();
852 if (!empty($_GET['searchterm'])) $links = $LINKSDB->filterFulltext($_GET['searchterm']);
853 elseif (!empty($_GET['searchtags'])) $links = $LINKSDB->filterTags(trim($_GET['searchtags']));
854 else $links = $LINKSDB;
2732de7c 855 $body='';
24e267ca
SS
856 $linksToDisplay=array();
857
858 // Get only links which have a thumbnail.
859 foreach($links as $link)
2732de7c 860 {
24e267ca
SS
861 $permalink='?'.htmlspecialchars(smallhash($link['linkdate']),ENT_QUOTES);
862 $thumb=thumbnail($link['url'],$permalink);
863 if ($thumb!='') // Only output links which have a thumbnail.
2732de7c 864 {
24e267ca
SS
865 $link['thumbnail']=$thumb; // Thumbnail HTML code.
866 $link['permalink']=$permalink;
867 $linksToDisplay[]=$link; // Add to array.
2732de7c
SS
868 }
869 }
24e267ca
SS
870 $PAGE = new pageBuilder;
871 $PAGE->assign('linksToDisplay',$linksToDisplay);
872 $PAGE->renderPage('picwall');
873 exit;
874 }
2732de7c 875
e6a0ab54 876 // -------- Tag cloud
24e267ca
SS
877 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=tagcloud'))
878 {
e6a0ab54 879 $tags= $LINKSDB->allTags();
f4aba1ac 880 // We sort tags alphabetically, then choose a font size according to count.
e6a0ab54
SS
881 // First, find max value.
882 $maxcount=0; foreach($tags as $key=>$value) $maxcount=max($maxcount,$value);
883 ksort($tags);
24e267ca 884 $tagList=array();
e6a0ab54
SS
885 foreach($tags as $key=>$value)
886 {
24e267ca 887 $tagList[$key] = array('count'=>$value,'size'=>max(40*$value/$maxcount,8));
e6a0ab54 888 }
24e267ca
SS
889 $PAGE = new pageBuilder;
890 $PAGE->assign('tags',$tagList);
891 $PAGE->renderPage('tagcloud');
892 exit;
893 }
894
ef734b5d
SS
895 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
896 if (isset($_GET['addtag']))
897 {
898 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
4887ceda 899 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER
ef734b5d 900 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
f4aba1ac 901 $params['searchtags'] = (empty($params['searchtags']) ? trim($_GET['addtag']) : trim($params['searchtags']).' '.urlencode(trim($_GET['addtag'])));
ef734b5d
SS
902 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
903 header('Location: ?'.http_build_query($params));
904 exit;
905 }
906
907 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
908 if (isset($_GET['removetag']))
909 {
910 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
4887ceda 911 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?'); exit; } // In case browser does not send HTTP_REFERER
ef734b5d
SS
912 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
913 if (isset($params['searchtags']))
914 {
915 $tags = explode(' ',$params['searchtags']);
916 $tags=array_diff($tags, array($_GET['removetag'])); // Remove value from array $tags.
917 if (count($tags)==0) unset($params['searchtags']); else $params['searchtags'] = implode(' ',$tags);
918 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
919 }
920 header('Location: ?'.http_build_query($params));
921 exit;
24e267ca
SS
922 }
923
ef734b5d
SS
924 // -------- User wants to change the number of links per page (linksperpage=...)
925 if (isset($_GET['linksperpage']))
926 {
927 if (is_numeric($_GET['linksperpage'])) { $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage'])); }
4887ceda 928 header('Location: '.(empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']));
ef734b5d
SS
929 exit;
930 }
24e267ca
SS
931
932
ef734b5d
SS
933 // -------- Handle other actions allowed for non-logged in users:
934 if (!isLoggedIn())
935 {
936 // User tries to post new link but is not loggedin:
937 // Show login screen, then redirect to ?post=...
24e267ca 938 if (isset($_GET['post']))
ef734b5d 939 {
76ec20af 940 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.
ef734b5d
SS
941 exit;
942 }
24e267ca
SS
943 $PAGE = new pageBuilder;
944 buildLinkList($PAGE); // Compute list of links to display
945 $PAGE->renderPage('linklist');
946 exit; // Never remove this one ! All operations below are reserved for logged in user.
ef734b5d 947 }
24e267ca 948
ef734b5d 949 // -------- All other functions are reserved for the registered user:
24e267ca 950
ef734b5d 951 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
24e267ca
SS
952 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=tools'))
953 {
954 $PAGE = new pageBuilder;
955 $PAGE->assign('pageabsaddr',indexUrl());
956 $PAGE->renderPage('tools');
ef734b5d
SS
957 exit;
958 }
f4aba1ac
SS
959
960 // -------- User wants to change his/her password.
24e267ca 961 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=changepasswd'))
f4aba1ac 962 {
008d8b95 963 if ($GLOBALS['config']['OPEN_SHAARLI']) die('You are not supposed to change a password on an Open Shaarli.');
f4aba1ac
SS
964 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
965 {
966 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
967
968 // Make sure old password is correct.
969 $oldhash = sha1($_POST['oldpassword'].$GLOBALS['login'].$GLOBALS['salt']);
970 if ($oldhash!=$GLOBALS['hash']) { echo '<script language="JavaScript">alert("The old password is not correct.");document.location=\'?do=changepasswd\';</script>'; exit; }
f4aba1ac 971 // Save new password
ba0718dc
SS
972 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
973 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']);
974 writeConfig();
f4aba1ac
SS
975 echo '<script language="JavaScript">alert("Your password has been changed.");document.location=\'?do=tools\';</script>';
976 exit;
977 }
24e267ca 978 else // show the change password form.
f4aba1ac 979 {
24e267ca
SS
980 $PAGE = new pageBuilder;
981 $PAGE->assign('token',getToken());
982 $PAGE->renderPage('changepassword');
983 exit;
f4aba1ac
SS
984 }
985 }
24e267ca 986
ba0718dc 987 // -------- User wants to change configuration
24e267ca 988 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=configure'))
ba0718dc
SS
989 {
990 if (!empty($_POST['title']) )
991 {
24e267ca 992 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
ba0718dc
SS
993 $tz = 'UTC';
994 if (!empty($_POST['continent']) && !empty($_POST['city']))
995 if (isTZvalid($_POST['continent'],$_POST['city']))
24e267ca 996 $tz = $_POST['continent'].'/'.$_POST['city'];
ba0718dc
SS
997 $GLOBALS['timezone'] = $tz;
998 $GLOBALS['title']=$_POST['title'];
008d8b95 999 $GLOBALS['redirector']=$_POST['redirector'];
ba0718dc
SS
1000 writeConfig();
1001 echo '<script language="JavaScript">alert("Configuration was saved.");document.location=\'?do=tools\';</script>';
1002 exit;
1003 }
24e267ca 1004 else // Show the configuration form.
ba0718dc 1005 {
24e267ca
SS
1006 $PAGE = new pageBuilder;
1007 $PAGE->assign('token',getToken());
1008 $PAGE->assign('title',htmlspecialchars( empty($GLOBALS['title']) ? '' : $GLOBALS['title'] , ENT_QUOTES));
1009 $PAGE->assign('redirector',htmlspecialchars( empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector'] , ENT_QUOTES));
ba0718dc 1010 list($timezone_form,$timezone_js) = templateTZform($GLOBALS['timezone']);
24e267ca
SS
1011 $PAGE->assign('timezone_form',$timezone_form); // FIXME: put entire tz form generation in template ?
1012 $PAGE->assign('timezone_js',$timezone_js);
1013 $PAGE->renderPage('configure');
1014 exit;
ba0718dc 1015 }
24e267ca
SS
1016 }
1017
f4aba1ac 1018 // -------- User wants to rename a tag or delete it
24e267ca 1019 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=changetag'))
f4aba1ac
SS
1020 {
1021 if (empty($_POST['fromtag']))
1022 {
24e267ca
SS
1023 $PAGE = new pageBuilder;
1024 $PAGE->assign('token',getToken());
1025 $PAGE->renderPage('changetag');
1026 exit;
f4aba1ac
SS
1027 }
1028 if (!tokenOk($_POST['token'])) die('Wrong token.');
24e267ca
SS
1029
1030 // Delete a tag:
f4aba1ac
SS
1031 if (!empty($_POST['deletetag']) && !empty($_POST['fromtag']))
1032 {
1033 $needle=trim($_POST['fromtag']);
1034 $linksToAlter = $LINKSDB->filterTags($needle,true); // true for case-sensitive tag search.
1035 foreach($linksToAlter as $key=>$value)
1036 {
1037 $tags = explode(' ',trim($value['tags']));
1038 unset($tags[array_search($needle,$tags)]); // Remove tag.
1039 $value['tags']=trim(implode(' ',$tags));
1040 $LINKSDB[$key]=$value;
1041 }
1042 $LINKSDB->savedb(); // save to disk
1043 invalidateCaches();
1044 echo '<script language="JavaScript">alert("Tag was removed from '.count($linksToAlter).' links.");document.location=\'?\';</script>';
1045 exit;
1046 }
1047
1048 // Rename a tag:
1049 if (!empty($_POST['renametag']) && !empty($_POST['fromtag']) && !empty($_POST['totag']))
1050 {
1051 $needle=trim($_POST['fromtag']);
1052 $linksToAlter = $LINKSDB->filterTags($needle,true); // true for case-sensitive tag search.
1053 foreach($linksToAlter as $key=>$value)
1054 {
1055 $tags = explode(' ',trim($value['tags']));
1056 $tags[array_search($needle,$tags)] = trim($_POST['totag']); // Remplace tags value.
1057 $value['tags']=trim(implode(' ',$tags));
1058 $LINKSDB[$key]=$value;
1059 }
1060 $LINKSDB->savedb(); // save to disk
1061 invalidateCaches();
1062 echo '<script language="JavaScript">alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode($_POST['totag']).'\';</script>';
1063 exit;
24e267ca 1064 }
f4aba1ac 1065 }
24e267ca 1066
ef734b5d 1067 // -------- User wants to add a link without using the bookmarklet: show form.
24e267ca 1068 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=addlink'))
ef734b5d 1069 {
24e267ca
SS
1070 $PAGE = new pageBuilder;
1071 $PAGE->renderPage('addlink');
ef734b5d 1072 exit;
24e267ca
SS
1073 }
1074
ef734b5d
SS
1075 // -------- User clicked the "Save" button when editing a link: Save link to database.
1076 if (isset($_POST['save_edit']))
1077 {
1078 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
ba0718dc 1079 $tags = trim(preg_replace('/\s\s+/',' ', $_POST['lf_tags'])); // Remove multiple spaces.
ef734b5d
SS
1080 $linkdate=$_POST['lf_linkdate'];
1081 $link = array('title'=>trim($_POST['lf_title']),'url'=>trim($_POST['lf_url']),'description'=>trim($_POST['lf_description']),'private'=>(isset($_POST['lf_private']) ? 1 : 0),
24e267ca 1082 'linkdate'=>$linkdate,'tags'=>str_replace(',',' ',$tags));
ef734b5d
SS
1083 if ($link['title']=='') $link['title']=$link['url']; // If title is empty, use the URL as title.
1084 $LINKSDB[$linkdate] = $link;
1085 $LINKSDB->savedb(); // save to disk
751aaefe 1086 pubsubhub();
ca201236 1087 invalidateCaches();
24e267ca 1088
ef734b5d
SS
1089 // If we are called from the bookmarklet, we must close the popup:
1090 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
4887ceda
SS
1091 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1092 header('Location: '.$returnurl); // After saving the link, redirect to the page the user was on.
ef734b5d 1093 exit;
24e267ca
SS
1094 }
1095
ef734b5d
SS
1096 // -------- User clicked the "Cancel" button when editing a link.
1097 if (isset($_POST['cancel_edit']))
1098 {
1099 // If we are called from the bookmarklet, we must close the popup;
1100 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
1101 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1102 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
24e267ca 1103 exit;
ef734b5d
SS
1104 }
1105
1106 // -------- User clicked the "Delete" button when editing a link : Delete link from database.
1107 if (isset($_POST['delete_link']))
1108 {
1109 if (!tokenOk($_POST['token'])) die('Wrong token.');
1110 // We do not need to ask for confirmation:
1111 // - confirmation is handled by javascript
1112 // - we are protected from XSRF by the token.
1113 $linkdate=$_POST['lf_linkdate'];
1114 unset($LINKSDB[$linkdate]);
1115 $LINKSDB->savedb(); // save to disk
ca201236 1116 invalidateCaches();
ef734b5d
SS
1117 // If we are called from the bookmarklet, we must close the popup:
1118 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
1119 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
1120 header('Location: '.$returnurl); // After deleting the link, redirect to the page the user was on.
1121 exit;
24e267ca
SS
1122 }
1123
ef734b5d 1124 // -------- User clicked the "EDIT" button on a link: Display link edit form.
24e267ca 1125 if (isset($_GET['edit_link']))
ef734b5d
SS
1126 {
1127 $link = $LINKSDB[$_GET['edit_link']]; // Read database
1128 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
24e267ca
SS
1129 $PAGE = new pageBuilder;
1130 $PAGE->assign('link',$link);
1131 $PAGE->assign('link_is_new',false);
1132 $PAGE->assign('token',getToken()); // XSRF protection.
1133 $PAGE->assign('http_referer',(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''));
1134 $PAGE->renderPage('editlink');
1135 exit;
ef734b5d 1136 }
24e267ca 1137
ef734b5d
SS
1138 // -------- User want to post a new link: Display link edit form.
1139 if (isset($_GET['post']))
1140 {
1141 $url=$_GET['post'];
1142
1143 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
6d946e78
SS
1144 $i=strpos($url,'&utm_source='); if ($i!==false) $url=substr($url,0,$i);
1145 $i=strpos($url,'?utm_source='); if ($i!==false) $url=substr($url,0,$i);
1146 $i=strpos($url,'#xtor=RSS-'); if ($i!==false) $url=substr($url,0,$i);
24e267ca 1147
ef734b5d
SS
1148 $link_is_new = false;
1149 $link = $LINKSDB->getLinkFromUrl($url); // Check if URL is not already in database (in this case, we will edit the existing link)
24e267ca 1150 if (!$link)
ef734b5d
SS
1151 {
1152 $link_is_new = true; // This is a new link
1153 $linkdate = strval(date('Ymd_His'));
1154 $title = (empty($_GET['title']) ? '' : $_GET['title'] ); // Get title if it was provided in URL (by the bookmarklet).
1155 $description=''; $tags=''; $private=0;
24e267ca 1156 if (($url!='') && parse_url($url,PHP_URL_SCHEME)=='') $url = 'http://'.$url;
ef734b5d
SS
1157 // 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.)
1158 if (empty($title) && parse_url($url,PHP_URL_SCHEME)=='http')
1159 {
1160 list($status,$headers,$data) = getHTTP($url,4); // Short timeout to keep the application responsive.
24e267ca 1161 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
6d946e78 1162 if (strpos($status,'200 OK')!==false) $title=html_entity_decode(html_extract_title($data),ENT_QUOTES,'UTF-8');
ef734b5d 1163 }
99c9c954 1164 if ($url=='') $url='?'.smallHash($linkdate); // In case of empty URL, this is just a text (with a link that point to itself)
24e267ca 1165 $link = array('linkdate'=>$linkdate,'title'=>$title,'url'=>$url,'description'=>$description,'tags'=>$tags,'private'=>0);
ef734b5d 1166 }
24e267ca
SS
1167
1168 $PAGE = new pageBuilder;
1169 $PAGE->assign('link',$link);
1170 $PAGE->assign('link_is_new',$link_is_new);
1171 $PAGE->assign('token',getToken()); // XSRF protection.
1172 $PAGE->assign('http_referer',(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''));
1173 $PAGE->renderPage('editlink');
ef734b5d
SS
1174 exit;
1175 }
24e267ca 1176
ef734b5d 1177 // -------- Export as Netscape Bookmarks HTML file.
24e267ca 1178 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=export'))
ca201236
SS
1179 {
1180 if (empty($_GET['what']))
1181 {
24e267ca
SS
1182 $PAGE = new pageBuilder;
1183 $PAGE->renderPage('export');
1184 exit;
ca201236
SS
1185 }
1186 $exportWhat=$_GET['what'];
1187 if (!array_intersect(array('all','public','private'),array($exportWhat))) die('What are you trying to export ???');
24e267ca 1188
ef734b5d 1189 header('Content-Type: text/html; charset=utf-8');
ca201236 1190 header('Content-disposition: attachment; filename=bookmarks_'.$exportWhat.'_'.strval(date('Ymd_His')).'.html');
5112a433 1191 $currentdate=date('Y/m/d H:i:s');
ef734b5d
SS
1192 echo <<<HTML
1193<!DOCTYPE NETSCAPE-Bookmark-file-1>
1194<!-- This is an automatically generated file.
1195 It will be read and overwritten.
1196 DO NOT EDIT! -->
24e267ca 1197<!-- Shaarli {$exportWhat} bookmarks export on {$currentdate} -->
ef734b5d
SS
1198<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
1199<TITLE>Bookmarks</TITLE>
1200<H1>Bookmarks</H1>
1201HTML;
1202 foreach($LINKSDB as $link)
1203 {
ca201236
SS
1204 if ($exportWhat=='all' ||
1205 ($exportWhat=='private' && $link['private']!=0) ||
1206 ($exportWhat=='public' && $link['private']==0))
1207 {
1208 echo '<DT><A HREF="'.htmlspecialchars($link['url']).'" ADD_DATE="'.linkdate2timestamp($link['linkdate']).'" PRIVATE="'.$link['private'].'"';
1209 if ($link['tags']!='') echo ' TAGS="'.htmlspecialchars(str_replace(' ',',',$link['tags'])).'"';
1210 echo '>'.htmlspecialchars($link['title'])."</A>\n";
1211 if ($link['description']!='') echo '<DD>'.htmlspecialchars($link['description'])."\n";
1212 }
ef734b5d 1213 }
5112a433 1214 exit;
24e267ca 1215 }
ef734b5d
SS
1216
1217 // -------- User is uploading a file for import
24e267ca 1218 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=upload'))
ef734b5d
SS
1219 {
1220 // If file is too big, some form field may be missing.
1221 if (!isset($_POST['token']) || (!isset($_FILES)) || (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size']==0))
1222 {
1223 $returnurl = ( empty($_SERVER['HTTP_REFERER']) ? '?' : $_SERVER['HTTP_REFERER'] );
1224 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>';
1225 exit;
24e267ca 1226 }
ef734b5d
SS
1227 if (!tokenOk($_POST['token'])) die('Wrong token.');
1228 importFile();
1229 exit;
24e267ca
SS
1230 }
1231
ef734b5d 1232 // -------- Show upload/import dialog:
24e267ca
SS
1233 if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=import'))
1234 {
1235 $PAGE = new pageBuilder;
1236 $PAGE->assign('token',getToken());
1237 $PAGE->assign('maxfilesize',getMaxFileSize());
1238 $PAGE->renderPage('import');
ef734b5d 1239 exit;
24e267ca 1240 }
ef734b5d
SS
1241
1242 // -------- Otherwise, simply display search form and links:
24e267ca
SS
1243 $PAGE = new pageBuilder;
1244 buildLinkList($PAGE); // Compute list of links to display
1245 $PAGE->renderPage('linklist');
ef734b5d 1246 exit;
24e267ca 1247}
ef734b5d
SS
1248
1249// -----------------------------------------------------------------------------------------------
1250// Process the import file form.
1251function importFile()
1252{
1253 global $LINKSDB;
1254 $filename=$_FILES['filetoupload']['name'];
24e267ca 1255 $filesize=$_FILES['filetoupload']['size'];
ef734b5d 1256 $data=file_get_contents($_FILES['filetoupload']['tmp_name']);
ca201236 1257 $private = (empty($_POST['private']) ? 0 : 1); // Should the links be imported as private ?
eae4f48b
SS
1258 $overwrite = !empty($_POST['overwrite']) ; // Should the imported links overwrite existing ones ?
1259 $import_count=0;
ef734b5d
SS
1260
1261 // Sniff file type:
1262 $type='unknown';
1263 if (startsWith($data,'<!DOCTYPE NETSCAPE-Bookmark-file-1>')) $type='netscape'; // Netscape bookmark file (aka Firefox).
24e267ca 1264
ef734b5d
SS
1265 // Then import the bookmarks.
1266 if ($type=='netscape')
1267 {
1268 // This is a standard Netscape-style bookmark file.
24e267ca 1269 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.
ef734b5d
SS
1270 foreach(explode('<DT>',$data) as $html) // explode is very fast
1271 {
24e267ca 1272 $link = array('linkdate'=>'','title'=>'','url'=>'','description'=>'','tags'=>'','private'=>0);
ef734b5d
SS
1273 $d = explode('<DD>',$html);
1274 if (startswith($d[0],'<A '))
1275 {
eae4f48b 1276 $link['description'] = (isset($d[1]) ? html_entity_decode(trim($d[1]),ENT_QUOTES,'UTF-8') : ''); // Get description (optional)
ef734b5d 1277 preg_match('!<A .*?>(.*?)</A>!i',$d[0],$matches); $link['title'] = (isset($matches[1]) ? trim($matches[1]) : ''); // Get title
eae4f48b 1278 $link['title'] = html_entity_decode($link['title'],ENT_QUOTES,'UTF-8');
ef734b5d 1279 preg_match_all('! ([A-Z_]+)=\"(.*?)"!i',$html,$matches,PREG_SET_ORDER); // Get all other attributes
5112a433 1280 $raw_add_date=0;
ef734b5d
SS
1281 foreach($matches as $m)
1282 {
1283 $attr=$m[1]; $value=$m[2];
eae4f48b 1284 if ($attr=='HREF') $link['url']=html_entity_decode($value,ENT_QUOTES,'UTF-8');
5112a433 1285 elseif ($attr=='ADD_DATE') $raw_add_date=intval($value);
ef734b5d 1286 elseif ($attr=='PRIVATE') $link['private']=($value=='0'?0:1);
eae4f48b 1287 elseif ($attr=='TAGS') $link['tags']=html_entity_decode(str_replace(',',' ',$value),ENT_QUOTES,'UTF-8');
24e267ca 1288 }
5112a433 1289 if ($link['url']!='')
ca201236
SS
1290 {
1291 if ($private==1) $link['private']=1;
5112a433
SS
1292 $dblink = $LINKSDB->getLinkFromUrl($link['url']); // See if the link is already in database.
1293 if ($dblink==false)
1294 { // Link not in database, let's import it...
1295 if (empty($raw_add_date)) $raw_add_date=time(); // In case of shitty bookmark file with no ADD_DATE
24e267ca 1296
5112a433
SS
1297 // Make sure date/time is not already used by another link.
1298 // (Some bookmark files have several different links with the same ADD_DATE)
1299 // We increment date by 1 second until we find a date which is not used in db.
1300 // (so that links that have the same date/time are more or less kept grouped by date, but do not conflict.)
1301 while (!empty($LINKSDB[date('Ymd_His',$raw_add_date)])) { $raw_add_date++; }// Yes, I know it's ugly.
1302 $link['linkdate']=date('Ymd_His',$raw_add_date);
1303 $LINKSDB[$link['linkdate']] = $link;
1304 $import_count++;
1305 }
1306 else // link already present in database.
1307 {
1308 if ($overwrite)
1309 { // If overwrite is required, we import link data, except date/time.
1310 $link['linkdate']=$dblink['linkdate'];
1311 $LINKSDB[$link['linkdate']] = $link;
1312 $import_count++;
1313 }
1314 }
1315
ca201236 1316 }
24e267ca 1317 }
ef734b5d 1318 }
ef734b5d 1319 $LINKSDB->savedb();
ca201236 1320 invalidateCaches();
24e267ca 1321 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) was successfully processed: '.$import_count.' links imported.");document.location=\'?\';</script>';
ef734b5d
SS
1322 }
1323 else
1324 {
1325 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) has an unknown file format. Nothing was imported.");document.location=\'?\';</script>';
1326 }
24e267ca 1327}
ef734b5d
SS
1328
1329// -----------------------------------------------------------------------------------------------
24e267ca
SS
1330// Template for the list of links (<div id="linklist">)
1331// This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1332function buildLinkList($PAGE)
ef734b5d 1333{
24e267ca 1334 global $LINKSDB; // Get the links database.
99c9c954 1335
24e267ca 1336 // ---- Filter link database according to parameters
ef734b5d 1337 $linksToDisplay=array();
24e267ca
SS
1338 $search_type='';
1339 $search_crits='';
ef734b5d
SS
1340 if (!empty($_GET['searchterm'])) // Fulltext search
1341 {
f4aba1ac 1342 $linksToDisplay = $LINKSDB->filterFulltext(trim($_GET['searchterm']));
24e267ca
SS
1343 $search_crits=htmlspecialchars(trim($_GET['searchterm']));
1344 $search_type='fulltext';
ef734b5d
SS
1345 }
1346 elseif (!empty($_GET['searchtags'])) // Search by tag
1347 {
f4aba1ac 1348 $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
24e267ca
SS
1349 $search_crits=explode(' ',trim($_GET['searchtags']));
1350 $search_type='tags';
ef734b5d 1351 }
24e267ca 1352 elseif (isset($_SERVER["QUERY_STRING"]) && preg_match('/[a-zA-Z0-9-_@]{6}(&.+?)?/',$_SERVER["QUERY_STRING"])) // Detect smallHashes in URL
99c9c954 1353 {
24e267ca
SS
1354 $linksToDisplay = $LINKSDB->filterSmallHash(substr(trim($_SERVER["QUERY_STRING"], '/'),0,6));
1355 $search_type='permalink';
99c9c954 1356 }
ef734b5d
SS
1357 else
1358 $linksToDisplay = $LINKSDB; // otherwise, display without filtering.
24e267ca
SS
1359
1360
1361 // ---- Handle paging.
ef734b5d
SS
1362 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ???
1363 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1364 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1365 */
1366 $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // Stupid and ugly. Thanks php.
008d8b95
SS
1367
1368 // If there is only a single link, we change on-the-fly the title of the page.
1369 if (count($linksToDisplay)==1) $GLOBALS['pagetitle'] = $linksToDisplay[$keys[0]]['title'].' - '.$GLOBALS['title'];
1370
24e267ca 1371 // Select articles according to paging.
ef734b5d
SS
1372 $pagecount = ceil(count($keys)/$_SESSION['LINKS_PER_PAGE']);
1373 $pagecount = ($pagecount==0 ? 1 : $pagecount);
1374 $page=( empty($_GET['page']) ? 1 : intval($_GET['page']));
1375 $page = ( $page<1 ? 1 : $page );
1376 $page = ( $page>$pagecount ? $pagecount : $page );
1377 $i = ($page-1)*$_SESSION['LINKS_PER_PAGE']; // Start index.
24e267ca
SS
1378 $end = $i+$_SESSION['LINKS_PER_PAGE'];
1379 $linkDisp=array(); // Links to display
ef734b5d 1380 while ($i<$end && $i<count($keys))
24e267ca 1381 {
ef734b5d 1382 $link = $linksToDisplay[$keys[$i]];
24e267ca 1383 $link['description']=nl2br(keepMultipleSpaces(text2clickable(htmlspecialchars($link['description']))));
ef734b5d 1384 $title=$link['title'];
24e267ca
SS
1385 $classLi = $i%2!=0 ? '' : 'publicLinkHightLight';
1386 $link['class'] = ($link['private']==0 ? $classLi : 'private');
1387 $link['localdate']=linkdate2locale($link['linkdate']);
1388 $link['taglist']=explode(' ',$link['tags']);
1389 $linkDisp[$keys[$i]] = $link;
ef734b5d 1390 $i++;
24e267ca 1391 }
ef734b5d 1392
24e267ca 1393 // Compute paging navigation
ef734b5d
SS
1394 $searchterm= ( empty($_GET['searchterm']) ? '' : '&searchterm='.$_GET['searchterm'] );
1395 $searchtags= ( empty($_GET['searchtags']) ? '' : '&searchtags='.$_GET['searchtags'] );
24e267ca
SS
1396 $paging='';
1397 $previous_page_url=''; if ($i!=count($keys)) $previous_page_url='?page='.($page+1).$searchterm.$searchtags;
1398 $next_page_url='';if ($page>1) $next_page_url='?page='.($page-1).$searchterm.$searchtags;
1399
1400 $token = ''; if (isLoggedIn()) $token=getToken();
1401
1402 // Fill all template fields.
1403 $PAGE->assign('previous_page_url',$previous_page_url);
1404 $PAGE->assign('next_page_url',$next_page_url);
1405 $PAGE->assign('page_current',$page);
1406 $PAGE->assign('page_max',$pagecount);
1407 $PAGE->assign('result_count',count($linksToDisplay));
1408 $PAGE->assign('search_type',$search_type);
1409 $PAGE->assign('search_crits',$search_crits);
1410 $PAGE->assign('redirector',empty($GLOBALS['redirector']) ? '' : $GLOBALS['redirector']); // optional redirector URL
1411 $PAGE->assign('token',$token);
1412 $PAGE->assign('links',$linkDisp);
1413 return;
ef734b5d
SS
1414}
1415
6d946e78
SS
1416// Returns the HTML code to display a thumbnail for a link
1417// with a link to the original URL.
0adcceee 1418// Understands various services (youtube.com...)
6d946e78 1419// Input: $url = url for which the thumbnail must be found.
24e267ca 1420// $href = if provided, this URL will be followed instead of $url
6d946e78 1421function thumbnail($url,$href=false)
0adcceee 1422{
008d8b95 1423 if (!$GLOBALS['config']['ENABLE_THUMBNAILS']) return '';
24e267ca 1424
6d946e78 1425 if ($href==false) $href=$url;
24e267ca 1426
28770b26 1427 // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
008d8b95 1428 // (eg. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
28770b26 1429 // ^^^^^^^^^^^ ^^^^^^^^^^^
0adcceee
SS
1430 $domain = parse_url($url,PHP_URL_HOST);
1431 if ($domain=='youtube.com' || $domain=='www.youtube.com')
1432 {
1433 parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract video ID and get thumbnail
6d946e78 1434 if (!empty($params['v'])) return '<a href="'.htmlspecialchars($href).'"><img src="http://img.youtube.com/vi/'.htmlspecialchars($params['v']).'/default.jpg" width="120" height="90"></a>';
0adcceee 1435 }
6d946e78
SS
1436 if ($domain=='youtu.be') // Youtube short links
1437 {
1438 $path = parse_url($url,PHP_URL_PATH);
1439 return '<a href="'.htmlspecialchars($href).'"><img src="http://img.youtube.com/vi'.htmlspecialchars($path).'/default.jpg" width="120" height="90"></a>';
24e267ca 1440 }
0adcceee
SS
1441 if ($domain=='imgur.com')
1442 {
1443 $path = parse_url($url,PHP_URL_PATH);
6d946e78
SS
1444 if (startsWith($path,'/a/')) return ''; // Thumbnails for albums are not available.
1445 if (startsWith($path,'/r/')) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com/'.htmlspecialchars(basename($path)).'s.jpg" width="90" height="90"></a>';
1446 if (startsWith($path,'/gallery/')) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com'.htmlspecialchars(substr($path,8)).'s.jpg" width="90" height="90"></a>';
1447 if (substr_count($path,'/')==1) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com/'.htmlspecialchars(substr($path,1)).'s.jpg" width="90" height="90"></a>';
0adcceee
SS
1448 }
1449 if ($domain=='i.imgur.com')
1450 {
1451 $pi = pathinfo(parse_url($url,PHP_URL_PATH));
6d946e78 1452 if (!empty($pi['filename'])) return '<a href="'.htmlspecialchars($href).'"><img src="http://i.imgur.com/'.htmlspecialchars($pi['filename']).'s.jpg" width="90" height="90"></a>';
24e267ca 1453 }
0adcceee
SS
1454 if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
1455 {
6d946e78 1456 if (strpos($url,'dailymotion.com/video/')!==false)
0adcceee
SS
1457 {
1458 $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
6d946e78 1459 return '<a href="'.htmlspecialchars($href).'"><img src="'.htmlspecialchars($thumburl).'" width="120" style="height:auto;"></a>';
0adcceee 1460 }
24e267ca 1461 }
dcd653d1
SS
1462 if (endsWith($domain,'.imageshack.us'))
1463 {
1464 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1465 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1466 {
1467 $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
6d946e78 1468 return '<a href="'.htmlspecialchars($href).'"><img src="'.htmlspecialchars($thumburl).'" width="120" style="height:auto;"></a>';
dcd653d1
SS
1469 }
1470 }
6d946e78 1471
28770b26
SS
1472 // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
1473 // So we deport the thumbnail generation in order not to slow down page generation
1474 // (and we also cache the thumbnail)
24e267ca 1475
008d8b95 1476 if (!$GLOBALS['config']['ENABLE_LOCALCACHE']) return ''; // If local cache is disabled, no thumbnails for services which require the use a local cache.
24e267ca 1477
05f41b06
EK
1478 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
1479 || $domain=='vimeo.com'
1480 || $domain=='ted.com' || endsWith($domain,'.ted.com')
1481 )
0adcceee 1482 {
5112a433
SS
1483 if ($domain=='vimeo.com')
1484 { // Make sure this vimeo url points to a video (/xxx... where xxx is numeric)
24e267ca 1485 $path = parse_url($url,PHP_URL_PATH);
5112a433
SS
1486 if (!preg_match('!/\d+.+?!',$path)) return ''; // This is not a single video URL.
1487 }
1488 if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
1489 { // Make sure this TED url points to a video (/talks/...)
1490 $path = parse_url($url,PHP_URL_PATH);
1491 if ("/talks/" !== substr($path,0,7)) return ''; // This is not a single video URL.
1492 }
28770b26 1493 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
6d946e78 1494 return '<a href="'.htmlspecialchars($href).'"><img src="?do=genthumbnail&hmac='.htmlspecialchars($sign).'&url='.urlencode($url).'" width="120" style="height:auto;"></a>';
0adcceee 1495 }
28770b26 1496
99c9c954
SS
1497 // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
1498 // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
1499 // But using the extension will do.
1500 $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
1501 if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
1502 {
1503 $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation)
24e267ca 1504 return '<a href="'.htmlspecialchars($href).'"><img src="?do=genthumbnail&hmac='.htmlspecialchars($sign).'&url='.urlencode($url).'" width="120" style="height:auto;"></a>';
99c9c954 1505 }
0adcceee
SS
1506 return ''; // No thumbnail.
1507
1508}
1509
ef734b5d
SS
1510// -----------------------------------------------------------------------------------------------
1511// Installation
1512// This function should NEVER be called if the file data/config.php exists.
1513function install()
1514{
eae4f48b
SS
1515 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1516 if (endsWith($_SERVER['SERVER_NAME'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
24e267ca 1517
4887ceda 1518 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
ef734b5d 1519 {
ba0718dc
SS
1520 $tz = 'UTC';
1521 if (!empty($_POST['continent']) && !empty($_POST['city']))
1522 if (isTZvalid($_POST['continent'],$_POST['city']))
1523 $tz = $_POST['continent'].'/'.$_POST['city'];
24e267ca 1524 $GLOBALS['timezone'] = $tz;
4887ceda 1525 // Everything is ok, let's create config file.
ba0718dc
SS
1526 $GLOBALS['login'] = $_POST['setlogin'];
1527 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
1528 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']);
24e267ca 1529 $GLOBALS['title'] = (empty($_POST['title']) ? 'Shared links on '.htmlspecialchars(indexUrl()) : $_POST['title'] );
ba0718dc 1530 writeConfig();
24e267ca
SS
1531 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location=\'?do=login\';</script>';
1532 exit;
4887ceda 1533 }
24e267ca
SS
1534
1535 // Display config form:
ba0718dc
SS
1536 list($timezone_form,$timezone_js) = templateTZform();
1537 $timezone_html=''; if ($timezone_form!='') $timezone_html='<tr><td valign="top"><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>';
24e267ca
SS
1538
1539 $PAGE = new pageBuilder;
1540 $PAGE->assign('timezone_html',$timezone_html);
1541 $PAGE->assign('timezone_js',$timezone_js);
1542 $PAGE->renderPage('install');
ef734b5d
SS
1543 exit;
1544}
1545
ba0718dc
SS
1546// Generates the timezone selection form and javascript.
1547// Input: (optional) current timezone (can be 'UTC/UTC'). It will be pre-selected.
1548// Output: array(html,js)
1549// Example: list($htmlform,$js) = templateTZform('Europe/Paris'); // Europe/Paris pre-selected.
1550// Returns array('','') if server does not support timezones list. (eg. php 5.1 on free.fr)
1551function templateTZform($ptz=false)
1552{
1553 if (function_exists('timezone_identifiers_list')) // because of old php version (5.1) which can be found on free.fr
1554 {
1555 // Try to split the provided timezone.
1556 if ($ptz==false) { $l=timezone_identifiers_list(); $ptz=$l[0]; }
1557 $spos=strpos($ptz,'/'); $pcontinent=substr($ptz,0,$spos); $pcity=substr($ptz,$spos+1);
24e267ca 1558
ba0718dc
SS
1559 // Display config form:
1560 $timezone_form = '';
1561 $timezone_js = '';
1562 // The list is in the forme "Europe/Paris", "America/Argentina/Buenos_Aires"...
1563 // We split the list in continents/cities.
1564 $continents = array();
1565 $cities = array();
24e267ca 1566 foreach(timezone_identifiers_list() as $tz)
ba0718dc
SS
1567 {
1568 if ($tz=='UTC') $tz='UTC/UTC';
1569 $spos = strpos($tz,'/');
6d946e78 1570 if ($spos!==false)
ba0718dc
SS
1571 {
1572 $continent=substr($tz,0,$spos); $city=substr($tz,$spos+1);
1573 $continents[$continent]=1;
1574 if (!isset($cities[$continent])) $cities[$continent]=array();
1575 $cities[$continent].='<option value="'.$city.'"'.($pcity==$city?'selected':'').'>'.$city.'</option>';
1576 }
1577 }
1578 $continents_html = '';
1579 $continents = array_keys($continents);
1580 foreach($continents as $continent)
24e267ca 1581 $continents_html.='<option value="'.$continent.'"'.($pcontinent==$continent?'selected':'').'>'.$continent.'</option>';
ba0718dc
SS
1582 $cities_html = $cities[$pcontinent];
1583 $timezone_form = "Continent: <select name=\"continent\" id=\"continent\" onChange=\"onChangecontinent();\">${continents_html}</select><br /><br />";
24e267ca 1584 $timezone_form .= "City: <select name=\"city\" id=\"city\">${cities[$pcontinent]}</select><br /><br />";
ba0718dc 1585 $timezone_js = "<script language=\"JavaScript\">";
24e267ca 1586 $timezone_js .= "function onChangecontinent(){document.getElementById(\"city\").innerHTML = citiescontinent[document.getElementById(\"continent\").value];}";
ba0718dc
SS
1587 $timezone_js .= "var citiescontinent = ".json_encode($cities).";" ;
1588 $timezone_js .= "</script>" ;
1589 return array($timezone_form,$timezone_js);
1590 }
1591 return array('','');
1592}
1593
1594// Tells if a timezone is valid or not.
1595// If not valid, returns false.
1596// If system does not support timezone list, returns false.
1597function isTZvalid($continent,$city)
1598{
1599 $tz = $continent.'/'.$city;
1600 if (function_exists('timezone_identifiers_list')) // because of old php version (5.1) which can be found on free.fr
1601 {
1602 if (in_array($tz, timezone_identifiers_list())) // it's a valid timezone ?
1603 return true;
1604 }
1605 return false;
1606}
1607
1608
44a9d860
SS
1609// Webservices (for use with jQuery/jQueryUI)
1610// eg. index.php?ws=tags&term=minecr
1611function processWS()
1612{
1613 if (empty($_GET['ws']) || empty($_GET['term'])) return;
1614 $term = $_GET['term'];
1615 global $LINKSDB;
1616 header('Content-Type: application/json; charset=utf-8');
1617
f4aba1ac 1618 // Search in tags (case insentitive, cumulative search)
44a9d860 1619 if ($_GET['ws']=='tags')
24e267ca 1620 {
dcd653d1 1621 $tags=explode(' ',str_replace(',',' ',$term)); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d")
44a9d860
SS
1622 $addtags=''; if ($tags) $addtags=implode(' ',$tags).' '; // We will pre-pend previous tags
1623 $suggested=array();
1624 /* To speed up things, we store list of tags in session */
24e267ca 1625 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags();
44a9d860
SS
1626 foreach($_SESSION['tags'] as $key=>$value)
1627 {
008d8b95 1628 if (startsWith($key,$last,$case=false) && !in_array($key,$tags)) $suggested[$addtags.$key.' ']=0;
24e267ca 1629 }
44a9d860
SS
1630 echo json_encode(array_keys($suggested));
1631 exit;
1632 }
24e267ca 1633
f4aba1ac
SS
1634 // Search a single tag (case sentitive, single tag search)
1635 if ($_GET['ws']=='singletag')
24e267ca 1636 {
f4aba1ac 1637 /* To speed up things, we store list of tags in session */
24e267ca 1638 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags();
f4aba1ac
SS
1639 foreach($_SESSION['tags'] as $key=>$value)
1640 {
1641 if (startsWith($key,$term,$case=true)) $suggested[$key]=0;
24e267ca 1642 }
f4aba1ac
SS
1643 echo json_encode(array_keys($suggested));
1644 exit;
24e267ca 1645 }
44a9d860
SS
1646}
1647
ba0718dc
SS
1648// Re-write configuration file according to globals.
1649// Requires some $GLOBALS to be set (login,hash,salt,title).
1650// If the config file cannot be saved, an error message is dislayed and the user is redirected to "Tools" menu.
1651// (otherwise, the function simply returns.)
1652function writeConfig()
1653{
008d8b95
SS
1654 if (is_file($GLOBALS['config']['CONFIG_FILE']) && !isLoggedIn()) die('You are not authorized to alter config.'); // Only logged in user can alter config.
1655 if (empty($GLOBALS['redirector'])) $GLOBALS['redirector']='';
ba0718dc 1656 $config='<?php $GLOBALS[\'login\']='.var_export($GLOBALS['login'],true).'; $GLOBALS[\'hash\']='.var_export($GLOBALS['hash'],true).'; $GLOBALS[\'salt\']='.var_export($GLOBALS['salt'],true).'; ';
008d8b95
SS
1657 $config .='$GLOBALS[\'timezone\']='.var_export($GLOBALS['timezone'],true).'; date_default_timezone_set('.var_export($GLOBALS['timezone'],true).'); $GLOBALS[\'title\']='.var_export($GLOBALS['title'],true).';';
1658 $config .= '$GLOBALS[\'redirector\']='.var_export($GLOBALS['redirector'],true).'; ';
24e267ca 1659 $config .= ' ?>';
008d8b95 1660 if (!file_put_contents($GLOBALS['config']['CONFIG_FILE'],$config) || strcmp(file_get_contents($GLOBALS['config']['CONFIG_FILE']),$config)!=0)
ba0718dc
SS
1661 {
1662 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>';
1663 exit;
1664 }
1665}
1666
28770b26
SS
1667/* Because some f*cking services like Flickr require an extra HTTP request to get the thumbnail URL,
1668 I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
1669 The following function takes the URL a link (eg. a flickr page) and return the proper thumbnail.
1670 This function is called by passing the url:
1671 http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
1672 [URL] is the URL of the link (eg. a flickr page)
1673 [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
1674 The function below will fetch the image from the webservice and store it in the cache.
1675*/
1676function genThumbnail()
1677{
1678 // Make sure the parameters in the URL were generated by us.
1679 $sign = hash_hmac('sha256', $_GET['url'], $GLOBALS['salt']);
24e267ca
SS
1680 if ($sign!=$_GET['hmac']) die('Naughty boy !');
1681
28770b26
SS
1682 // Let's see if we don't already have the image for this URL in the cache.
1683 $thumbname=hash('sha1',$_GET['url']).'.jpg';
008d8b95 1684 if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$thumbname))
28770b26
SS
1685 { // We have the thumbnail, just serve it:
1686 header('Content-Type: image/jpeg');
24e267ca 1687 echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname);
28770b26
SS
1688 return;
1689 }
1690 // We may also serve a blank image (if service did not respond)
1691 $blankname=hash('sha1',$_GET['url']).'.gif';
008d8b95 1692 if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$blankname))
28770b26
SS
1693 {
1694 header('Content-Type: image/gif');
24e267ca 1695 echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname);
28770b26 1696 return;
24e267ca
SS
1697 }
1698
28770b26
SS
1699 // Otherwise, generate the thumbnail.
1700 $url = $_GET['url'];
1701 $domain = parse_url($url,PHP_URL_HOST);
1702
1703 if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
24e267ca 1704 {
28770b26
SS
1705 // WTF ? I need a flickr API key to get a fucking thumbnail ? No way.
1706 // I'll extract the thumbnail URL myself. First, we have to get the flickr HTML page.
1707 // All images in Flickr are in the form:
1708 // http://farm[farm].static.flickr.com/[server]/[id]_[secret]_[size].jpg
1709 // Example: http://farm7.static.flickr.com/6205/6088513739_fc158467fe_z.jpg
1710 // We want the 240x120 format, which is _m.jpg.
1711 // We search for the first image in the page which does not have the _s size,
1712 // when use the _m to get the thumbnail.
1713
1714 // Is this a link to an image, or to a flickr page ?
1715 $imageurl='';
28770b26
SS
1716 if (endswith(parse_url($url,PHP_URL_PATH),'.jpg'))
1717 { // This is a direct link to an image. eg. http://farm1.static.flickr.com/5/5921913_ac83ed27bd_o.jpg
1718 preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
24e267ca 1719 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
28770b26
SS
1720 }
1721 else // this is a flickr page (html)
1722 {
1723 list($httpstatus,$headers,$data) = getHTTP($url,20); // Get the flickr html page.
6d946e78 1724 if (strpos($httpstatus,'200 OK')!==false)
28770b26
SS
1725 {
1726 preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)[^s].jpg!',$data,$matches);
24e267ca 1727 if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
28770b26
SS
1728 }
1729 }
1730 if ($imageurl!='')
1731 { // Let's download the image.
1732 list($httpstatus,$headers,$data) = getHTTP($imageurl,10); // Image is 240x120, so 10 seconds to download should be enough.
6d946e78 1733 if (strpos($httpstatus,'200 OK')!==false)
28770b26 1734 {
008d8b95 1735 file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname,$data); // Save image to cache.
28770b26
SS
1736 header('Content-Type: image/jpeg');
1737 echo $data;
1738 return;
1739 }
24e267ca 1740 }
28770b26
SS
1741 }
1742
c4c9c414 1743 elseif ($domain=='vimeo.com' )
28770b26
SS
1744 {
1745 // This is more complex: we have to perform a HTTP request, then parse the result.
1746 // Maybe we should deport this to javascript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
1747 $vid = substr(parse_url($url,PHP_URL_PATH),1);
1748 list($httpstatus,$headers,$data) = getHTTP('http://vimeo.com/api/v2/video/'.htmlspecialchars($vid).'.php',5);
6d946e78 1749 if (strpos($httpstatus,'200 OK')!==false)
28770b26
SS
1750 {
1751 $t = unserialize($data);
1752 $imageurl = $t[0]['thumbnail_medium'];
1753 // Then we download the image and serve it to our client.
1754 list($httpstatus,$headers,$data) = getHTTP($imageurl,10);
6d946e78 1755 if (strpos($httpstatus,'200 OK')!==false)
28770b26 1756 {
008d8b95 1757 file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname,$data); // Save image to cache.
28770b26
SS
1758 header('Content-Type: image/jpeg');
1759 echo $data;
1760 return;
24e267ca
SS
1761 }
1762 }
28770b26 1763 }
05f41b06 1764
c4c9c414 1765 elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
05f41b06
EK
1766 {
1767 // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
1768 // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
1769 // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
1770 list($httpstatus,$headers,$data) = getHTTP($url,5);
1771 if (strpos($httpstatus,'200 OK')!==false)
1772 {
1773 // Extract the link to the thumbnail
1774 preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)[^s]!',$data,$matches);
1775 if (!empty($matches[1]))
1776 { // Let's download the image.
1777 $imageurl=$matches[1];
1778 list($httpstatus,$headers,$data) = getHTTP($imageurl,20); // No control on image size, so wait long enough.
1779 if (strpos($httpstatus,'200 OK')!==false)
1780 {
1781 $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname;
1782 file_put_contents($filepath,$data); // Save image to cache.
1783 if (resizeImage($filepath))
1784 {
1785 header('Content-Type: image/jpeg');
24e267ca 1786 echo file_get_contents($filepath);
05f41b06
EK
1787 return;
1788 }
1789 }
1790 }
1791 }
1792 }
24e267ca 1793
c4c9c414 1794 else
99c9c954 1795 {
c4c9c414
EK
1796 // For all other domains, we try to download the image and make a thumbnail.
1797 list($httpstatus,$headers,$data) = getHTTP($url,30); // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
1798 if (strpos($httpstatus,'200 OK')!==false)
99c9c954 1799 {
c4c9c414
EK
1800 $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname;
1801 file_put_contents($filepath,$data); // Save image to cache.
1802 if (resizeImage($filepath))
1803 {
1804 header('Content-Type: image/jpeg');
24e267ca 1805 echo file_get_contents($filepath);
c4c9c414
EK
1806 return;
1807 }
99c9c954 1808 }
c4c9c414 1809 }
28770b26 1810
008d8b95 1811
28770b26
SS
1812 // Otherwise, return an empty image (8x8 transparent gif)
1813 $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
008d8b95 1814 file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname,$blankgif); // Also put something in cache so that this URL is not requested twice.
28770b26
SS
1815 header('Content-Type: image/gif');
1816 echo $blankgif;
1817}
1818
99c9c954
SS
1819// Make a thumbnail of the image (to width: 120 pixels)
1820// Returns true if success, false otherwise.
1821function resizeImage($filepath)
1822{
1823 if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
1824
1825 // Trick: some stupid people rename GIF as JPEG... or else.
1826 // So we really try to open each image type whatever the extension is.
1827 $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
1828 $im=false;
6d946e78
SS
1829 $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
1830 $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
1831 $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
99c9c954
SS
1832 if (!$im) return false; // Unable to open image (corrupted or not an image)
1833 $w = imagesx($im);
1834 $h = imagesy($im);
008d8b95
SS
1835 $ystart = 0; $yheight=$h;
1836 if ($h>$w) { $ystart= ($h/2)-($w/2); $yheight=$w/2; }
99c9c954 1837 $nw = 120; // Desired width
008d8b95 1838 $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
99c9c954
SS
1839 // Resize image:
1840 $im2 = imagecreatetruecolor($nw,$nh);
008d8b95 1841 imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
99c9c954
SS
1842 imageinterlace($im2,true); // For progressive JPEG.
1843 $tempname=$filepath.'_TEMP.jpg';
1844 imagejpeg($im2, $tempname, 90);
1845 imagedestroy($im);
1846 imagedestroy($im2);
1847 rename($tempname,$filepath); // Overwrite original picture with thumbnail.
1848 return true;
1849}
1850
ca201236
SS
1851// Invalidate caches when the database is changed or the user logs out.
1852// (eg. tags cache).
1853function invalidateCaches()
1854{
1855 unset($_SESSION['tags']);
1856}
1857
24e267ca 1858if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=genthumbnail')) { genThumbnail(); exit; } // Thumbnail generation/cache does not need the link database.
008d8b95 1859$LINKSDB=new linkdb(isLoggedIn() || $GLOBALS['config']['OPEN_SHAARLI']); // Read links from database (and filter private links if used it not logged in).
24e267ca 1860if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'ws=')) { processWS(); exit; } // Webservices (for jQuery/jQueryUI)
008d8b95 1861if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=$GLOBALS['config']['LINKS_PER_PAGE'];
24e267ca
SS
1862if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=rss')) { showRSS(); exit; }
1863if (isset($_SERVER["QUERY_STRING"]) && startswith($_SERVER["QUERY_STRING"],'do=atom')) { showATOM(); exit; }
ef734b5d 1864renderPage();
24e267ca 1865?>