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