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