]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - index.php
Version 0.0.16 beta:
[github/shaarli/Shaarli.git] / index.php
CommitLineData
ef734b5d 1<?php
e6a0ab54 2// Shaarli 0.0.16 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
ef734b5d
SS
8
9// -----------------------------------------------------------------------------------------------
10// User config:
11define('DATADIR','data'); // Data subdirectory
12define('CONFIG_FILE',DATADIR.'/config.php'); // Configuration file (user login/password)
13define('DATASTORE',DATADIR.'/datastore.php'); // Data storage file.
14define('LINKS_PER_PAGE',20); // Default links per page.
15define('IPBANS_FILENAME',DATADIR.'/ipbans.php'); // File storage for failures and bans.
16define('BAN_AFTER',4); // Ban IP after this many failures.
17define('BAN_DURATION',1800); // Ban duration for IP address after login failures (in seconds) (1800 sec. = 30 minutes)
44a9d860 18define('OPEN_SHAARLI',false); // If true, anyone can add/edit/delete links without having to login
e6a0ab54 19define('HIDE_TIMESTAMPS',false); // If true, the moment when links were saved are not shown to users that are not logged in.
ca201236 20
ca201236
SS
21// -----------------------------------------------------------------------------------------------
22// Program config (touch at your own risks !)
e6a0ab54
SS
23define('UPDATECHECK_FILENAME',DATADIR.'/lastupdatecheck.txt'); // For updates check of Shaarli.
24define('UPDATECHECK_INTERVAL',86400); // Updates check frequency for Shaarli. 86400 seconds=24 hours
ef4275c5
SS
25ini_set('max_input_time','60'); // High execution time in case of problematic imports/exports.
26ini_set('memory_limit', '128M'); // Try to set max upload file size and read (May not work on some hosts).
27ini_set('post_max_size', '16M');
28ini_set('upload_max_filesize', '16M');
29define('PHPPREFIX','<?php /* '); // Prefix to encapsulate data in php code.
30define('PHPSUFFIX',' */ ?>'); // Suffix to encapsulate data in php code.
31$STARTTIME = microtime(true); // Measure page execution time.
4887ceda 32checkphpversion();
4887ceda
SS
33error_reporting(E_ALL^E_WARNING); // See all error except warnings.
34//error_reporting(-1); // See all errors (for debugging only)
ef734b5d 35ob_start();
ef4275c5
SS
36// In case stupid admin has left magic_quotes enabled in php.ini:
37if (get_magic_quotes_gpc())
38{
39 function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; }
40 $_POST = array_map('stripslashes_deep', $_POST);
41 $_GET = array_map('stripslashes_deep', $_GET);
42 $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
43}
ef734b5d
SS
44// Prevent caching: (yes, it's ugly)
45header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
46header("Cache-Control: no-store, no-cache, must-revalidate");
47header("Cache-Control: post-check=0, pre-check=0", false);
48header("Pragma: no-cache");
e6a0ab54 49define('shaarli_version','0.0.16 beta');
ef734b5d
SS
50if (!is_dir(DATADIR)) { mkdir(DATADIR,0705); chmod(DATADIR,0705); }
51if (!is_file(DATADIR.'/.htaccess')) { file_put_contents(DATADIR.'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.
52if (!is_file(CONFIG_FILE)) install();
53require CONFIG_FILE; // Read login/password hash into $GLOBALS.
ef734b5d
SS
54autoLocale(); // Sniff browser language and set date format accordingly.
55header('Content-Type: text/html; charset=utf-8'); // We use UTF-8 for proper international characters handling.
56$LINKSDB=false;
57
e6a0ab54 58// Check php version
4887ceda
SS
59function checkphpversion()
60{
e6a0ab54 61 if (version_compare(PHP_VERSION, '5.1.0') < 0)
4887ceda 62 {
ca201236 63 header('Content-Type: text/plain; charset=utf-8');
e6a0ab54 64 echo 'Your server supports php '.PHP_VERSION.'. Shaarli requires at last php 5.1.0, and thus cannot run. Sorry.';
ca201236 65 exit;
e6a0ab54
SS
66 }
67}
68
69// Checks if an update is available for Shaarli.
70// (at most once a day, and only for registered user.)
71// Output: '' = no new version.
72// other= the available version.
73function checkUpdate()
74{
75 if (!isLoggedIn()) return ''; // Do not check versions for visitors.
76
77 // Get latest version number at most once a day.
78 if (!is_file(UPDATECHECK_FILENAME) || (filemtime(UPDATECHECK_FILENAME)<time()-(UPDATECHECK_INTERVAL)))
79 {
80 $version=shaarli_version;
81 list($httpstatus,$headers,$data) = getHTTP('http://sebsauvage.net/files/shaarli_version.txt',2);
82 if (strpos($httpstatus,'200 OK')) $version=$data;
83 // If failed, nevermind. We don't want to bother the user with that.
84 file_put_contents(UPDATECHECK_FILENAME,$version); // touch file date
4887ceda 85 }
e6a0ab54
SS
86 // Compare versions:
87 $newestversion=file_get_contents(UPDATECHECK_FILENAME);
88 if ($newestversion!=shaarli_version) return $newestversion;
89 return '';
4887ceda
SS
90}
91
ef734b5d
SS
92// -----------------------------------------------------------------------------------------------
93// Log to text file
94function logm($message)
95{
96 if (!file_exists(DATADIR.'/log.txt')) {$logFile = fopen(DATADIR.'/log.txt','w'); }
97 else { $logFile = fopen(DATADIR.'/log.txt','a'); }
98 fwrite($logFile,strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."\n");
99 fclose($logFile);
100}
101
102// ------------------------------------------------------------------------------------------
103// Sniff browser language to display dates in the right format automatically.
104// (Note that is may not work on your server if the corresponding local is not installed.)
105function autoLocale()
106{
107 $loc='en_US'; // Default if browser does not send HTTP_ACCEPT_LANGUAGE
108 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) // eg. "fr,fr-fr;q=0.8,en;q=0.5,en-us;q=0.3"
109 { // (It's a bit crude, but it works very well. Prefered language is always presented first.)
110 if (preg_match('/([a-z]{2}(-[a-z]{2})?)/i',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches)) $loc=$matches[1];
111 }
112 setlocale(LC_TIME,$loc); // LC_TIME = Set local for date/time format only.
113}
114
115// ------------------------------------------------------------------------------------------
116// Session management
117define('INACTIVITY_TIMEOUT',3600); // (in seconds). If the user does not access any page within this time, his/her session is considered expired.
118ini_set('session.use_cookies', 1); // Use cookies to store session.
119ini_set('session.use_only_cookies', 1); // Force cookies for session (phpsessionID forbidden in URL)
120ini_set('session.use_trans_sid', false); // Prevent php to use sessionID in URL if cookies are disabled.
121session_name('shaarli');
122session_start();
123
124// Returns the IP address of the client (Used to prevent session cookie hijacking.)
125function allIPs()
126{
127 $ip = $_SERVER["REMOTE_ADDR"];
128 // Then we use more HTTP headers to prevent session hijacking from users behind the same proxy.
129 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$ip.'_'.$_SERVER['HTTP_X_FORWARDED_FOR']; }
130 if (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip=$ip.'_'.$_SERVER['HTTP_CLIENT_IP']; }
131 return $ip;
132}
133
134// Check that user/password is correct.
135function check_auth($login,$password)
136{
137 $hash = sha1($password.$login.$GLOBALS['salt']);
138 if ($login==$GLOBALS['login'] && $hash==$GLOBALS['hash'])
139 { // Login/password is correct.
140 $_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // generate unique random number (different than phpsessionid)
141 $_SESSION['ip']=allIPs(); // We store IP address(es) of the client to make sure session is not hijacked.
142 $_SESSION['username']=$login;
143 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // Set session expiration.
144 logm('Login successful');
145 return True;
146 }
147 logm('Login failed for user '.$login);
148 return False;
149}
150
151// Returns true if the user is logged in.
152function isLoggedIn()
153{
44a9d860
SS
154 if (OPEN_SHAARLI) return true;
155
ef734b5d
SS
156 // If session does not exist on server side, or IP address has changed, or session has expired, logout.
157 if (empty($_SESSION['uid']) || $_SESSION['ip']!=allIPs() || time()>=$_SESSION['expires_on'])
158 {
159 logout();
160 return false;
161 }
162 $_SESSION['expires_on']=time()+INACTIVITY_TIMEOUT; // User accessed a page : Update his/her session expiration date.
163 return true;
164}
165
166// Force logout.
167function logout() { unset($_SESSION['uid']); unset($_SESSION['ip']); unset($_SESSION['username']);}
168
169
170// ------------------------------------------------------------------------------------------
171// Brute force protection system
172// Several consecutive failed logins will ban the IP address for 30 minutes.
173if (!is_file(IPBANS_FILENAME)) file_put_contents(IPBANS_FILENAME, "<?php\n\$GLOBALS['IPBANS']=".var_export(array('FAILURES'=>array(),'BANS'=>array()),true).";\n?>");
174include IPBANS_FILENAME;
175// Signal a failed login. Will ban the IP if too many failures:
176function ban_loginFailed()
177{
178 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
179 if (!isset($gb['FAILURES'][$ip])) $gb['FAILURES'][$ip]=0;
180 $gb['FAILURES'][$ip]++;
181 if ($gb['FAILURES'][$ip]>(BAN_AFTER-1))
182 {
183 $gb['BANS'][$ip]=time()+BAN_DURATION;
184 logm('IP address banned from login');
185 }
186 $GLOBALS['IPBANS'] = $gb;
187 file_put_contents(IPBANS_FILENAME, "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
188}
189
190// Signals a successful login. Resets failed login counter.
191function ban_loginOk()
192{
193 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
194 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
195 $GLOBALS['IPBANS'] = $gb;
196 file_put_contents(IPBANS_FILENAME, "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
197}
198
199// Checks if the user CAN login. If 'true', the user can try to login.
200function ban_canLogin()
201{
202 $ip=$_SERVER["REMOTE_ADDR"]; $gb=$GLOBALS['IPBANS'];
203 if (isset($gb['BANS'][$ip]))
204 {
205 // User is banned. Check if the ban has expired:
206 if ($gb['BANS'][$ip]<=time())
207 { // Ban expired, user can try to login again.
208 logm('Ban lifted.');
209 unset($gb['FAILURES'][$ip]); unset($gb['BANS'][$ip]);
210 file_put_contents(IPBANS_FILENAME, "<?php\n\$GLOBALS['IPBANS']=".var_export($gb,true).";\n?>");
211 return true; // Ban has expired, user can login.
212 }
213 return false; // User is banned.
214 }
215 return true; // User is not banned.
216}
217
218// ------------------------------------------------------------------------------------------
219// Process login form: Check if login/password is correct.
220if (isset($_POST['login']))
221{
222 if (!ban_canLogin()) die('I said: NO. You are banned for the moment. Go away.');
223 if (isset($_POST['password']) && tokenOk($_POST['token']) && (check_auth($_POST['login'], $_POST['password'])))
224 { // Login/password is ok.
225 ban_loginOk();
226 // Optional redirect after login:
227 if (isset($_GET['post'])) { header('Location: ?post='.urlencode($_GET['post']).(!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')); exit; }
eae4f48b
SS
228 if (isset($_POST['returnurl']))
229 {
230 if (endsWith($_POST['returnurl'],'?do=login')) { header('Location: ?'); exit; } // Prevent loops over login screen.
231 header('Location: '.$_POST['returnurl']); exit;
232 }
ef734b5d
SS
233 header('Location: ?'); exit;
234 }
235 else
236 {
237 ban_loginFailed();
238 echo '<script language="JavaScript">alert("Wrong login/password.");document.location=\'?do=login\';</script>'; // Redirect to login screen.
239 exit;
240 }
241}
242
243// ------------------------------------------------------------------------------------------
244// Misc utility functions:
245
246// Returns the server URL (including port and http/https), without path.
247// eg. "http://myserver.com:8080"
248// You can append $_SERVER['SCRIPT_NAME'] to get the current script URL.
249function serverUrl()
250{
251 $serverport = ($_SERVER["SERVER_PORT"]!='80' ? ':'.$_SERVER["SERVER_PORT"] : '');
252 return 'http'.(!empty($_SERVER['HTTPS'])?'s':'').'://'.$_SERVER["SERVER_NAME"].$serverport;
253}
254
255// Convert post_max_size/upload_max_filesize (eg.'16M') parameters to bytes.
256function return_bytes($val)
257{
258 $val = trim($val); $last=strtolower($val[strlen($val)-1]);
259 switch($last)
260 {
261 case 'g': $val *= 1024;
262 case 'm': $val *= 1024;
263 case 'k': $val *= 1024;
264 }
265 return $val;
266}
267
268// Try to determine max file size for uploads (POST).
269// Returns an integer (in bytes)
270function getMaxFileSize()
271{
272 $size1 = return_bytes(ini_get('post_max_size'));
273 $size2 = return_bytes(ini_get('upload_max_filesize'));
274 // Return the smaller of two:
275 $maxsize = min($size1,$size2);
276 // FIXME: Then convert back to readable notations ? (eg. 2M instead of 2000000)
277 return $maxsize;
278}
279
280// Tells if a string start with a substring or not.
281function startsWith($haystack,$needle,$case=true)
282{
283 if($case){return (strcmp(substr($haystack, 0, strlen($needle)),$needle)===0);}
284 return (strcasecmp(substr($haystack, 0, strlen($needle)),$needle)===0);
285}
286
287// Tells if a string ends with a substring or not.
288function endsWith($haystack,$needle,$case=true)
289{
290 if($case){return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);}
291 return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);
292}
293
294/* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a timestamp (Unix epoch)
295 (used to build the ADD_DATE attribute in Netscape-bookmarks file)
296 PS: I could have used strptime(), but it does not exist on Windows. I'm too kind. */
297function linkdate2timestamp($linkdate)
298{
299 $Y=$M=$D=$h=$m=$s=0;
300 $r = sscanf($linkdate,'%4d%2d%2d_%2d%2d%2d',$Y,$M,$D,$h,$m,$s);
301 return mktime($h,$m,$s,$M,$D,$Y);
302}
303
304/* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a RFC822 date.
305 (used to build the pubDate attribute in RSS feed.) */
306function linkdate2rfc822($linkdate)
307{
308 return date('r',linkdate2timestamp($linkdate)); // 'r' is for RFC822 date format.
309}
310
311/* Converts a linkdate time (YYYYMMDD_HHMMSS) of an article to a localized date format.
312 (used to display link date on screen)
313 The date format is automatically chose according to locale/languages sniffed from browser headers (see autoLocale()). */
314function linkdate2locale($linkdate)
315{
316 return utf8_encode(strftime('%c',linkdate2timestamp($linkdate))); // %c is for automatic date format according to locale.
317 // Note that if you use a local which is not installed on your webserver,
318 // the date will not be displayed in the chosen locale, but probably in US notation.
319}
320
321// Parse HTTP response headers and return an associative array.
322function http_parse_headers( $headers )
323{
324 $res=array();
325 foreach($headers as $header)
326 {
327 $i = strpos($header,': ');
328 if ($i)
329 {
330 $key=substr($header,0,$i);
331 $value=substr($header,$i+2,strlen($header)-$i-2);
332 $res[$key]=$value;
333 }
334 }
335 return $res;
336}
337
338/* GET an URL.
339 Input: $url : url to get (http://...)
340 $timeout : Network timeout (will wait this many seconds for an anwser before giving up).
4887ceda 341 Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK") or error message
ef734b5d
SS
342 [1] = associative array containing HTTP response headers (eg. echo getHTTP($url)[1]['Content-Type'])
343 [2] = data
344 Example: list($httpstatus,$headers,$data) = getHTTP('http://sebauvage.net/');
345 if (strpos($httpstatus,'200 OK'))
346 echo 'Data type: '.htmlspecialchars($headers['Content-Type']);
347 else
348 echo 'There was an error: '.htmlspecialchars($httpstatus)
349*/
350function getHTTP($url,$timeout=30)
351{
4887ceda
SS
352 try
353 {
354 $options = array('http'=>array('method'=>'GET','timeout' => $timeout)); // Force network timeout
355 $context = stream_context_create($options);
356 $data=file_get_contents($url,false,$context,-1, 2000000); // We download at most 2 Mb from source.
357 if (!$data) { $lasterror=error_get_last(); return array($lasterror['message'],array(),''); }
358 $httpStatus=$http_response_header[0]; // eg. "HTTP/1.1 200 OK"
359 $responseHeaders=http_parse_headers($http_response_header);
360 return array($httpStatus,$responseHeaders,$data);
361 }
362 catch (Exception $e) // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
363 {
364 return array($e->getMessage(),'','');
365 }
ef734b5d
SS
366}
367
368// Extract title from an HTML document.
369// (Returns an empty string if not found.)
370function html_extract_title($html)
371{
372 return preg_match('!<title>(.*?)</title>!i', $html, $matches) ? $matches[1] : '';
373}
374
375// ------------------------------------------------------------------------------------------
376// Token management for XSRF protection
377// Token should be used in any form which acts on data (create,update,delete,import...).
378if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
379
380// Returns a token.
381function getToken()
382{
383 $rnd = sha1(uniqid('',true).'_'.mt_rand()); // We generate a random string.
384 $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
385 return $rnd;
386}
387
388// Tells if a token is ok. Using this function will destroy the token.
389// true=token is ok.
390function tokenOk($token)
391{
392 if (isset($_SESSION['tokens'][$token]))
393 {
394 unset($_SESSION['tokens'][$token]); // Token is used: destroy it.
395 return true; // Token is ok.
396 }
397 return false; // Wrong token, or already used.
398}
399
400// ------------------------------------------------------------------------------------------
401/* Data storage for links.
402 This object behaves like an associative array.
403 Example:
404 $mylinks = new linkdb();
405 echo $mylinks['20110826_161819']['title'];
406 foreach($mylinks as $link)
407 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
408
409 We implement 3 interfaces:
410 - ArrayAccess so that this object behaves like an associative array.
411 - Iterator so that this object can be used in foreach() loops.
412 - Countable interface so that we can do a count() on this object.
413*/
414class linkdb implements Iterator, Countable, ArrayAccess
415
416{
417 private $links; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...)
418 private $urls; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
419 private $keys; // List of linkdate keys (for the Iterator interface implementation)
420 private $position; // Position in the $this->keys array. (for the Iterator interface implementation.)
421 private $loggedin; // Is the used logged in ? (used to filter private links)
422
423 // Constructor:
424 function __construct($isLoggedIn)
425 // Input : $isLoggedIn : is the used logged in ?
426 {
427 $this->loggedin = $isLoggedIn;
428 $this->checkdb(); // Make sure data file exists.
429 $this->readdb(); // Then read it.
430 }
431
432 // ---- Countable interface implementation
433 public function count() { return count($this->links); }
434
435 // ---- ArrayAccess interface implementation
436 public function offsetSet($offset, $value)
437 {
438 if (!$this->loggedin) die('You are not authorized to add a link.');
439 if (empty($value['linkdate']) || empty($value['url'])) die('Internal Error: A link should always have a linkdate and url.');
440 if (empty($offset)) die('You must specify a key.');
441 $this->links[$offset] = $value;
442 $this->urls[$value['url']]=$offset;
443 }
444 public function offsetExists($offset) { return array_key_exists($offset,$this->links); }
445 public function offsetUnset($offset)
446 {
447 if (!$this->loggedin) die('You are not authorized to delete a link.');
448 $url = $this->links[$offset]['url']; unset($this->urls[$url]);
449 unset($this->links[$offset]);
450 }
451 public function offsetGet($offset) { return isset($this->links[$offset]) ? $this->links[$offset] : null; }
452
453 // ---- Iterator interface implementation
454 function rewind() { $this->keys=array_keys($this->links); rsort($this->keys); $this->position=0; } // Start over for iteration, ordered by date (latest first).
455 function key() { return $this->keys[$this->position]; } // current key
456 function current() { return $this->links[$this->keys[$this->position]]; } // current value
457 function next() { ++$this->position; } // go to next item
458 function valid() { return isset($this->keys[$this->position]); } // Check if current position is valid.
459
460 // ---- Misc methods
461 private function checkdb() // Check if db directory and file exists.
462 {
463 if (!file_exists(DATASTORE)) // Create a dummy database for example.
464 {
465 $this->links = array();
466 $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');
467 $this->links[$link['linkdate']] = $link;
468 $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');
469 $this->links[$link['linkdate']] = $link;
470 file_put_contents(DATASTORE, PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX); // Write database to disk
471 }
472 }
473
474 // Read database from disk to memory
475 private function readdb()
476 {
477 // Read data
478 $this->links=(file_exists(DATASTORE) ? unserialize(gzinflate(base64_decode(substr(file_get_contents(DATASTORE),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() );
479
480 // If user is not logged in, filter private links.
481 if (!$this->loggedin)
482 {
483 $toremove=array();
484 foreach($this->links as $link) { if ($link['private']!=0) $toremove[]=$link['linkdate']; }
485 foreach($toremove as $linkdate) { unset($this->links[$linkdate]); }
486 }
487
488 // Keep the list of the mapping URLs-->linkdate up-to-date.
489 $this->urls=array();
490 foreach($this->links as $link) { $this->urls[$link['url']]=$link['linkdate']; }
491 }
492
493 // Save database from memory to disk.
494 public function savedb()
495 {
496 if (!$this->loggedin) die('You are not authorized to change the database.');
497 file_put_contents(DATASTORE, PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX);
498 }
499
500 // Returns the link for a given URL (if it exists). false it does not exist.
501 public function getLinkFromUrl($url)
502 {
503 if (isset($this->urls[$url])) return $this->links[$this->urls[$url]];
504 return false;
505 }
506
507 // Case insentitive search among links (in url, title and description). Returns filtered list of links.
508 // eg. print_r($mydb->filterTags('hollandais'));
509 public function filterFulltext($searchterms)
510 {
511 // FIXME: explode(' ',$searchterms) and perform a AND search.
512 // FIXME: accept double-quotes to search for a string "as is" ?
513 $filtered=array();
514 $s = strtolower($searchterms);
515 foreach($this->links as $l)
516 {
517 $found=strpos(strtolower($l['title']),$s) || strpos(strtolower($l['description']),$s) || strpos(strtolower($l['url']),$s) || strpos(strtolower($l['tags']),$s);
518 if ($found) $filtered[$l['linkdate']] = $l;
519 }
520 krsort($filtered);
521 return $filtered;
522 }
523
524 // Filter by tag.
525 // You can specify one or more tags (tags can be separated by space or comma).
526 // eg. print_r($mydb->filterTags('linux programming'));
527 public function filterTags($tags)
528 {
529 $t = str_replace(',',' ',strtolower($tags));
530 $searchtags=explode(' ',$t);
531 $filtered=array();
532 foreach($this->links as $l)
533 {
534 $linktags = explode(' ',strtolower($l['tags']));
535 if (count(array_intersect($linktags,$searchtags)) == count($searchtags))
536 $filtered[$l['linkdate']] = $l;
537 }
538 krsort($filtered);
539 return $filtered;
44a9d860 540 }
ef734b5d 541
44a9d860
SS
542 // Returns the list of all tags
543 // Output: associative array key=tags, value=0
544 public function allTags()
545 {
546 $tags=array();
547 foreach($this->links as $link)
548 foreach(explode(' ',$link['tags']) as $tag)
ca201236
SS
549 if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1);
550 arsort($tags); // Sort tags by usage (most used tag first)
44a9d860
SS
551 return $tags;
552 }
553
ef734b5d
SS
554}
555
556// ------------------------------------------------------------------------------------------
557// Ouput the last 50 links in RSS 2.0 format.
558function showRSS()
559{
560 global $LINKSDB;
ca201236
SS
561
562 // Optionnaly filter the results:
563 $linksToDisplay=array();
564 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
565 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags($_GET['searchtags']);
566 else $linksToDisplay = $LINKSDB;
567
ef734b5d
SS
568 header('Content-Type: application/xhtml+xml; charset=utf-8');
569 $pageaddr=htmlspecialchars(serverUrl().$_SERVER["SCRIPT_NAME"]);
570 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">';
571 echo '<channel><title>Shared links on '.$pageaddr.'</title><link>'.$pageaddr.'</link>';
572 echo '<description>Shared links</description><language></language><copyright>'.$pageaddr.'</copyright>'."\n\n";
573 $i=0;
ca201236 574 $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys().
ef734b5d
SS
575 while ($i<50 && $i<count($keys))
576 {
ca201236 577 $link = $linksToDisplay[$keys[$i]];
ef734b5d 578 $rfc822date = linkdate2rfc822($link['linkdate']);
e6a0ab54
SS
579 echo '<item><title>'.htmlspecialchars($link['title']).'</title><guid>'.htmlspecialchars($link['url']).'</guid><link>'.htmlspecialchars($link['url']).'</link>';
580 if (!HIDE_TIMESTAMPS || isLoggedIn()) echo '<pubDate>'.htmlspecialchars($rfc822date).'</pubDate>';
ef734b5d
SS
581 echo '<description><![CDATA['.htmlspecialchars($link['description']).']]></description></item>'."\n";
582 $i++;
583 }
584 echo '</channel></rss>';
585 exit;
586}
587
588// ------------------------------------------------------------------------------------------
589// Render HTML page:
590function renderPage()
591{
592 global $STARTTIME;
593 global $LINKSDB;
594
595 // 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.
596 // So I use a custom templating system.
597
598 // -------- Display login form.
599 if (startswith($_SERVER["QUERY_STRING"],'do=login'))
600 {
44a9d860 601 if (OPEN_SHAARLI) { header('Location: ?'); exit; } // No need to login for open Shaarli
ef734b5d
SS
602 if (!ban_canLogin())
603 {
604 $loginform='<div id="headerform">You have been banned from login after too many failed attempts. Try later.</div>';
605 $data = array('pageheader'=>$loginform,'body'=>'','onload'=>'');
606 templatePage($data);
607 exit;
608 }
609 $returnurl_html = (isset($_SERVER['HTTP_REFERER']) ? '<input type="hidden" name="returnurl" value="'.htmlspecialchars($_SERVER['HTTP_REFERER']).'">' : '');
610 $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"><input type="hidden" name="token" value="'.getToken().'">'.$returnurl_html.'</form></div>';
611 $onload = 'onload="document.loginform.login.focus();"';
612 $data = array('pageheader'=>$loginform,'body'=>'','onload'=>$onload);
613 templatePage($data);
614 exit;
615 }
616
617 // -------- User wants to logout.
618 if (startswith($_SERVER["QUERY_STRING"],'do=logout'))
619 {
ca201236 620 invalidateCaches();
ef734b5d
SS
621 logout();
622 header('Location: ?');
623 exit;
e6a0ab54
SS
624 }
625
626 // -------- Tag cloud
627 if (startswith($_SERVER["QUERY_STRING"],'do=tagcloud'))
628 {
629 $tags= $LINKSDB->allTags();
630 // We sort tags alphabetically, when choose a font size according to count.
631 // First, find max value.
632 $maxcount=0; foreach($tags as $key=>$value) $maxcount=max($maxcount,$value);
633 ksort($tags);
634 $cloud='';
635 foreach($tags as $key=>$value)
636 {
637 $size = max(40*$value/$maxcount,8); // Minimum size 8.
638 $colorvalue = 128-ceil(127*$value/$maxcount);
639 $color='rgb('.$colorvalue.','.$colorvalue.','.$colorvalue.')';
640 $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> ';
641 }
642 $cloud='<div id="cloudtag">'.$cloud.'</div>';
643 $data = array('pageheader'=>'','body'=>$cloud,'onload'=>'');
644 templatePage($data);
645 exit;
646 }
ef734b5d
SS
647
648 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
649 if (isset($_GET['addtag']))
650 {
651 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
4887ceda 652 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER
ef734b5d 653 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
4887ceda 654 $params['searchtags'] = (empty($params['searchtags']) ? trim($_GET['addtag']) : trim($params['searchtags'].' '.urlencode($_GET['addtag'])));
ef734b5d
SS
655 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
656 header('Location: ?'.http_build_query($params));
657 exit;
658 }
659
660 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
661 if (isset($_GET['removetag']))
662 {
663 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
4887ceda 664 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?'); exit; } // In case browser does not send HTTP_REFERER
ef734b5d
SS
665 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
666 if (isset($params['searchtags']))
667 {
668 $tags = explode(' ',$params['searchtags']);
669 $tags=array_diff($tags, array($_GET['removetag'])); // Remove value from array $tags.
670 if (count($tags)==0) unset($params['searchtags']); else $params['searchtags'] = implode(' ',$tags);
671 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
672 }
673 header('Location: ?'.http_build_query($params));
674 exit;
675 }
676
677 // -------- User wants to change the number of links per page (linksperpage=...)
678 if (isset($_GET['linksperpage']))
679 {
680 if (is_numeric($_GET['linksperpage'])) { $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage'])); }
4887ceda 681 header('Location: '.(empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']));
ef734b5d
SS
682 exit;
683 }
684
685
686 // -------- Handle other actions allowed for non-logged in users:
687 if (!isLoggedIn())
688 {
689 // User tries to post new link but is not loggedin:
690 // Show login screen, then redirect to ?post=...
691 if (isset($_GET['post']))
692 {
693 header('Location: ?do=login&post='.urlencode($_GET['post']).(isset($_GET['source'])?'&source='.urlencode($_GET['source']):'')); // Redirect to login page, then back to post link.
694 exit;
695 }
696
697 // Show search form and display list of links.
698 $searchform=<<<HTML
699<div id="headerform" style="width:100%; white-space:nowrap;";>
700 <form method="GET" name="searchform" style="display:inline;"><input type="text" name="searchterm" style="width:50%" value=""> <input type="submit" value="Search" class="bigbutton"></form>
701 <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
702</div>
703HTML;
704 $onload = 'document.searchform.searchterm.focus();';
705 $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload);
706 templatePage($data);
707 exit; // Never remove this one !
708 }
709
710 // -------- All other functions are reserved for the registered user:
711
712 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
713 if (startswith($_SERVER["QUERY_STRING"],'do=tools'))
714 {
715 $pageabsaddr=serverUrl().$_SERVER["SCRIPT_NAME"]; // Why doesn't php have a built-in function for that ?
716 // The javascript code for the bookmarklet:
717 $toolbar= <<<HTML
ca201236
SS
718<div id="headerform"><br>
719 <a href="?do=import"><b>Import</b></a> - Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)<br><br>
720 <a href="?do=export"><b>Export</b></a> - Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)<br><br>
721 <a class="smallbutton" style="color:black;" 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
722</div>
723HTML;
724 $data = array('pageheader'=>$toolbar,'body'=>'','onload'=>'');
725 templatePage($data);
726 exit;
727 }
728
729 // -------- User wants to add a link without using the bookmarklet: show form.
730 if (startswith($_SERVER["QUERY_STRING"],'do=addlink'))
731 {
732 $onload = 'document.addform.post.focus();';
733 $addform= '<div id="headerform"><form method="GET" action="" name="addform"><input type="text" name="post" style="width:70%;"> <input type="submit" value="Add link" class="bigbutton"></div>';
734 $data = array('pageheader'=>$addform,'body'=>'','onload'=>$onload);
735 templatePage($data);
736 exit;
737 }
738
739 // -------- User clicked the "Save" button when editing a link: Save link to database.
740 if (isset($_POST['save_edit']))
741 {
742 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
743 $linkdate=$_POST['lf_linkdate'];
744 $link = array('title'=>trim($_POST['lf_title']),'url'=>trim($_POST['lf_url']),'description'=>trim($_POST['lf_description']),'private'=>(isset($_POST['lf_private']) ? 1 : 0),
745 'linkdate'=>$linkdate,'tags'=>trim($_POST['lf_tags']));
746 if ($link['title']=='') $link['title']=$link['url']; // If title is empty, use the URL as title.
747 $LINKSDB[$linkdate] = $link;
748 $LINKSDB->savedb(); // save to disk
ca201236 749 invalidateCaches();
ef734b5d
SS
750
751 // If we are called from the bookmarklet, we must close the popup:
752 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
4887ceda
SS
753 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
754 header('Location: '.$returnurl); // After saving the link, redirect to the page the user was on.
ef734b5d
SS
755 exit;
756 }
757
758 // -------- User clicked the "Cancel" button when editing a link.
759 if (isset($_POST['cancel_edit']))
760 {
761 // If we are called from the bookmarklet, we must close the popup;
762 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
763 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
764 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
765 exit;
766 }
767
768 // -------- User clicked the "Delete" button when editing a link : Delete link from database.
769 if (isset($_POST['delete_link']))
770 {
771 if (!tokenOk($_POST['token'])) die('Wrong token.');
772 // We do not need to ask for confirmation:
773 // - confirmation is handled by javascript
774 // - we are protected from XSRF by the token.
775 $linkdate=$_POST['lf_linkdate'];
776 unset($LINKSDB[$linkdate]);
777 $LINKSDB->savedb(); // save to disk
ca201236 778 invalidateCaches();
ef734b5d
SS
779 // If we are called from the bookmarklet, we must close the popup:
780 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
781 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
782 header('Location: '.$returnurl); // After deleting the link, redirect to the page the user was on.
783 exit;
784 }
785
786 // -------- User clicked the "EDIT" button on a link: Display link edit form.
787 if (isset($_GET['edit_link']))
788 {
789 $link = $LINKSDB[$_GET['edit_link']]; // Read database
790 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
791 list($editform,$onload)=templateEditForm($link);
792 $data = array('pageheader'=>$editform,'body'=>'','onload'=>$onload);
793 templatePage($data);
794 exit;
795 }
796
797 // -------- User want to post a new link: Display link edit form.
798 if (isset($_GET['post']))
799 {
800 $url=$_GET['post'];
801
802 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
803 $i=strpos($url,'&utm_source='); if ($i) $url=substr($url,0,$i);
804 $i=strpos($url,'?utm_source='); if ($i) $url=substr($url,0,$i);
eae4f48b 805 $i=strpos($url,'#xtor=RSS-'); if ($i) $url=substr($url,0,$i);
ef734b5d
SS
806
807 $link_is_new = false;
808 $link = $LINKSDB->getLinkFromUrl($url); // Check if URL is not already in database (in this case, we will edit the existing link)
809 if (!$link)
810 {
811 $link_is_new = true; // This is a new link
812 $linkdate = strval(date('Ymd_His'));
813 $title = (empty($_GET['title']) ? '' : $_GET['title'] ); // Get title if it was provided in URL (by the bookmarklet).
814 $description=''; $tags=''; $private=0;
815 if (parse_url($url,PHP_URL_SCHEME)=='') $url = 'http://'.$url;
816 // 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.)
817 if (empty($title) && parse_url($url,PHP_URL_SCHEME)=='http')
818 {
819 list($status,$headers,$data) = getHTTP($url,4); // Short timeout to keep the application responsive.
1e49378a
SS
820 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
821 if (strpos($status,'200 OK')) $title=html_entity_decode(html_extract_title($data),ENT_QUOTES,'UTF-8');
ef734b5d
SS
822 }
823 $link = array('linkdate'=>$linkdate,'title'=>$title,'url'=>$url,'description'=>$description,'tags'=>$tags,'private'=>0);
824 }
825 list($editform,$onload)=templateEditForm($link,$link_is_new);
826 $data = array('pageheader'=>$editform,'body'=>'','onload'=>$onload);
827 templatePage($data);
828 exit;
829 }
830
831 // -------- Export as Netscape Bookmarks HTML file.
832 if (startswith($_SERVER["QUERY_STRING"],'do=export'))
ca201236
SS
833 {
834 if (empty($_GET['what']))
835 {
836 $toolbar= <<<HTML
837<div id="headerform"><br>
838 <a href="?do=export&what=all"><b>Export all</b></a> - Export all links<br><br>
839 <a href="?do=export&what=public"><b>Export public</b></a> - Export public links only<br><br>
840 <a href="?do=export&what=private"><b>Export private</b></a> - Export private links only<br><br>
841</div>
842HTML;
843 $data = array('pageheader'=>$toolbar,'body'=>'','onload'=>'');
844 templatePage($data);
845 exit;
846 }
847 $exportWhat=$_GET['what'];
848 if (!array_intersect(array('all','public','private'),array($exportWhat))) die('What are you trying to export ???');
849
ef734b5d 850 header('Content-Type: text/html; charset=utf-8');
ca201236 851 header('Content-disposition: attachment; filename=bookmarks_'.$exportWhat.'_'.strval(date('Ymd_His')).'.html');
ef734b5d
SS
852 echo <<<HTML
853<!DOCTYPE NETSCAPE-Bookmark-file-1>
854<!-- This is an automatically generated file.
855 It will be read and overwritten.
856 DO NOT EDIT! -->
857<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
858<TITLE>Bookmarks</TITLE>
859<H1>Bookmarks</H1>
860HTML;
861 foreach($LINKSDB as $link)
862 {
ca201236
SS
863 if ($exportWhat=='all' ||
864 ($exportWhat=='private' && $link['private']!=0) ||
865 ($exportWhat=='public' && $link['private']==0))
866 {
867 echo '<DT><A HREF="'.htmlspecialchars($link['url']).'" ADD_DATE="'.linkdate2timestamp($link['linkdate']).'" PRIVATE="'.$link['private'].'"';
868 if ($link['tags']!='') echo ' TAGS="'.htmlspecialchars(str_replace(' ',',',$link['tags'])).'"';
869 echo '>'.htmlspecialchars($link['title'])."</A>\n";
870 if ($link['description']!='') echo '<DD>'.htmlspecialchars($link['description'])."\n";
871 }
ef734b5d 872 }
ca201236 873 echo '<!-- Shaarli '.$exportWhat.' bookmarks export on '.date('Y/m/d H:i:s')."-->\n";
ef734b5d
SS
874 exit;
875 }
876
877 // -------- User is uploading a file for import
878 if (startswith($_SERVER["QUERY_STRING"],'do=upload'))
879 {
880 // If file is too big, some form field may be missing.
881 if (!isset($_POST['token']) || (!isset($_FILES)) || (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size']==0))
882 {
883 $returnurl = ( empty($_SERVER['HTTP_REFERER']) ? '?' : $_SERVER['HTTP_REFERER'] );
884 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>';
885 exit;
886 }
887 if (!tokenOk($_POST['token'])) die('Wrong token.');
888 importFile();
889 exit;
890 }
891
892 // -------- Show upload/import dialog:
893 if (startswith($_SERVER["QUERY_STRING"],'do=import'))
894 {
895 $token = getToken();
896 $maxfilesize=getMaxFileSize();
897 $onload = 'onload="document.uploadform.filetoupload.focus();"';
898 $uploadform=<<<HTML
899<div id="headerform">
900Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes).
901<form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform">
902 <input type="hidden" name="token" value="{$token}">
903 <input type="file" name="filetoupload" size="80">
904 <input type="hidden" name="MAX_FILE_SIZE" value="{$maxfilesize}">
ca201236 905 <input type="submit" name="import_file" value="Import" class="bigbutton"><br>
eae4f48b
SS
906 <input type="checkbox" name="private">&nbsp;Import all links as private<br>
907 <input type="checkbox" name="overwrite">&nbsp;Overwrite existing links
ef734b5d
SS
908</form>
909</div>
910HTML;
911 $data = array('pageheader'=>$uploadform,'body'=>'','onload'=>$onload );
912 templatePage($data);
913 exit;
914 }
915
916 // -------- Otherwise, simply display search form and links:
917 $searchform=<<<HTML
918<div id="headerform" style="width:100%; white-space:nowrap;";>
919 <form method="GET" name="searchform" style="display:inline;"><input type="text" name="searchterm" style="width:50%" value=""> <input type="submit" value="Search" class="bigbutton"></form>
920 <form method="GET" name="tagfilter" style="display:inline;padding-left:24px;"><input type="text" name="searchtags" style="width:20%" value=""> <input type="submit" value="Filter by tag" class="bigbutton"></form>
921</div>
922HTML;
923 $onload = 'document.searchform.searchterm.focus();';
924 $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload);
925 templatePage($data);
926 exit;
927}
928
929// -----------------------------------------------------------------------------------------------
930// Process the import file form.
931function importFile()
932{
933 global $LINKSDB;
934 $filename=$_FILES['filetoupload']['name'];
935 $filesize=$_FILES['filetoupload']['size'];
936 $data=file_get_contents($_FILES['filetoupload']['tmp_name']);
ca201236 937 $private = (empty($_POST['private']) ? 0 : 1); // Should the links be imported as private ?
eae4f48b
SS
938 $overwrite = !empty($_POST['overwrite']) ; // Should the imported links overwrite existing ones ?
939 $import_count=0;
ef734b5d
SS
940
941 // Sniff file type:
942 $type='unknown';
943 if (startsWith($data,'<!DOCTYPE NETSCAPE-Bookmark-file-1>')) $type='netscape'; // Netscape bookmark file (aka Firefox).
944
945 // Then import the bookmarks.
946 if ($type=='netscape')
947 {
948 // This is a standard Netscape-style bookmark file.
949 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.
950 // 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
951 foreach(explode('<DT>',$data) as $html) // explode is very fast
952 {
953 $link = array('linkdate'=>'','title'=>'','url'=>'','description'=>'','tags'=>'','private'=>0);
954 $d = explode('<DD>',$html);
955 if (startswith($d[0],'<A '))
956 {
eae4f48b 957 $link['description'] = (isset($d[1]) ? html_entity_decode(trim($d[1]),ENT_QUOTES,'UTF-8') : ''); // Get description (optional)
ef734b5d 958 preg_match('!<A .*?>(.*?)</A>!i',$d[0],$matches); $link['title'] = (isset($matches[1]) ? trim($matches[1]) : ''); // Get title
eae4f48b 959 $link['title'] = html_entity_decode($link['title'],ENT_QUOTES,'UTF-8');
ef734b5d
SS
960 preg_match_all('! ([A-Z_]+)=\"(.*?)"!i',$html,$matches,PREG_SET_ORDER); // Get all other attributes
961 foreach($matches as $m)
962 {
963 $attr=$m[1]; $value=$m[2];
eae4f48b 964 if ($attr=='HREF') $link['url']=html_entity_decode($value,ENT_QUOTES,'UTF-8');
ef734b5d
SS
965 elseif ($attr=='ADD_DATE') $link['linkdate']=date('Ymd_His',intval($value));
966 elseif ($attr=='PRIVATE') $link['private']=($value=='0'?0:1);
eae4f48b 967 elseif ($attr=='TAGS') $link['tags']=html_entity_decode(str_replace(',',' ',$value),ENT_QUOTES,'UTF-8');
ef734b5d 968 }
eae4f48b 969 if ($link['linkdate']!='' && $link['url']!='' && ($overwrite || empty($LINKSDB[$link['linkdate']])))
ca201236
SS
970 {
971 if ($private==1) $link['private']=1;
972 $LINKSDB[$link['linkdate']] = $link;
eae4f48b 973 $import_count++;
ca201236 974 }
ef734b5d
SS
975 }
976 }
ef734b5d 977 $LINKSDB->savedb();
ca201236 978 invalidateCaches();
eae4f48b 979 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) was successfully processed: '.$import_count.' links imported.");document.location=\'?\';</script>';
ef734b5d
SS
980 }
981 else
982 {
983 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) has an unknown file format. Nothing was imported.");document.location=\'?\';</script>';
984 }
985}
986
987// -----------------------------------------------------------------------------------------------
988/* Template for the edit link form
989 Input: $link : link to edit (assocative array item as returned by the LINKDB class)
990Output: An array : (string) : The html code of the edit link form.
991 (string) : The proper onload to use in body.
992 Example: list($html,$onload)=templateEditForm($mylinkdb['20110805_124532']);
993 echo $html;
994*/
995function templateEditForm($link,$link_is_new=false)
996{
997 $url=htmlspecialchars($link['url']);
998 $title=htmlspecialchars($link['title']);
999 $tags=htmlspecialchars($link['tags']);
1000 $description=htmlspecialchars($link['description']);
1001 $private = ($link['private']==0 ? '' : 'checked="yes"');
1002
1003 // Automatically focus on empty fields:
1004 $onload='onload="document.linkform.lf_tags.focus();"';
1005 if ($description=='') $onload='onload="document.linkform.lf_description.focus();"';
1006 if ($title=='') $onload='onload="document.linkform.lf_title.focus();"';
1007
1008 // Do not show "Delete" button if this is a new link.
1009 $delete_button = '<input type="submit" value="Delete" name="delete_link" class="bigbutton" style="margin-left:180px;" onClick="return confirmDeleteLink();">';
1010 if ($link_is_new) $delete_button='';
1011
1012 $token=getToken(); // XSRF protection.
1013 $returnurl_html = (isset($_SERVER['HTTP_REFERER']) ? '<input type="hidden" name="returnurl" value="'.htmlspecialchars($_SERVER['HTTP_REFERER']).'">' : '');
1014 $editlinkform=<<<HTML
1015<div id="editlinkform">
1016 <form method="post" name="linkform">
1017 <input type="hidden" name="lf_linkdate" value="{$link['linkdate']}">
1018 <i>URL</i><br><input type="text" name="lf_url" value="{$url}" style="width:100%"><br>
1019 <i>Title</i><br><input type="text" name="lf_title" value="{$title}" style="width:100%"><br>
1020 <i>Description</i><br><textarea name="lf_description" rows="4" cols="25" style="width:100%">{$description}</textarea><br>
44a9d860 1021 <i>Tags</i><br><input type="text" id="lf_tags" name="lf_tags" value="{$tags}" style="width:100%"><br>
ef734b5d
SS
1022 <input type="checkbox" {$private} style="margin:7 0 10 0;" name="lf_private">&nbsp;<i>Private</i><br>
1023 <input type="submit" value="Save" name="save_edit" class="bigbutton" style="margin-left:40px;">
1024 <input type="submit" value="Cancel" name="cancel_edit" class="bigbutton" style="margin-left:40px;">
1025 {$delete_button}
1026 <input type="hidden" name="token" value="{$token}">
1027 {$returnurl_html}
1028 </form>
1029</div>
1030HTML;
1031 return array($editlinkform,$onload);
1032}
1033
1034
1035// -----------------------------------------------------------------------------------------------
1036// Template for the list of links.
1037// Returns html code to show the list of link according to parameters passed in URL (search terms, page...)
1038function templateLinkList()
1039{
1040 global $LINKSDB;
1041
1042 // Search according to entered search terms:
1043 $linksToDisplay=array();
1044 $searched='';
1045 if (!empty($_GET['searchterm'])) // Fulltext search
1046 {
1047 $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
1048 $searched='&nbsp;<b>'.count($linksToDisplay).' results for <i>'.htmlspecialchars($_GET['searchterm']).'</i></b>:';
1049 }
1050 elseif (!empty($_GET['searchtags'])) // Search by tag
1051 {
1052 $linksToDisplay = $LINKSDB->filterTags($_GET['searchtags']);
1053 $tagshtml=''; foreach(explode(' ',$_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> ';
1054 $searched='&nbsp;<b>'.count($linksToDisplay).' results for tags '.$tagshtml.':</b>';
1055 }
1056 else
1057 $linksToDisplay = $LINKSDB; // otherwise, display without filtering.
1058
1059 $linklist='';
1060 $actions='';
1061
1062 // Handle paging.
1063 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ???
1064 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1065 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1066 */
1067 $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // Stupid and ugly. Thanks php.
1068 $pagecount = ceil(count($keys)/$_SESSION['LINKS_PER_PAGE']);
1069 $pagecount = ($pagecount==0 ? 1 : $pagecount);
1070 $page=( empty($_GET['page']) ? 1 : intval($_GET['page']));
1071 $page = ( $page<1 ? 1 : $page );
1072 $page = ( $page>$pagecount ? $pagecount : $page );
1073 $i = ($page-1)*$_SESSION['LINKS_PER_PAGE']; // Start index.
1074 $end = $i+$_SESSION['LINKS_PER_PAGE'];
1075 while ($i<$end && $i<count($keys))
1076 {
1077 $link = $linksToDisplay[$keys[$i]];
1078 $description=$link['description'];
1079 $title=$link['title'];
1080 $classprivate = ($link['private']==0 ? '' : 'class="private"');
1081 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>';
1082 $tags='';
1083 if ($link['tags']!='') foreach(explode(' ',$link['tags']) as $tag) { $tags.='<span class="linktag" title="Add tag"><a href="?addtag='.htmlspecialchars($tag).'">'.htmlspecialchars($tag).'</a></span> '; }
1084 $linklist.='<li '.$classprivate.'><span class="linktitle"><a href="'.htmlspecialchars($link['url']).'">'.htmlspecialchars($title).'</a></span>'.$actions.'<br>';
4887ceda 1085 if ($description!='') $linklist.='<div class="linkdescription">'.nl2br(htmlspecialchars($description)).'</div><br>';
e6a0ab54
SS
1086 if (!HIDE_TIMESTAMPS || isLoggedIn()) $linklist.='<span class="linkdate">'.htmlspecialchars(linkdate2locale($link['linkdate'])).' - </span>';
1087 $linklist.='<span class="linkurl">'.htmlspecialchars($link['url']).'</span><br>'.$tags."</li>\n";
ef734b5d
SS
1088 $i++;
1089 }
1090
1091 // Show paging.
1092 $searchterm= ( empty($_GET['searchterm']) ? '' : '&searchterm='.$_GET['searchterm'] );
1093 $searchtags= ( empty($_GET['searchtags']) ? '' : '&searchtags='.$_GET['searchtags'] );
1094 $paging='';
1095 if ($i!=count($keys)) $paging.='<a href="?page='.($page+1).$searchterm.$searchtags.'">&#x25C4;Older</a>';
1096 $paging.= '<span style="color:#fff; padding:0 20 0 20;">page '.$page.' / '.$pagecount.'</span>';
1097 if ($page>1) $paging.='<a href="?page='.($page-1).$searchterm.$searchtags.'">Newer&#x25BA;</a>';
1098 $linksperpage = <<<HTML
1099<div style="float:right; padding-right:5px;">
1100Links per page: <a href="?linksperpage=20">20</a> <a href="?linksperpage=50">50</a> <a href="?linksperpage=100">100</a>
1101 <form method="GET" style="display:inline;"><input type="text" name="linksperpage" size="2" style="height:15px;"></form></div>
1102HTML;
1103 $paging = '<div class="paging">'.$linksperpage.$paging.'</div>';
1104 $linklist='<div id="linklist">'.$paging.$searched.'<ul>'.$linklist.'</ul>'.$paging.'</div>';
1105 return $linklist;
1106}
1107
1108// -----------------------------------------------------------------------------------------------
1109// Template for the whole page.
1110/* Input: $data (associative array).
1111 Keys: 'body' : body of HTML document
1112 'pageheader' : html code to show in page header (top of page)
1113 'onload' : optional onload javascript for the <body>
1114*/
1115function templatePage($data)
1116{
1117 global $STARTTIME;
1118 global $LINKSDB;
1119 $shaarli_version = shaarli_version;
e6a0ab54
SS
1120
1121 $newversion=checkUpdate();
1122 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
1123 $linkcount = count($LINKSDB);
1124 $open='';
1125 if (OPEN_SHAARLI)
1126 {
1127 $menu=' <a href="?do=tools">Tools</a> &nbsp;<a href="?do=addlink"><b>Add link</b></a>';
1128 $open='Open ';
1129 }
1130 else
1131 $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>');
ef734b5d
SS
1132 foreach(array('pageheader','body','onload') as $k) // make sure all required fields exist (put an empty string if not).
1133 {
1134 if (!array_key_exists($k,$data)) $data[$k]='';
1135 }
44a9d860
SS
1136 $jsincludes=''; $jsincludes_bottom = '';
1137 if (OPEN_SHAARLI || isLoggedIn())
1138 {
1139 $jsincludes='<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>';
1140 $source = serverUrl().$_SERVER['SCRIPT_NAME'].'?ws=tags';
1141 $jsincludes_bottom = <<<JS
1142<script language="JavaScript">
1143$(document).ready(function()
1144{
1145 $('#lf_tags').autocomplete({source:'{$source}',minLength:0});
1146});
1147</script>
1148JS;
1149 }
ef734b5d
SS
1150 $feedurl=htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME'].'?do=rss');
1151 echo <<<HTML
1152<html>
1153<head>
44a9d860 1154<title>{$open}Shaarli - Let's shaare your links...</title>
eae4f48b
SS
1155<link rel="alternate" type="application/rss+xml" href="{$feedurl}" />
1156<link type="text/css" rel="stylesheet" href="shaarli.css" />
44a9d860 1157{$jsincludes}
ef734b5d 1158</head>
e6a0ab54 1159<body {$data['onload']}>{$newversion}
ef734b5d 1160<div id="pageheader"><div style="float:right; font-style:italic; color:#bbb; text-align:right; padding:0 5 0 0;">Shaare your links...<br>{$linkcount} links</div>
44a9d860 1161 <b><i>{$open}Shaarli {$shaarli_version}</i></b> - <a href="?">Home</a>&nbsp;{$menu}&nbsp;<a href="{$feedurl}" style="padding-left:30px;">RSS Feed</a>
e6a0ab54
SS
1162&nbsp;&nbsp; <a href="?do=tagcloud">Tag cloud</a>
1163{$data['pageheader']}
ef734b5d
SS
1164</div>
1165{$data['body']}
1166
1167HTML;
1168 $exectime = round(microtime(true)-$STARTTIME,4);
1169 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<br>Who gives a shit that this page was generated in '.$exectime.' seconds&nbsp;?</div>';
1170 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 1171 echo $jsincludes_bottom.'</body></html>';
ef734b5d
SS
1172}
1173
1174// -----------------------------------------------------------------------------------------------
1175// Installation
1176// This function should NEVER be called if the file data/config.php exists.
1177function install()
1178{
eae4f48b
SS
1179 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1180 if (endsWith($_SERVER['SERVER_NAME'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1181
4887ceda 1182 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
ef734b5d 1183 {
4887ceda
SS
1184 $tz=(empty($_POST['settimezone']) ? 'UTC':$_POST['settimezone']);
1185 // Everything is ok, let's create config file.
1186 $salt=sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
1187 $hash = sha1($_POST['setpassword'].$_POST['setlogin'].$salt);
1188 $config='<?php $GLOBALS[\'login\']='.var_export($_POST['setlogin'],true).'; $GLOBALS[\'hash\']='.var_export($hash,true).'; $GLOBALS[\'salt\']='.var_export($salt,true).'; date_default_timezone_set('.var_export($tz,true).'); ?>';
44a9d860
SS
1189 if (!file_put_contents(CONFIG_FILE,$config) || strcmp(file_get_contents(CONFIG_FILE),$config)!=0)
1190 {
1191 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>';
1192 exit;
1193 }
4887ceda
SS
1194 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location=\'?do=login\';</script>';
1195 exit;
1196 }
ef734b5d 1197 // Display config form:
4887ceda
SS
1198 $timezoneselect='';
1199 if (function_exists('timezone_identifiers_list')) // because of old php version (5.1) which can be found on free.fr
1200 {
1201 $timezones='';
1202 foreach(timezone_identifiers_list() as $tz) $timezones.='<option value="'.htmlspecialchars($tz).'">'.htmlspecialchars($tz)."</option>\n";
1203 $timezoneselect='Timezone: <select name="settimezone"><option value="" selected>(please select:)</option>'.$timezones.'</select><br><br>';
1204 }
ef734b5d 1205 echo <<<HTML
eae4f48b
SS
1206<html><head><title>Shaarli - Configuration</title><link type="text/css" rel="stylesheet" href="shaarli.css" /></head>
1207<body onload="document.configform.setlogin.focus();" style="padding:20px;"><h1>Shaarli - Shaare your links...</h1>
1208It looks like it's the first time you run Shaarli. Please chose a login/password and a timezone:<br>
ef734b5d
SS
1209<form method="POST" action="" name="configform" style="border:1px solid black; padding:10 10 10 10;">
1210Login: <input type="text" name="setlogin"><br><br>Password: <input type="password" name="setpassword"><br><br>
4887ceda 1211{$timezoneselect}
ef734b5d
SS
1212<input type="submit" name="Save" value="Save config" class="bigbutton"></form></body></html>
1213HTML;
1214 exit;
1215}
1216
44a9d860
SS
1217// Webservices (for use with jQuery/jQueryUI)
1218// eg. index.php?ws=tags&term=minecr
1219function processWS()
1220{
1221 if (empty($_GET['ws']) || empty($_GET['term'])) return;
1222 $term = $_GET['term'];
1223 global $LINKSDB;
1224 header('Content-Type: application/json; charset=utf-8');
1225
1226 // Search in tags
1227 if ($_GET['ws']=='tags')
1228 {
1229 $tags=explode(' ',$term); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d")
1230 $addtags=''; if ($tags) $addtags=implode(' ',$tags).' '; // We will pre-pend previous tags
1231 $suggested=array();
1232 /* To speed up things, we store list of tags in session */
1233 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags();
1234 foreach($_SESSION['tags'] as $key=>$value)
1235 {
1236 if (startsWith($key,$last,$case=false)) $suggested[$addtags.$key.' ']=0;
1237 }
1238 echo json_encode(array_keys($suggested));
1239 exit;
1240 }
1241}
1242
ca201236
SS
1243// Invalidate caches when the database is changed or the user logs out.
1244// (eg. tags cache).
1245function invalidateCaches()
1246{
1247 unset($_SESSION['tags']);
1248}
1249
44a9d860
SS
1250$LINKSDB=new linkdb(isLoggedIn() || OPEN_SHAARLI); // Read links from database (and filter private links if used it not logged in).
1251if (startswith($_SERVER["QUERY_STRING"],'ws=')) { processWS(); exit; } // Webservices (for jQuery/jQueryUI)
ef734b5d
SS
1252if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=LINKS_PER_PAGE;
1253if (startswith($_SERVER["QUERY_STRING"],'do=rss')) { showRSS(); exit; }
1254renderPage();
1255?>