]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
1558205139e099a688c40aac0402dc11b60d6553
[github/shaarli/Shaarli.git] / index.php
1 <?php
2 // Shaarli 0.0.18 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.18 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 ($newestversion!=shaarli_version) 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 localized date format.
314 (used to display link date on screen)
315 The date format is automatically chosen according to locale/languages sniffed from browser headers (see autoLocale()). */
316 function linkdate2locale($linkdate)
317 {
318 return utf8_encode(strftime('%c',linkdate2timestamp($linkdate))); // %c is for automatic date format according to locale.
319 // Note that if you use a local which is not installed on your webserver,
320 // the date will not be displayed in the chosen locale, but probably in US notation.
321 }
322
323 // Parse HTTP response headers and return an associative array.
324 function http_parse_headers( $headers )
325 {
326 $res=array();
327 foreach($headers as $header)
328 {
329 $i = strpos($header,': ');
330 if ($i)
331 {
332 $key=substr($header,0,$i);
333 $value=substr($header,$i+2,strlen($header)-$i-2);
334 $res[$key]=$value;
335 }
336 }
337 return $res;
338 }
339
340 /* GET an URL.
341 Input: $url : url to get (http://...)
342 $timeout : Network timeout (will wait this many seconds for an anwser before giving up).
343 Output: An array. [0] = HTTP status message (eg. "HTTP/1.1 200 OK") or error message
344 [1] = associative array containing HTTP response headers (eg. echo getHTTP($url)[1]['Content-Type'])
345 [2] = data
346 Example: list($httpstatus,$headers,$data) = getHTTP('http://sebauvage.net/');
347 if (strpos($httpstatus,'200 OK'))
348 echo 'Data type: '.htmlspecialchars($headers['Content-Type']);
349 else
350 echo 'There was an error: '.htmlspecialchars($httpstatus)
351 */
352 function getHTTP($url,$timeout=30)
353 {
354 try
355 {
356 $options = array('http'=>array('method'=>'GET','timeout' => $timeout)); // Force network timeout
357 $context = stream_context_create($options);
358 $data=file_get_contents($url,false,$context,-1, 2000000); // We download at most 2 Mb from source.
359 if (!$data) { $lasterror=error_get_last(); return array($lasterror['message'],array(),''); }
360 $httpStatus=$http_response_header[0]; // eg. "HTTP/1.1 200 OK"
361 $responseHeaders=http_parse_headers($http_response_header);
362 return array($httpStatus,$responseHeaders,$data);
363 }
364 catch (Exception $e) // getHTTP *can* fail silentely (we don't care if the title cannot be fetched)
365 {
366 return array($e->getMessage(),'','');
367 }
368 }
369
370 // Extract title from an HTML document.
371 // (Returns an empty string if not found.)
372 function html_extract_title($html)
373 {
374 return preg_match('!<title>(.*?)</title>!i', $html, $matches) ? $matches[1] : '';
375 }
376
377 // ------------------------------------------------------------------------------------------
378 // Token management for XSRF protection
379 // Token should be used in any form which acts on data (create,update,delete,import...).
380 if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
381
382 // Returns a token.
383 function getToken()
384 {
385 $rnd = sha1(uniqid('',true).'_'.mt_rand()); // We generate a random string.
386 $_SESSION['tokens'][$rnd]=1; // Store it on the server side.
387 return $rnd;
388 }
389
390 // Tells if a token is ok. Using this function will destroy the token.
391 // true=token is ok.
392 function tokenOk($token)
393 {
394 if (isset($_SESSION['tokens'][$token]))
395 {
396 unset($_SESSION['tokens'][$token]); // Token is used: destroy it.
397 return true; // Token is ok.
398 }
399 return false; // Wrong token, or already used.
400 }
401
402 // ------------------------------------------------------------------------------------------
403 /* Data storage for links.
404 This object behaves like an associative array.
405 Example:
406 $mylinks = new linkdb();
407 echo $mylinks['20110826_161819']['title'];
408 foreach($mylinks as $link)
409 echo $link['title'].' at url '.$link['url'].' ; description:'.$link['description'];
410
411 We implement 3 interfaces:
412 - ArrayAccess so that this object behaves like an associative array.
413 - Iterator so that this object can be used in foreach() loops.
414 - Countable interface so that we can do a count() on this object.
415 */
416 class linkdb implements Iterator, Countable, ArrayAccess
417
418 {
419 private $links; // List of links (associative array. Key=linkdate (eg. "20110823_124546"), value= associative array (keys:title,description...)
420 private $urls; // List of all recorded URLs (key=url, value=linkdate) for fast reserve search (url-->linkdate)
421 private $keys; // List of linkdate keys (for the Iterator interface implementation)
422 private $position; // Position in the $this->keys array. (for the Iterator interface implementation.)
423 private $loggedin; // Is the used logged in ? (used to filter private links)
424
425 // Constructor:
426 function __construct($isLoggedIn)
427 // Input : $isLoggedIn : is the used logged in ?
428 {
429 $this->loggedin = $isLoggedIn;
430 $this->checkdb(); // Make sure data file exists.
431 $this->readdb(); // Then read it.
432 }
433
434 // ---- Countable interface implementation
435 public function count() { return count($this->links); }
436
437 // ---- ArrayAccess interface implementation
438 public function offsetSet($offset, $value)
439 {
440 if (!$this->loggedin) die('You are not authorized to add a link.');
441 if (empty($value['linkdate']) || empty($value['url'])) die('Internal Error: A link should always have a linkdate and url.');
442 if (empty($offset)) die('You must specify a key.');
443 $this->links[$offset] = $value;
444 $this->urls[$value['url']]=$offset;
445 }
446 public function offsetExists($offset) { return array_key_exists($offset,$this->links); }
447 public function offsetUnset($offset)
448 {
449 if (!$this->loggedin) die('You are not authorized to delete a link.');
450 $url = $this->links[$offset]['url']; unset($this->urls[$url]);
451 unset($this->links[$offset]);
452 }
453 public function offsetGet($offset) { return isset($this->links[$offset]) ? $this->links[$offset] : null; }
454
455 // ---- Iterator interface implementation
456 function rewind() { $this->keys=array_keys($this->links); rsort($this->keys); $this->position=0; } // Start over for iteration, ordered by date (latest first).
457 function key() { return $this->keys[$this->position]; } // current key
458 function current() { return $this->links[$this->keys[$this->position]]; } // current value
459 function next() { ++$this->position; } // go to next item
460 function valid() { return isset($this->keys[$this->position]); } // Check if current position is valid.
461
462 // ---- Misc methods
463 private function checkdb() // Check if db directory and file exists.
464 {
465 if (!file_exists(DATASTORE)) // Create a dummy database for example.
466 {
467 $this->links = array();
468 $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');
469 $this->links[$link['linkdate']] = $link;
470 $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');
471 $this->links[$link['linkdate']] = $link;
472 file_put_contents(DATASTORE, PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX); // Write database to disk
473 }
474 }
475
476 // Read database from disk to memory
477 private function readdb()
478 {
479 // Read data
480 $this->links=(file_exists(DATASTORE) ? unserialize(gzinflate(base64_decode(substr(file_get_contents(DATASTORE),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() );
481 // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439
482
483 // If user is not logged in, filter private links.
484 if (!$this->loggedin)
485 {
486 $toremove=array();
487 foreach($this->links as $link) { if ($link['private']!=0) $toremove[]=$link['linkdate']; }
488 foreach($toremove as $linkdate) { unset($this->links[$linkdate]); }
489 }
490
491 // Keep the list of the mapping URLs-->linkdate up-to-date.
492 $this->urls=array();
493 foreach($this->links as $link) { $this->urls[$link['url']]=$link['linkdate']; }
494 }
495
496 // Save database from memory to disk.
497 public function savedb()
498 {
499 if (!$this->loggedin) die('You are not authorized to change the database.');
500 file_put_contents(DATASTORE, PHPPREFIX.base64_encode(gzdeflate(serialize($this->links))).PHPSUFFIX);
501 }
502
503 // Returns the link for a given URL (if it exists). false it does not exist.
504 public function getLinkFromUrl($url)
505 {
506 if (isset($this->urls[$url])) return $this->links[$this->urls[$url]];
507 return false;
508 }
509
510 // Case insentitive search among links (in url, title and description). Returns filtered list of links.
511 // eg. print_r($mydb->filterFulltext('hollandais'));
512 public function filterFulltext($searchterms)
513 {
514 // FIXME: explode(' ',$searchterms) and perform a AND search.
515 // FIXME: accept double-quotes to search for a string "as is" ?
516 $filtered=array();
517 $s = strtolower($searchterms);
518 foreach($this->links as $l)
519 {
520 $found=strpos(strtolower($l['title']),$s) || strpos(strtolower($l['description']),$s) || strpos(strtolower($l['url']),$s) || strpos(strtolower($l['tags']),$s);
521 if ($found) $filtered[$l['linkdate']] = $l;
522 }
523 krsort($filtered);
524 return $filtered;
525 }
526
527 // Filter by tag.
528 // You can specify one or more tags (tags can be separated by space or comma).
529 // eg. print_r($mydb->filterTags('linux programming'));
530 public function filterTags($tags,$casesensitive=false)
531 {
532 $t = str_replace(',',' ',($casesensitive?$tags:strtolower($tags)));
533 $searchtags=explode(' ',$t);
534 $filtered=array();
535 foreach($this->links as $l)
536 {
537 $linktags = explode(' ',($casesensitive?$l['tags']:strtolower($l['tags'])));
538 if (count(array_intersect($linktags,$searchtags)) == count($searchtags))
539 $filtered[$l['linkdate']] = $l;
540 }
541 krsort($filtered);
542 return $filtered;
543 }
544
545 // Returns the list of all tags
546 // Output: associative array key=tags, value=0
547 public function allTags()
548 {
549 $tags=array();
550 foreach($this->links as $link)
551 foreach(explode(' ',$link['tags']) as $tag)
552 if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1);
553 arsort($tags); // Sort tags by usage (most used tag first)
554 return $tags;
555 }
556 }
557
558 // ------------------------------------------------------------------------------------------
559 // Ouput the last 50 links in RSS 2.0 format.
560 function showRSS()
561 {
562 global $LINKSDB;
563
564 // Optionnaly filter the results:
565 $linksToDisplay=array();
566 if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
567 elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
568 else $linksToDisplay = $LINKSDB;
569
570 header('Content-Type: application/xhtml+xml; charset=utf-8');
571 $pageaddr=htmlspecialchars(serverUrl().$_SERVER["SCRIPT_NAME"]);
572 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">';
573 echo '<channel><title>'.htmlspecialchars($GLOBALS['title']).'</title><link>'.$pageaddr.'</link>';
574 echo '<description>Shared links</description><language></language><copyright>'.$pageaddr.'</copyright>'."\n\n";
575 $i=0;
576 $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys().
577 while ($i<50 && $i<count($keys))
578 {
579 $link = $linksToDisplay[$keys[$i]];
580 $rfc822date = linkdate2rfc822($link['linkdate']);
581 echo '<item><title>'.htmlspecialchars($link['title']).'</title><guid>'.htmlspecialchars($link['url']).'</guid><link>'.htmlspecialchars($link['url']).'</link>';
582 if (!HIDE_TIMESTAMPS || isLoggedIn()) echo '<pubDate>'.htmlspecialchars($rfc822date).'</pubDate>';
583 echo '<description><![CDATA['.nl2br(htmlspecialchars($link['description'])).']]></description></item>'."\n";
584 $i++;
585 }
586 echo '</channel></rss>';
587 exit;
588 }
589
590 // ------------------------------------------------------------------------------------------
591 // Render HTML page:
592 function renderPage()
593 {
594 global $STARTTIME;
595 global $LINKSDB;
596
597 // 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.
598 // So I use a custom templating system.
599
600 // -------- Display login form.
601 if (startswith($_SERVER["QUERY_STRING"],'do=login'))
602 {
603 if (OPEN_SHAARLI) { header('Location: ?'); exit; } // No need to login for open Shaarli
604 if (!ban_canLogin())
605 {
606 $loginform='<div id="headerform">You have been banned from login after too many failed attempts. Try later.</div>';
607 $data = array('pageheader'=>$loginform,'body'=>'','onload'=>'');
608 templatePage($data);
609 exit;
610 }
611 $returnurl_html = (isset($_SERVER['HTTP_REFERER']) ? '<input type="hidden" name="returnurl" value="'.htmlspecialchars($_SERVER['HTTP_REFERER']).'">' : '');
612 $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>';
613 $onload = 'onload="document.loginform.login.focus();"';
614 $data = array('pageheader'=>$loginform,'body'=>'','onload'=>$onload);
615 templatePage($data);
616 exit;
617 }
618
619 // -------- User wants to logout.
620 if (startswith($_SERVER["QUERY_STRING"],'do=logout'))
621 {
622 invalidateCaches();
623 logout();
624 header('Location: ?');
625 exit;
626 }
627
628 // -------- Tag cloud
629 if (startswith($_SERVER["QUERY_STRING"],'do=tagcloud'))
630 {
631 $tags= $LINKSDB->allTags();
632 // We sort tags alphabetically, then choose a font size according to count.
633 // First, find max value.
634 $maxcount=0; foreach($tags as $key=>$value) $maxcount=max($maxcount,$value);
635 ksort($tags);
636 $cloud='';
637 foreach($tags as $key=>$value)
638 {
639 $size = max(40*$value/$maxcount,8); // Minimum size 8.
640 $colorvalue = 128-ceil(127*$value/$maxcount);
641 $color='rgb('.$colorvalue.','.$colorvalue.','.$colorvalue.')';
642 $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> ';
643 }
644 $cloud='<div id="cloudtag">'.$cloud.'</div>';
645 $data = array('pageheader'=>'','body'=>$cloud,'onload'=>'');
646 templatePage($data);
647 exit;
648 }
649
650 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
651 if (isset($_GET['addtag']))
652 {
653 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
654 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER
655 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
656 $params['searchtags'] = (empty($params['searchtags']) ? trim($_GET['addtag']) : trim($params['searchtags']).' '.urlencode(trim($_GET['addtag'])));
657 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
658 header('Location: ?'.http_build_query($params));
659 exit;
660 }
661
662 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
663 if (isset($_GET['removetag']))
664 {
665 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
666 if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?'); exit; } // In case browser does not send HTTP_REFERER
667 parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
668 if (isset($params['searchtags']))
669 {
670 $tags = explode(' ',$params['searchtags']);
671 $tags=array_diff($tags, array($_GET['removetag'])); // Remove value from array $tags.
672 if (count($tags)==0) unset($params['searchtags']); else $params['searchtags'] = implode(' ',$tags);
673 unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
674 }
675 header('Location: ?'.http_build_query($params));
676 exit;
677 }
678
679 // -------- User wants to change the number of links per page (linksperpage=...)
680 if (isset($_GET['linksperpage']))
681 {
682 if (is_numeric($_GET['linksperpage'])) { $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage'])); }
683 header('Location: '.(empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']));
684 exit;
685 }
686
687
688 // -------- Handle other actions allowed for non-logged in users:
689 if (!isLoggedIn())
690 {
691 // User tries to post new link but is not loggedin:
692 // Show login screen, then redirect to ?post=...
693 if (isset($_GET['post']))
694 {
695 header('Location: ?do=login&post='.urlencode($_GET['post']).(isset($_GET['source'])?'&source='.urlencode($_GET['source']):'')); // Redirect to login page, then back to post link.
696 exit;
697 }
698
699 // Show search form and display list of links.
700 $searchform=<<<HTML
701 <div id="headerform" style="width:100%; white-space:nowrap;";>
702 <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>
703 <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>
704 </div>
705 HTML;
706 $onload = 'onload="document.searchform.searchterm.focus();"';
707 $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload);
708 templatePage($data);
709 exit; // Never remove this one ! All operations below are reserved for logged in user.
710 }
711
712 // -------- All other functions are reserved for the registered user:
713
714 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
715 if (startswith($_SERVER["QUERY_STRING"],'do=tools'))
716 {
717 $pageabsaddr=serverUrl().$_SERVER["SCRIPT_NAME"]; // Why doesn't php have a built-in function for that ?
718 // The javascript code for the bookmarklet:
719 $changepwd = (OPEN_SHAARLI ? '' : '<a href="?do=changepasswd"><b>Change password</b></a> - Change your password.<br><br>' );
720 $toolbar= <<<HTML
721 <div id="headerform"><br>
722 {$changepwd}
723 <a href="?do=configure"><b>Configure your Shaarli</b></a> - Change Title, timezone...<br><br>
724 <a href="?do=changetag"><b>Rename/delete tags</b></a> - Rename or delete a tag in all links.<br><br>
725 <a href="?do=import"><b>Import</b></a> - Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)<br><br>
726 <a href="?do=export"><b>Export</b></a> - Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)<br><br>
727 <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>
728 </div>
729 HTML;
730 $data = array('pageheader'=>$toolbar,'body'=>'','onload'=>'');
731 templatePage($data);
732 exit;
733 }
734
735 // -------- User wants to change his/her password.
736 if (startswith($_SERVER["QUERY_STRING"],'do=changepasswd'))
737 {
738 if (OPEN_SHAARLI) die('You are not supposed to change a password on an Open Shaarli.');
739 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
740 {
741 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
742
743 // Make sure old password is correct.
744 $oldhash = sha1($_POST['oldpassword'].$GLOBALS['login'].$GLOBALS['salt']);
745 if ($oldhash!=$GLOBALS['hash']) { echo '<script language="JavaScript">alert("The old password is not correct.");document.location=\'?do=changepasswd\';</script>'; exit; }
746 // Save new password
747 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
748 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']);
749 writeConfig();
750 echo '<script language="JavaScript">alert("Your password has been changed.");document.location=\'?do=tools\';</script>';
751 exit;
752 }
753 else
754 {
755 $token = getToken();
756 $changepwdform= <<<HTML
757 <form method="POST" action="" name="changepasswordform" style="padding:10 10 10 10;">
758 Old password: <input type="password" name="oldpassword">&nbsp; &nbsp;
759 New password: <input type="password" name="setpassword">
760 <input type="hidden" name="token" value="{$token}">
761 <input type="submit" name="Save" value="Save password" class="bigbutton"></form>
762 HTML;
763 $data = array('pageheader'=>$changepwdform,'body'=>'','onload'=>'onload="document.changepasswordform.oldpassword.focus();"');
764 templatePage($data);
765 exit;
766 }
767 }
768
769 // -------- User wants to change configuration
770 if (startswith($_SERVER["QUERY_STRING"],'do=configure'))
771 {
772 if (!empty($_POST['title']) )
773 {
774 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
775 $tz = 'UTC';
776 if (!empty($_POST['continent']) && !empty($_POST['city']))
777 if (isTZvalid($_POST['continent'],$_POST['city']))
778 $tz = $_POST['continent'].'/'.$_POST['city'];
779 $GLOBALS['timezone'] = $tz;
780 $GLOBALS['title']=$_POST['title'];
781 writeConfig();
782 echo '<script language="JavaScript">alert("Configuration was saved.");document.location=\'?do=tools\';</script>';
783 exit;
784 }
785 else
786 {
787 $token = getToken();
788 $title = htmlspecialchars( empty($GLOBALS['title']) ? '' : $GLOBALS['title'] , ENT_QUOTES);
789 list($timezone_form,$timezone_js) = templateTZform($GLOBALS['timezone']);
790 $timezone_html=''; if ($timezone_form!='') $timezone_html='<tr><td valign="top"><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>';
791 $changepwdform= <<<HTML
792 ${timezone_js}<form method="POST" action="" name="configform" id="configform"><input type="hidden" name="token" value="{$token}">
793 <table border="0" cellpadding="20">
794 <tr><td><b>Page title:</b></td><td><input type="text" name="title" id="title" size="50" value="{$title}"></td></tr>
795 {$timezone_html}
796 <tr><td></td><td align="right"><input type="submit" name="Save" value="Save config" class="bigbutton"></td></tr>
797 </table>
798 </form>
799 HTML;
800 $data = array('pageheader'=>$changepwdform,'body'=>'','onload'=>'onload="document.configform.title.focus();"');
801 templatePage($data);
802 exit;
803 }
804 }
805
806 // -------- User wants to rename a tag or delete it
807 if (startswith($_SERVER["QUERY_STRING"],'do=changetag'))
808 {
809 if (empty($_POST['fromtag']))
810 {
811 $token = getToken();
812 $changetagform = <<<HTML
813 <form method="POST" action="" name="changetag" style="padding:10 10 10 10;">
814 <input type="hidden" name="token" value="{$token}">
815 Tag: <input type="text" name="fromtag" id="fromtag">
816 <input type="text" name="totag" style="margin-left:40px;"><input type="submit" name="renametag" value="Rename tag" class="bigbutton">
817 &nbsp;&nbsp;or&nbsp; <input type="submit" name="deletetag" value="Delete tag" class="bigbutton" onClick="return confirmDeleteTag();"><br>(Case sensitive)</form>
818 <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>
819 HTML;
820 $data = array('pageheader'=>$changetagform,'body'=>'','onload'=>'onload="document.changetag.fromtag.focus();"');
821 templatePage($data);
822 exit;
823 }
824 if (!tokenOk($_POST['token'])) die('Wrong token.');
825
826 if (!empty($_POST['deletetag']) && !empty($_POST['fromtag']))
827 {
828 $needle=trim($_POST['fromtag']);
829 $linksToAlter = $LINKSDB->filterTags($needle,true); // true for case-sensitive tag search.
830 foreach($linksToAlter as $key=>$value)
831 {
832 $tags = explode(' ',trim($value['tags']));
833 unset($tags[array_search($needle,$tags)]); // Remove tag.
834 $value['tags']=trim(implode(' ',$tags));
835 $LINKSDB[$key]=$value;
836 }
837 $LINKSDB->savedb(); // save to disk
838 invalidateCaches();
839 echo '<script language="JavaScript">alert("Tag was removed from '.count($linksToAlter).' links.");document.location=\'?\';</script>';
840 exit;
841 }
842
843 // Rename a tag:
844 if (!empty($_POST['renametag']) && !empty($_POST['fromtag']) && !empty($_POST['totag']))
845 {
846 $needle=trim($_POST['fromtag']);
847 $linksToAlter = $LINKSDB->filterTags($needle,true); // true for case-sensitive tag search.
848 foreach($linksToAlter as $key=>$value)
849 {
850 $tags = explode(' ',trim($value['tags']));
851 $tags[array_search($needle,$tags)] = trim($_POST['totag']); // Remplace tags value.
852 $value['tags']=trim(implode(' ',$tags));
853 $LINKSDB[$key]=$value;
854 }
855 $LINKSDB->savedb(); // save to disk
856 invalidateCaches();
857 echo '<script language="JavaScript">alert("Tag was renamed in '.count($linksToAlter).' links.");document.location=\'?searchtags='.urlencode($_POST['totag']).'\';</script>';
858 exit;
859 }
860 }
861
862 // -------- User wants to add a link without using the bookmarklet: show form.
863 if (startswith($_SERVER["QUERY_STRING"],'do=addlink'))
864 {
865 $onload = 'onload="document.addform.post.focus();"';
866 $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>';
867 $data = array('pageheader'=>$addform,'body'=>'','onload'=>$onload);
868 templatePage($data);
869 exit;
870 }
871
872 // -------- User clicked the "Save" button when editing a link: Save link to database.
873 if (isset($_POST['save_edit']))
874 {
875 if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away !
876 $tags = trim(preg_replace('/\s\s+/',' ', $_POST['lf_tags'])); // Remove multiple spaces.
877 $linkdate=$_POST['lf_linkdate'];
878 $link = array('title'=>trim($_POST['lf_title']),'url'=>trim($_POST['lf_url']),'description'=>trim($_POST['lf_description']),'private'=>(isset($_POST['lf_private']) ? 1 : 0),
879 'linkdate'=>$linkdate,'tags'=>$tags);
880 if ($link['title']=='') $link['title']=$link['url']; // If title is empty, use the URL as title.
881 $LINKSDB[$linkdate] = $link;
882 $LINKSDB->savedb(); // save to disk
883 invalidateCaches();
884
885 // If we are called from the bookmarklet, we must close the popup:
886 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
887 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
888 header('Location: '.$returnurl); // After saving the link, redirect to the page the user was on.
889 exit;
890 }
891
892 // -------- User clicked the "Cancel" button when editing a link.
893 if (isset($_POST['cancel_edit']))
894 {
895 // If we are called from the bookmarklet, we must close the popup;
896 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
897 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
898 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
899 exit;
900 }
901
902 // -------- User clicked the "Delete" button when editing a link : Delete link from database.
903 if (isset($_POST['delete_link']))
904 {
905 if (!tokenOk($_POST['token'])) die('Wrong token.');
906 // We do not need to ask for confirmation:
907 // - confirmation is handled by javascript
908 // - we are protected from XSRF by the token.
909 $linkdate=$_POST['lf_linkdate'];
910 unset($LINKSDB[$linkdate]);
911 $LINKSDB->savedb(); // save to disk
912 invalidateCaches();
913 // If we are called from the bookmarklet, we must close the popup:
914 if (isset($_GET['source']) && $_GET['source']=='bookmarklet') { echo '<script language="JavaScript">self.close();</script>'; exit; }
915 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
916 header('Location: '.$returnurl); // After deleting the link, redirect to the page the user was on.
917 exit;
918 }
919
920 // -------- User clicked the "EDIT" button on a link: Display link edit form.
921 if (isset($_GET['edit_link']))
922 {
923 $link = $LINKSDB[$_GET['edit_link']]; // Read database
924 if (!$link) { header('Location: ?'); exit; } // Link not found in database.
925 list($editform,$onload)=templateEditForm($link);
926 $data = array('pageheader'=>$editform,'body'=>'','onload'=>$onload);
927 templatePage($data);
928 exit;
929 }
930
931 // -------- User want to post a new link: Display link edit form.
932 if (isset($_GET['post']))
933 {
934 $url=$_GET['post'];
935
936 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
937 $i=strpos($url,'&utm_source='); if ($i) $url=substr($url,0,$i);
938 $i=strpos($url,'?utm_source='); if ($i) $url=substr($url,0,$i);
939 $i=strpos($url,'#xtor=RSS-'); if ($i) $url=substr($url,0,$i);
940
941 $link_is_new = false;
942 $link = $LINKSDB->getLinkFromUrl($url); // Check if URL is not already in database (in this case, we will edit the existing link)
943 if (!$link)
944 {
945 $link_is_new = true; // This is a new link
946 $linkdate = strval(date('Ymd_His'));
947 $title = (empty($_GET['title']) ? '' : $_GET['title'] ); // Get title if it was provided in URL (by the bookmarklet).
948 $description=''; $tags=''; $private=0;
949 if (parse_url($url,PHP_URL_SCHEME)=='') $url = 'http://'.$url;
950 // 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.)
951 if (empty($title) && parse_url($url,PHP_URL_SCHEME)=='http')
952 {
953 list($status,$headers,$data) = getHTTP($url,4); // Short timeout to keep the application responsive.
954 // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
955 if (strpos($status,'200 OK')) $title=html_entity_decode(html_extract_title($data),ENT_QUOTES,'UTF-8');
956 }
957 $link = array('linkdate'=>$linkdate,'title'=>$title,'url'=>$url,'description'=>$description,'tags'=>$tags,'private'=>0);
958 }
959 list($editform,$onload)=templateEditForm($link,$link_is_new);
960 $data = array('pageheader'=>$editform,'body'=>'','onload'=>$onload);
961 templatePage($data);
962 exit;
963 }
964
965 // -------- Export as Netscape Bookmarks HTML file.
966 if (startswith($_SERVER["QUERY_STRING"],'do=export'))
967 {
968 if (empty($_GET['what']))
969 {
970 $toolbar= <<<HTML
971 <div id="headerform"><br>
972 <a href="?do=export&what=all"><b>Export all</b></a> - Export all links<br><br>
973 <a href="?do=export&what=public"><b>Export public</b></a> - Export public links only<br><br>
974 <a href="?do=export&what=private"><b>Export private</b></a> - Export private links only<br><br>
975 </div>
976 HTML;
977 $data = array('pageheader'=>$toolbar,'body'=>'','onload'=>'');
978 templatePage($data);
979 exit;
980 }
981 $exportWhat=$_GET['what'];
982 if (!array_intersect(array('all','public','private'),array($exportWhat))) die('What are you trying to export ???');
983
984 header('Content-Type: text/html; charset=utf-8');
985 header('Content-disposition: attachment; filename=bookmarks_'.$exportWhat.'_'.strval(date('Ymd_His')).'.html');
986 echo <<<HTML
987 <!DOCTYPE NETSCAPE-Bookmark-file-1>
988 <!-- This is an automatically generated file.
989 It will be read and overwritten.
990 DO NOT EDIT! -->
991 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
992 <TITLE>Bookmarks</TITLE>
993 <H1>Bookmarks</H1>
994 HTML;
995 foreach($LINKSDB as $link)
996 {
997 if ($exportWhat=='all' ||
998 ($exportWhat=='private' && $link['private']!=0) ||
999 ($exportWhat=='public' && $link['private']==0))
1000 {
1001 echo '<DT><A HREF="'.htmlspecialchars($link['url']).'" ADD_DATE="'.linkdate2timestamp($link['linkdate']).'" PRIVATE="'.$link['private'].'"';
1002 if ($link['tags']!='') echo ' TAGS="'.htmlspecialchars(str_replace(' ',',',$link['tags'])).'"';
1003 echo '>'.htmlspecialchars($link['title'])."</A>\n";
1004 if ($link['description']!='') echo '<DD>'.htmlspecialchars($link['description'])."\n";
1005 }
1006 }
1007 echo '<!-- Shaarli '.$exportWhat.' bookmarks export on '.date('Y/m/d H:i:s')."-->\n";
1008 exit;
1009 }
1010
1011 // -------- User is uploading a file for import
1012 if (startswith($_SERVER["QUERY_STRING"],'do=upload'))
1013 {
1014 // If file is too big, some form field may be missing.
1015 if (!isset($_POST['token']) || (!isset($_FILES)) || (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size']==0))
1016 {
1017 $returnurl = ( empty($_SERVER['HTTP_REFERER']) ? '?' : $_SERVER['HTTP_REFERER'] );
1018 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>';
1019 exit;
1020 }
1021 if (!tokenOk($_POST['token'])) die('Wrong token.');
1022 importFile();
1023 exit;
1024 }
1025
1026 // -------- Show upload/import dialog:
1027 if (startswith($_SERVER["QUERY_STRING"],'do=import'))
1028 {
1029 $token = getToken();
1030 $maxfilesize=getMaxFileSize();
1031 $onload = 'onload="document.uploadform.filetoupload.focus();"';
1032 $uploadform=<<<HTML
1033 <div id="headerform">
1034 Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes).
1035 <form method="POST" action="?do=upload" enctype="multipart/form-data" name="uploadform">
1036 <input type="hidden" name="token" value="{$token}">
1037 <input type="file" name="filetoupload" size="80">
1038 <input type="hidden" name="MAX_FILE_SIZE" value="{$maxfilesize}">
1039 <input type="submit" name="import_file" value="Import" class="bigbutton"><br>
1040 <input type="checkbox" name="private">&nbsp;Import all links as private<br>
1041 <input type="checkbox" name="overwrite">&nbsp;Overwrite existing links
1042 </form>
1043 </div>
1044 HTML;
1045 $data = array('pageheader'=>$uploadform,'body'=>'','onload'=>$onload );
1046 templatePage($data);
1047 exit;
1048 }
1049
1050 // -------- Otherwise, simply display search form and links:
1051 $searchform=<<<HTML
1052 <div id="headerform" style="width:100%; white-space:nowrap;";>
1053 <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>
1054 <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>
1055 </div>
1056 HTML;
1057 $onload = 'onload="document.searchform.searchterm.focus();"';
1058 $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload);
1059 templatePage($data);
1060 exit;
1061 }
1062
1063 // -----------------------------------------------------------------------------------------------
1064 // Process the import file form.
1065 function importFile()
1066 {
1067 global $LINKSDB;
1068 $filename=$_FILES['filetoupload']['name'];
1069 $filesize=$_FILES['filetoupload']['size'];
1070 $data=file_get_contents($_FILES['filetoupload']['tmp_name']);
1071 $private = (empty($_POST['private']) ? 0 : 1); // Should the links be imported as private ?
1072 $overwrite = !empty($_POST['overwrite']) ; // Should the imported links overwrite existing ones ?
1073 $import_count=0;
1074
1075 // Sniff file type:
1076 $type='unknown';
1077 if (startsWith($data,'<!DOCTYPE NETSCAPE-Bookmark-file-1>')) $type='netscape'; // Netscape bookmark file (aka Firefox).
1078
1079 // Then import the bookmarks.
1080 if ($type=='netscape')
1081 {
1082 // This is a standard Netscape-style bookmark file.
1083 // This format is supported by all browsers (except IE, of course), also delicious, diigo and others.
1084 // I didn't want to use DOM... anyway, this is FAST (less than 1 second to import 7200 links (2.1 Mb html file)).
1085 foreach(explode('<DT>',$data) as $html) // explode is very fast
1086 {
1087 $link = array('linkdate'=>'','title'=>'','url'=>'','description'=>'','tags'=>'','private'=>0);
1088 $d = explode('<DD>',$html);
1089 if (startswith($d[0],'<A '))
1090 {
1091 $link['description'] = (isset($d[1]) ? html_entity_decode(trim($d[1]),ENT_QUOTES,'UTF-8') : ''); // Get description (optional)
1092 preg_match('!<A .*?>(.*?)</A>!i',$d[0],$matches); $link['title'] = (isset($matches[1]) ? trim($matches[1]) : ''); // Get title
1093 $link['title'] = html_entity_decode($link['title'],ENT_QUOTES,'UTF-8');
1094 preg_match_all('! ([A-Z_]+)=\"(.*?)"!i',$html,$matches,PREG_SET_ORDER); // Get all other attributes
1095 foreach($matches as $m)
1096 {
1097 $attr=$m[1]; $value=$m[2];
1098 if ($attr=='HREF') $link['url']=html_entity_decode($value,ENT_QUOTES,'UTF-8');
1099 elseif ($attr=='ADD_DATE') $link['linkdate']=date('Ymd_His',intval($value));
1100 elseif ($attr=='PRIVATE') $link['private']=($value=='0'?0:1);
1101 elseif ($attr=='TAGS') $link['tags']=html_entity_decode(str_replace(',',' ',$value),ENT_QUOTES,'UTF-8');
1102 }
1103 if ($link['linkdate']!='' && $link['url']!='' && ($overwrite || empty($LINKSDB[$link['linkdate']])))
1104 {
1105 if ($private==1) $link['private']=1;
1106 $LINKSDB[$link['linkdate']] = $link;
1107 $import_count++;
1108 }
1109 }
1110 }
1111 $LINKSDB->savedb();
1112 invalidateCaches();
1113 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) was successfully processed: '.$import_count.' links imported.");document.location=\'?\';</script>';
1114 }
1115 else
1116 {
1117 echo '<script language="JavaScript">alert("File '.$filename.' ('.$filesize.' bytes) has an unknown file format. Nothing was imported.");document.location=\'?\';</script>';
1118 }
1119 }
1120
1121 // -----------------------------------------------------------------------------------------------
1122 /* Template for the edit link form
1123 Input: $link : link to edit (assocative array item as returned by the LINKDB class)
1124 Output: An array : (string) : The html code of the edit link form.
1125 (string) : The proper onload to use in body.
1126 Example: list($html,$onload)=templateEditForm($mylinkdb['20110805_124532']);
1127 echo $html;
1128 */
1129 function templateEditForm($link,$link_is_new=false)
1130 {
1131 $url=htmlspecialchars($link['url']);
1132 $title=htmlspecialchars($link['title']);
1133 $tags=htmlspecialchars($link['tags']);
1134 $description=htmlspecialchars($link['description']);
1135 $private = ($link['private']==0 ? '' : 'checked="yes"');
1136
1137 // Automatically focus on empty fields:
1138 $onload='onload="document.linkform.lf_tags.focus();"';
1139 if ($description=='') $onload='onload="document.linkform.lf_description.focus();"';
1140 if ($title=='') $onload='onload="document.linkform.lf_title.focus();"';
1141
1142 // Do not show "Delete" button if this is a new link.
1143 $delete_button = '<input type="submit" value="Delete" name="delete_link" class="bigbutton" style="margin-left:180px;" onClick="return confirmDeleteLink();">';
1144 if ($link_is_new) $delete_button='';
1145
1146 $token=getToken(); // XSRF protection.
1147 $returnurl_html = (isset($_SERVER['HTTP_REFERER']) ? '<input type="hidden" name="returnurl" value="'.htmlspecialchars($_SERVER['HTTP_REFERER']).'">' : '');
1148 $editlinkform=<<<HTML
1149 <div id="editlinkform">
1150 <form method="post" name="linkform">
1151 <input type="hidden" name="lf_linkdate" value="{$link['linkdate']}">
1152 <i>URL</i><br><input type="text" name="lf_url" value="{$url}" style="width:100%"><br>
1153 <i>Title</i><br><input type="text" name="lf_title" value="{$title}" style="width:100%"><br>
1154 <i>Description</i><br><textarea name="lf_description" rows="4" cols="25" style="width:100%">{$description}</textarea><br>
1155 <i>Tags</i><br><input type="text" id="lf_tags" name="lf_tags" value="{$tags}" style="width:100%"><br>
1156 <input type="checkbox" {$private} style="margin:7 0 10 0;" name="lf_private">&nbsp;<i>Private</i><br>
1157 <input type="submit" value="Save" name="save_edit" class="bigbutton" style="margin-left:40px;">
1158 <input type="submit" value="Cancel" name="cancel_edit" class="bigbutton" style="margin-left:40px;">
1159 {$delete_button}
1160 <input type="hidden" name="token" value="{$token}">
1161 {$returnurl_html}
1162 </form>
1163 </div>
1164 HTML;
1165 return array($editlinkform,$onload);
1166 }
1167
1168
1169 // -----------------------------------------------------------------------------------------------
1170 // Template for the list of links.
1171 // Returns html code to show the list of link according to parameters passed in URL (search terms, page...)
1172 function templateLinkList()
1173 {
1174 global $LINKSDB;
1175
1176 // Search according to entered search terms:
1177 $linksToDisplay=array();
1178 $searched='';
1179 if (!empty($_GET['searchterm'])) // Fulltext search
1180 {
1181 $linksToDisplay = $LINKSDB->filterFulltext(trim($_GET['searchterm']));
1182 $searched='&nbsp;<b>'.count($linksToDisplay).' results for <i>'.htmlspecialchars(trim($_GET['searchterm'])).'</i></b>:';
1183 }
1184 elseif (!empty($_GET['searchtags'])) // Search by tag
1185 {
1186 $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
1187 $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> ';
1188 $searched='&nbsp;<b>'.count($linksToDisplay).' results for tags '.$tagshtml.':</b>';
1189 }
1190 else
1191 $linksToDisplay = $LINKSDB; // otherwise, display without filtering.
1192
1193 $linklist='';
1194 $actions='';
1195
1196 // Handle paging.
1197 /* Can someone explain to me why you get the following error when using array_keys() on an object which implements the interface ArrayAccess ???
1198 "Warning: array_keys() expects parameter 1 to be array, object given in ... "
1199 If my class implements ArrayAccess, why won't array_keys() accept it ? ( $keys=array_keys($linksToDisplay); )
1200 */
1201 $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // Stupid and ugly. Thanks php.
1202 $pagecount = ceil(count($keys)/$_SESSION['LINKS_PER_PAGE']);
1203 $pagecount = ($pagecount==0 ? 1 : $pagecount);
1204 $page=( empty($_GET['page']) ? 1 : intval($_GET['page']));
1205 $page = ( $page<1 ? 1 : $page );
1206 $page = ( $page>$pagecount ? $pagecount : $page );
1207 $i = ($page-1)*$_SESSION['LINKS_PER_PAGE']; // Start index.
1208 $end = $i+$_SESSION['LINKS_PER_PAGE'];
1209 while ($i<$end && $i<count($keys))
1210 {
1211 $link = $linksToDisplay[$keys[$i]];
1212 $description=$link['description'];
1213 $title=$link['title'];
1214 $classprivate = ($link['private']==0 ? '' : 'class="private"');
1215 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>';
1216 $tags='';
1217 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> '; }
1218 $linklist.='<li '.$classprivate.'><span class="linktitle"><a href="'.htmlspecialchars($link['url']).'">'.htmlspecialchars($title).'</a></span>'.$actions.'<br>';
1219 if ($description!='') $linklist.='<div class="linkdescription">'.nl2br(htmlspecialchars($description)).'</div><br>';
1220 if (!HIDE_TIMESTAMPS || isLoggedIn()) $linklist.='<span class="linkdate">'.htmlspecialchars(linkdate2locale($link['linkdate'])).' - </span>';
1221 $linklist.='<span class="linkurl">'.htmlspecialchars($link['url']).'</span><br>'.$tags."</li>\n";
1222 $i++;
1223 }
1224
1225 // Show paging.
1226 $searchterm= ( empty($_GET['searchterm']) ? '' : '&searchterm='.$_GET['searchterm'] );
1227 $searchtags= ( empty($_GET['searchtags']) ? '' : '&searchtags='.$_GET['searchtags'] );
1228 $paging='';
1229 if ($i!=count($keys)) $paging.='<a href="?page='.($page+1).$searchterm.$searchtags.'">&#x25C4;Older</a>';
1230 $paging.= '<span style="color:#fff; padding:0 20 0 20;">page '.$page.' / '.$pagecount.'</span>';
1231 if ($page>1) $paging.='<a href="?page='.($page-1).$searchterm.$searchtags.'">Newer&#x25BA;</a>';
1232 $linksperpage = <<<HTML
1233 <div style="float:right; padding-right:5px;">
1234 Links per page: <a href="?linksperpage=20">20</a> <a href="?linksperpage=50">50</a> <a href="?linksperpage=100">100</a>
1235 <form method="GET" style="display:inline;"><input type="text" name="linksperpage" size="2" style="height:15px;"></form></div>
1236 HTML;
1237 $paging = '<div class="paging">'.$linksperpage.$paging.'</div>';
1238 $linklist='<div id="linklist">'.$paging.$searched.'<ul>'.$linklist.'</ul>'.$paging.'</div>';
1239 return $linklist;
1240 }
1241
1242 // -----------------------------------------------------------------------------------------------
1243 // Template for the whole page.
1244 /* Input: $data (associative array).
1245 Keys: 'body' : body of HTML document
1246 'pageheader' : html code to show in page header (top of page)
1247 'onload' : optional onload javascript for the <body>
1248 */
1249 function templatePage($data)
1250 {
1251 global $STARTTIME;
1252 global $LINKSDB;
1253 $shaarli_version = shaarli_version;
1254
1255 $newversion=checkUpdate();
1256 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>';
1257 $linkcount = count($LINKSDB);
1258 $open='';
1259 if (OPEN_SHAARLI)
1260 {
1261 $menu=' <a href="?do=tools">Tools</a> &nbsp;<a href="?do=addlink"><b>Add link</b></a>';
1262 $open='Open ';
1263 }
1264 else
1265 $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>');
1266
1267 foreach(array('pageheader','body','onload') as $k) // make sure all required fields exist (put an empty string if not).
1268 {
1269 if (!array_key_exists($k,$data)) $data[$k]='';
1270 }
1271 $jsincludes=''; $jsincludes_bottom = '';
1272 if (OPEN_SHAARLI || isLoggedIn())
1273 {
1274 $jsincludes='<script language="JavaScript" src="jquery.min.js"></script><script language="JavaScript" src="jquery-ui.custom.min.js"></script>';
1275 $source = serverUrl().$_SERVER['SCRIPT_NAME'];
1276 $jsincludes_bottom = <<<JS
1277 <script language="JavaScript">
1278 $(document).ready(function()
1279 {
1280 $('#lf_tags').autocomplete({source:'{$source}?ws=tags',minLength:1});
1281 $('#searchtags').autocomplete({source:'{$source}?ws=tags',minLength:1});
1282 $('#fromtag').autocomplete({source:'{$source}?ws=singletag',minLength:1});
1283 });
1284 </script>
1285 JS;
1286 }
1287 $feedurl=htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME'].'?do=rss');
1288 if (!empty($_GET['searchtags'])) $feedurl.='&searchtags='.$_GET['searchtags'];
1289 elseif (!empty($_GET['searchterm'])) $feedurl.='&searchterm='.$_GET['searchterm'];
1290
1291 $title = htmlspecialchars( $GLOBALS['title'] );
1292 echo <<<HTML
1293 <html>
1294 <head>
1295 <title>{$title}</title>
1296 <link rel="alternate" type="application/rss+xml" href="{$feedurl}" />
1297 <link type="text/css" rel="stylesheet" href="shaarli.css" />
1298 {$jsincludes}
1299 </head>
1300 <body {$data['onload']}>{$newversion}
1301 <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>
1302 <b><i>{$title}</i></b> - <a href="?">Home</a>&nbsp;{$menu}&nbsp;<a href="{$feedurl}" style="padding-left:30px;">RSS Feed</a>
1303 &nbsp;&nbsp; <a href="?do=tagcloud">Tag cloud</a>
1304 {$data['pageheader']}
1305 </div>
1306 {$data['body']}
1307
1308 HTML;
1309 $exectime = round(microtime(true)-$STARTTIME,4);
1310 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>';
1311 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>';
1312 echo $jsincludes_bottom.'</body></html>';
1313 }
1314
1315 // -----------------------------------------------------------------------------------------------
1316 // Installation
1317 // This function should NEVER be called if the file data/config.php exists.
1318 function install()
1319 {
1320 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1321 if (endsWith($_SERVER['SERVER_NAME'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
1322
1323 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
1324 {
1325 $tz = 'UTC';
1326 if (!empty($_POST['continent']) && !empty($_POST['city']))
1327 if (isTZvalid($_POST['continent'],$_POST['city']))
1328 $tz = $_POST['continent'].'/'.$_POST['city'];
1329 $GLOBALS['timezone'] = $tz;
1330 // Everything is ok, let's create config file.
1331 $GLOBALS['login'] = $_POST['setlogin'];
1332 $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless.
1333 $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']);
1334 $GLOBALS['title'] = (empty($_POST['title']) ? 'Shared links on '.htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME']) : $_POST['title'] );
1335 writeConfig();
1336 echo '<script language="JavaScript">alert("Shaarli is now configured. Please enter your login/password and start shaaring your links !");document.location=\'?do=login\';</script>';
1337 exit;
1338 }
1339
1340 // Display config form:
1341 list($timezone_form,$timezone_js) = templateTZform();
1342 $timezone_html=''; if ($timezone_form!='') $timezone_html='<tr><td valign="top"><b>Timezone:</b></td><td>'.$timezone_form.'</td></tr>';
1343 echo <<<HTML
1344 <html><head><title>Shaarli - Configuration</title><link type="text/css" rel="stylesheet" href="shaarli.css" />${timezone_js}</head>
1345 <body onload="document.installform.setlogin.focus();" style="padding:20px;"><h1>Shaarli - Shaare your links...</h1>
1346 It looks like it's the first time you run Shaarli. Please configure it:<br>
1347 <form method="POST" action="" name="installform" id="installform" style="border:1px solid black; padding:10 10 10 10;">
1348 <table border="0" cellpadding="20">
1349 <tr><td><b>Login:</b></td><td><input type="text" name="setlogin" size="30"></td></tr>
1350 <tr><td><b>Password:</b></td><td><input type="password" name="setpassword" size="30"></td></tr>
1351 {$timezone_html}
1352 <tr><td><b>Page title:</b></td><td><input type="text" name="title" size="30"></td></tr>
1353 <tr><td></td><td align="right"><input type="submit" name="Save" value="Save config" class="bigbutton"></td></tr>
1354 </table>
1355 </form></body></html>
1356 HTML;
1357 exit;
1358 }
1359
1360 // Generates the timezone selection form and javascript.
1361 // Input: (optional) current timezone (can be 'UTC/UTC'). It will be pre-selected.
1362 // Output: array(html,js)
1363 // Example: list($htmlform,$js) = templateTZform('Europe/Paris'); // Europe/Paris pre-selected.
1364 // Returns array('','') if server does not support timezones list. (eg. php 5.1 on free.fr)
1365 function templateTZform($ptz=false)
1366 {
1367 if (function_exists('timezone_identifiers_list')) // because of old php version (5.1) which can be found on free.fr
1368 {
1369 // Try to split the provided timezone.
1370 if ($ptz==false) { $l=timezone_identifiers_list(); $ptz=$l[0]; }
1371 $spos=strpos($ptz,'/'); $pcontinent=substr($ptz,0,$spos); $pcity=substr($ptz,$spos+1);
1372
1373 // Display config form:
1374 $timezone_form = '';
1375 $timezone_js = '';
1376 // The list is in the forme "Europe/Paris", "America/Argentina/Buenos_Aires"...
1377 // We split the list in continents/cities.
1378 $continents = array();
1379 $cities = array();
1380 foreach(timezone_identifiers_list() as $tz)
1381 {
1382 if ($tz=='UTC') $tz='UTC/UTC';
1383 $spos = strpos($tz,'/');
1384 if ($spos)
1385 {
1386 $continent=substr($tz,0,$spos); $city=substr($tz,$spos+1);
1387 $continents[$continent]=1;
1388 if (!isset($cities[$continent])) $cities[$continent]=array();
1389 $cities[$continent].='<option value="'.$city.'"'.($pcity==$city?'selected':'').'>'.$city.'</option>';
1390 }
1391 }
1392 $continents_html = '';
1393 $continents = array_keys($continents);
1394 foreach($continents as $continent)
1395 $continents_html.='<option value="'.$continent.'"'.($pcontinent==$continent?'selected':'').'>'.$continent.'</option>';
1396 $cities_html = $cities[$pcontinent];
1397 $timezone_form = "Continent: <select name=\"continent\" id=\"continent\" onChange=\"onChangecontinent();\">${continents_html}</select><br /><br />";
1398 $timezone_form .= "City: <select name=\"city\" id=\"city\">${cities[$pcontinent]}</select><br /><br />";
1399 $timezone_js = "<script language=\"JavaScript\">";
1400 $timezone_js .= "function onChangecontinent(){document.getElementById(\"city\").innerHTML = citiescontinent[document.getElementById(\"continent\").value];}";
1401 $timezone_js .= "var citiescontinent = ".json_encode($cities).";" ;
1402 $timezone_js .= "</script>" ;
1403 return array($timezone_form,$timezone_js);
1404 }
1405 return array('','');
1406 }
1407
1408 // Tells if a timezone is valid or not.
1409 // If not valid, returns false.
1410 // If system does not support timezone list, returns false.
1411 function isTZvalid($continent,$city)
1412 {
1413 $tz = $continent.'/'.$city;
1414 if (function_exists('timezone_identifiers_list')) // because of old php version (5.1) which can be found on free.fr
1415 {
1416 if (in_array($tz, timezone_identifiers_list())) // it's a valid timezone ?
1417 return true;
1418 }
1419 return false;
1420 }
1421
1422
1423 // Webservices (for use with jQuery/jQueryUI)
1424 // eg. index.php?ws=tags&term=minecr
1425 function processWS()
1426 {
1427 if (empty($_GET['ws']) || empty($_GET['term'])) return;
1428 $term = $_GET['term'];
1429 global $LINKSDB;
1430 header('Content-Type: application/json; charset=utf-8');
1431
1432 // Search in tags (case insentitive, cumulative search)
1433 if ($_GET['ws']=='tags')
1434 {
1435 $tags=explode(' ',$term); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d")
1436 $addtags=''; if ($tags) $addtags=implode(' ',$tags).' '; // We will pre-pend previous tags
1437 $suggested=array();
1438 /* To speed up things, we store list of tags in session */
1439 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags();
1440 foreach($_SESSION['tags'] as $key=>$value)
1441 {
1442 if (startsWith($key,$last,$case=false)) $suggested[$addtags.$key.' ']=0;
1443 }
1444 echo json_encode(array_keys($suggested));
1445 exit;
1446 }
1447
1448 // Search a single tag (case sentitive, single tag search)
1449 if ($_GET['ws']=='singletag')
1450 {
1451 /* To speed up things, we store list of tags in session */
1452 if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags();
1453 foreach($_SESSION['tags'] as $key=>$value)
1454 {
1455 if (startsWith($key,$term,$case=true)) $suggested[$key]=0;
1456 }
1457 echo json_encode(array_keys($suggested));
1458 exit;
1459 }
1460 }
1461
1462 // Re-write configuration file according to globals.
1463 // Requires some $GLOBALS to be set (login,hash,salt,title).
1464 // If the config file cannot be saved, an error message is dislayed and the user is redirected to "Tools" menu.
1465 // (otherwise, the function simply returns.)
1466 function writeConfig()
1467 {
1468 if (is_file(CONFIG_FILE) && !isLoggedIn()) die('You are not authorized to alter config.'); // Only logged in user can alter config.
1469 $config='<?php $GLOBALS[\'login\']='.var_export($GLOBALS['login'],true).'; $GLOBALS[\'hash\']='.var_export($GLOBALS['hash'],true).'; $GLOBALS[\'salt\']='.var_export($GLOBALS['salt'],true).'; ';
1470 $config .='$GLOBALS[\'timezone\']='.var_export($GLOBALS['timezone'],true).'; date_default_timezone_set('.var_export($GLOBALS['timezone'],true).'); $GLOBALS[\'title\']='.var_export($GLOBALS['title'],true).'; ?>';
1471 if (!file_put_contents(CONFIG_FILE,$config) || strcmp(file_get_contents(CONFIG_FILE),$config)!=0)
1472 {
1473 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>';
1474 exit;
1475 }
1476 }
1477
1478 // Invalidate caches when the database is changed or the user logs out.
1479 // (eg. tags cache).
1480 function invalidateCaches()
1481 {
1482 unset($_SESSION['tags']);
1483 }
1484
1485 $LINKSDB=new linkdb(isLoggedIn() || OPEN_SHAARLI); // Read links from database (and filter private links if used it not logged in).
1486 if (startswith($_SERVER["QUERY_STRING"],'ws=')) { processWS(); exit; } // Webservices (for jQuery/jQueryUI)
1487 if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=LINKS_PER_PAGE;
1488 if (startswith($_SERVER["QUERY_STRING"],'do=rss')) { showRSS(); exit; }
1489 renderPage();
1490 ?>