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