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