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