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