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