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