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