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