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