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