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