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