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