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