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