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