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