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