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