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