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