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