]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
Fix an issue with bookmark visibility filter
[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
15 // Set 'UTC' as the default timezone if it is not defined in php.ini
16 // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
17 if (date_default_timezone_get() == '') {
18 date_default_timezone_set('UTC');
19 }
20
21 /*
22 * PHP configuration
23 */
24
25 // http://server.com/x/shaarli --> /shaarli/
26 define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0)));
27
28 // High execution time in case of problematic imports/exports.
29 ini_set('max_input_time', '60');
30
31 // Try to set max upload file size and read
32 ini_set('memory_limit', '128M');
33 ini_set('post_max_size', '16M');
34 ini_set('upload_max_filesize', '16M');
35
36 // See all error except warnings
37 error_reporting(E_ALL^E_WARNING);
38
39 // 3rd-party libraries
40 if (! file_exists(__DIR__ . '/vendor/autoload.php')) {
41 header('Content-Type: text/plain; charset=utf-8');
42 echo "Error: missing Composer configuration\n\n"
43 ."If you installed Shaarli through Git or using the development branch,\n"
44 ."please refer to the installation documentation to install PHP"
45 ." dependencies using Composer:\n"
46 ."- https://shaarli.readthedocs.io/en/master/Server-configuration/\n"
47 ."- https://shaarli.readthedocs.io/en/master/Download-and-Installation/";
48 exit;
49 }
50 require_once 'inc/rain.tpl.class.php';
51 require_once __DIR__ . '/vendor/autoload.php';
52
53 // Shaarli library
54 require_once 'application/bookmark/LinkUtils.php';
55 require_once 'application/config/ConfigPlugin.php';
56 require_once 'application/feed/Cache.php';
57 require_once 'application/http/HttpUtils.php';
58 require_once 'application/http/UrlUtils.php';
59 require_once 'application/updater/UpdaterUtils.php';
60 require_once 'application/FileUtils.php';
61 require_once 'application/TimeZone.php';
62 require_once 'application/Utils.php';
63
64 use \Shaarli\ApplicationUtils;
65 use Shaarli\Bookmark\BookmarkServiceInterface;
66 use \Shaarli\Bookmark\Exception\BookmarkNotFoundException;
67 use Shaarli\Bookmark\Bookmark;
68 use Shaarli\Bookmark\BookmarkFilter;
69 use Shaarli\Bookmark\BookmarkFileService;
70 use \Shaarli\Config\ConfigManager;
71 use \Shaarli\Feed\CachedPage;
72 use \Shaarli\Feed\FeedBuilder;
73 use Shaarli\Formatter\FormatterFactory;
74 use \Shaarli\History;
75 use \Shaarli\Languages;
76 use \Shaarli\Netscape\NetscapeBookmarkUtils;
77 use \Shaarli\Plugin\PluginManager;
78 use \Shaarli\Render\PageBuilder;
79 use \Shaarli\Render\ThemeUtils;
80 use \Shaarli\Router;
81 use \Shaarli\Security\LoginManager;
82 use \Shaarli\Security\SessionManager;
83 use \Shaarli\Thumbnailer;
84 use \Shaarli\Updater\Updater;
85 use \Shaarli\Updater\UpdaterUtils;
86
87 // Ensure the PHP version is supported
88 try {
89 ApplicationUtils::checkPHPVersion('7.1', PHP_VERSION);
90 } catch (Exception $exc) {
91 header('Content-Type: text/plain; charset=utf-8');
92 echo $exc->getMessage();
93 exit;
94 }
95
96 define('SHAARLI_VERSION', ApplicationUtils::getVersion(__DIR__ .'/'. ApplicationUtils::$VERSION_FILE));
97
98 // Force cookie path (but do not change lifetime)
99 $cookie = session_get_cookie_params();
100 $cookiedir = '';
101 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
102 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
103 }
104 // Set default cookie expiration and path.
105 session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
106 // Set session parameters on server side.
107 // Use cookies to store session.
108 ini_set('session.use_cookies', 1);
109 // Force cookies for session (phpsessionID forbidden in URL).
110 ini_set('session.use_only_cookies', 1);
111 // Prevent PHP form using sessionID in URL if cookies are disabled.
112 ini_set('session.use_trans_sid', false);
113
114 session_name('shaarli');
115 // Start session if needed (Some server auto-start sessions).
116 if (session_status() == PHP_SESSION_NONE) {
117 session_start();
118 }
119
120 // Regenerate session ID if invalid or not defined in cookie.
121 if (isset($_COOKIE['shaarli']) && !SessionManager::checkId($_COOKIE['shaarli'])) {
122 session_regenerate_id(true);
123 $_COOKIE['shaarli'] = session_id();
124 }
125
126 $conf = new ConfigManager();
127
128 // In dev mode, throw exception on any warning
129 if ($conf->get('dev.debug', false)) {
130 // See all errors (for debugging only)
131 error_reporting(-1);
132
133 set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
134 throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
135 });
136 }
137
138 $sessionManager = new SessionManager($_SESSION, $conf);
139 $loginManager = new LoginManager($conf, $sessionManager);
140 $loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
141 $clientIpId = client_ip_id($_SERVER);
142
143 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
144 if (! defined('LC_MESSAGES')) {
145 define('LC_MESSAGES', LC_COLLATE);
146 }
147
148 // Sniff browser language and set date format accordingly.
149 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
150 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
151 }
152
153 new Languages(setlocale(LC_MESSAGES, 0), $conf);
154
155 $conf->setEmpty('general.timezone', date_default_timezone_get());
156 $conf->setEmpty('general.title', t('Shared bookmarks on '). escape(index_url($_SERVER)));
157 RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
158 RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
159
160 $pluginManager = new PluginManager($conf);
161 $pluginManager->load($conf->get('general.enabled_plugins'));
162
163 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
164
165 ob_start(); // Output buffering for the page cache.
166
167 // Prevent caching on client side or proxy: (yes, it's ugly)
168 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
169 header("Cache-Control: no-store, no-cache, must-revalidate");
170 header("Cache-Control: post-check=0, pre-check=0", false);
171 header("Pragma: no-cache");
172
173 if (! is_file($conf->getConfigFileExt())) {
174 // Ensure Shaarli has proper access to its resources
175 $errors = ApplicationUtils::checkResourcePermissions($conf);
176
177 if ($errors != array()) {
178 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
179
180 foreach ($errors as $error) {
181 $message .= '<li>'.$error.'</li>';
182 }
183 $message .= '</ul>';
184
185 header('Content-Type: text/html; charset=utf-8');
186 echo $message;
187 exit;
188 }
189
190 // Display the installation form if no existing config is found
191 install($conf, $sessionManager, $loginManager);
192 }
193
194 $loginManager->checkLoginState($_COOKIE, $clientIpId);
195
196 /**
197 * Adapter function to ensure compatibility with third-party templates
198 *
199 * @see https://github.com/shaarli/Shaarli/pull/1086
200 *
201 * @return bool true when the user is logged in, false otherwise
202 */
203 function isLoggedIn()
204 {
205 global $loginManager;
206 return $loginManager->isLoggedIn();
207 }
208
209
210 // ------------------------------------------------------------------------------------------
211 // Process login form: Check if login/password is correct.
212 if (isset($_POST['login'])) {
213 if (! $loginManager->canLogin($_SERVER)) {
214 die(t('I said: NO. You are banned for the moment. Go away.'));
215 }
216 if (isset($_POST['password'])
217 && $sessionManager->checkToken($_POST['token'])
218 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
219 ) {
220 $loginManager->handleSuccessfulLogin($_SERVER);
221
222 $cookiedir = '';
223 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
224 // Note: Never forget the trailing slash on the cookie path!
225 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
226 }
227
228 if (!empty($_POST['longlastingsession'])) {
229 // Keep the session cookie even after the browser closes
230 $sessionManager->setStaySignedIn(true);
231 $expirationTime = $sessionManager->extendSession();
232
233 setcookie(
234 $loginManager::$STAY_SIGNED_IN_COOKIE,
235 $loginManager->getStaySignedInToken(),
236 $expirationTime,
237 WEB_PATH
238 );
239 } else {
240 // Standard session expiration (=when browser closes)
241 $expirationTime = 0;
242 }
243
244 // Send cookie with the new expiration date to the browser
245 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
246 session_regenerate_id(true);
247
248 // Optional redirect after login:
249 if (isset($_GET['post'])) {
250 $uri = '?post='. urlencode($_GET['post']);
251 foreach (array('description', 'source', 'title', 'tags') as $param) {
252 if (!empty($_GET[$param])) {
253 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
254 }
255 }
256 header('Location: '. $uri);
257 exit;
258 }
259
260 if (isset($_GET['edit_link'])) {
261 header('Location: ?edit_link='. escape($_GET['edit_link']));
262 exit;
263 }
264
265 if (isset($_POST['returnurl'])) {
266 // Prevent loops over login screen.
267 if (strpos($_POST['returnurl'], 'do=login') === false) {
268 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
269 exit;
270 }
271 }
272 header('Location: ?');
273 exit;
274 } else {
275 $loginManager->handleFailedLogin($_SERVER);
276 $redir = '&username='. urlencode($_POST['login']);
277 if (isset($_GET['post'])) {
278 $redir .= '&post=' . urlencode($_GET['post']);
279 foreach (array('description', 'source', 'title', 'tags') as $param) {
280 if (!empty($_GET[$param])) {
281 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
282 }
283 }
284 }
285 // Redirect to login screen.
286 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
287 exit;
288 }
289 }
290
291 // ------------------------------------------------------------------------------------------
292 // Token management for XSRF protection
293 // Token should be used in any form which acts on data (create,update,delete,import...).
294 if (!isset($_SESSION['tokens'])) {
295 $_SESSION['tokens']=array(); // Token are attached to the session.
296 }
297
298 /**
299 * Daily RSS feed: 1 RSS entry per day giving all the bookmarks on that day.
300 * Gives the last 7 days (which have bookmarks).
301 * This RSS feed cannot be filtered.
302 *
303 * @param BookmarkServiceInterface $bookmarkService
304 * @param ConfigManager $conf Configuration Manager instance
305 * @param LoginManager $loginManager LoginManager instance
306 */
307 function showDailyRSS($bookmarkService, $conf, $loginManager)
308 {
309 // Cache system
310 $query = $_SERVER['QUERY_STRING'];
311 $cache = new CachedPage(
312 $conf->get('config.PAGE_CACHE'),
313 page_url($_SERVER),
314 startsWith($query, 'do=dailyrss') && !$loginManager->isLoggedIn()
315 );
316 $cached = $cache->cachedVersion();
317 if (!empty($cached)) {
318 echo $cached;
319 exit;
320 }
321
322 /* Some Shaarlies may have very few bookmarks, so we need to look
323 back in time until we have enough days ($nb_of_days).
324 */
325 $nb_of_days = 7; // We take 7 days.
326 $today = date('Ymd');
327 $days = array();
328
329 foreach ($bookmarkService->search() as $bookmark) {
330 $day = $bookmark->getCreated()->format('Ymd'); // Extract day (without time)
331 if (strcmp($day, $today) < 0) {
332 if (empty($days[$day])) {
333 $days[$day] = array();
334 }
335 $days[$day][] = $bookmark;
336 }
337
338 if (count($days) > $nb_of_days) {
339 break; // Have we collected enough days?
340 }
341 }
342
343 // Build the RSS feed.
344 header('Content-Type: application/rss+xml; charset=utf-8');
345 $pageaddr = escape(index_url($_SERVER));
346 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
347 echo '<channel>';
348 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
349 echo '<link>'. $pageaddr .'</link>';
350 echo '<description>Daily shared bookmarks</description>';
351 echo '<language>en-en</language>';
352 echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL;
353
354 $factory = new FormatterFactory($conf);
355 $formatter = $factory->getFormatter();
356 $formatter->addContextData('index_url', index_url($_SERVER));
357 // For each day.
358 /** @var Bookmark[] $bookmarks */
359 foreach ($days as $day => $bookmarks) {
360 $formattedBookmarks = [];
361 $dayDate = DateTime::createFromFormat(Bookmark::LINK_DATE_FORMAT, $day.'_000000');
362 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
363
364 // We pre-format some fields for proper output.
365 foreach ($bookmarks as $key => $bookmark) {
366 $formattedBookmarks[$key] = $formatter->format($bookmark);
367 // This page is a bit specific, we need raw description to calculate the length
368 $formattedBookmarks[$key]['formatedDescription'] = $formattedBookmarks[$key]['description'];
369 $formattedBookmarks[$key]['description'] = $bookmark->getDescription();
370
371 if ($bookmark->isNote()) {
372 $link['url'] = index_url($_SERVER) . $bookmark->getUrl(); // make permalink URL absolute
373 }
374 }
375
376 // Then build the HTML for this day:
377 $tpl = new RainTPL();
378 $tpl->assign('title', $conf->get('general.title'));
379 $tpl->assign('daydate', $dayDate->getTimestamp());
380 $tpl->assign('absurl', $absurl);
381 $tpl->assign('links', $formattedBookmarks);
382 $tpl->assign('rssdate', escape($dayDate->format(DateTime::RSS)));
383 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
384 $tpl->assign('index_url', $pageaddr);
385 $html = $tpl->draw('dailyrss', true);
386
387 echo $html . PHP_EOL;
388 }
389 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
390
391 $cache->cache(ob_get_contents());
392 ob_end_flush();
393 exit;
394 }
395
396 /**
397 * Show the 'Daily' page.
398 *
399 * @param PageBuilder $pageBuilder Template engine wrapper.
400 * @param BookmarkServiceInterface $bookmarkService instance.
401 * @param ConfigManager $conf Configuration Manager instance.
402 * @param PluginManager $pluginManager Plugin Manager instance.
403 * @param LoginManager $loginManager Login Manager instance
404 */
405 function showDaily($pageBuilder, $bookmarkService, $conf, $pluginManager, $loginManager)
406 {
407 if (isset($_GET['day'])) {
408 $day = $_GET['day'];
409 if ($day === date('Ymd', strtotime('now'))) {
410 $pageBuilder->assign('dayDesc', t('Today'));
411 } elseif ($day === date('Ymd', strtotime('-1 days'))) {
412 $pageBuilder->assign('dayDesc', t('Yesterday'));
413 }
414 } else {
415 $day = date('Ymd', strtotime('now')); // Today, in format YYYYMMDD.
416 $pageBuilder->assign('dayDesc', t('Today'));
417 }
418
419 $days = $bookmarkService->days();
420 $i = array_search($day, $days);
421 if ($i === false && count($days)) {
422 // no bookmarks for day, but at least one day with bookmarks
423 $i = count($days) - 1;
424 $day = $days[$i];
425 }
426 $previousday = '';
427 $nextday = '';
428
429 if ($i !== false) {
430 if ($i >= 1) {
431 $previousday = $days[$i - 1];
432 }
433 if ($i < count($days) - 1) {
434 $nextday = $days[$i + 1];
435 }
436 }
437 try {
438 $linksToDisplay = $bookmarkService->filterDay($day);
439 } catch (Exception $exc) {
440 error_log($exc);
441 $linksToDisplay = [];
442 }
443
444 $factory = new FormatterFactory($conf);
445 $formatter = $factory->getFormatter();
446 // We pre-format some fields for proper output.
447 foreach ($linksToDisplay as $key => $bookmark) {
448 $linksToDisplay[$key] = $formatter->format($bookmark);
449 // This page is a bit specific, we need raw description to calculate the length
450 $linksToDisplay[$key]['formatedDescription'] = $linksToDisplay[$key]['description'];
451 $linksToDisplay[$key]['description'] = $bookmark->getDescription();
452 }
453
454 $dayDate = DateTime::createFromFormat(Bookmark::LINK_DATE_FORMAT, $day.'_000000');
455 $data = array(
456 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
457 'linksToDisplay' => $linksToDisplay,
458 'day' => $dayDate->getTimestamp(),
459 'dayDate' => $dayDate,
460 'previousday' => $previousday,
461 'nextday' => $nextday,
462 );
463
464 /* Hook is called before column construction so that plugins don't have
465 to deal with columns. */
466 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
467
468 /* We need to spread the articles on 3 columns.
469 I did not want to use a JavaScript lib like http://masonry.desandro.com/
470 so I manually spread entries with a simple method: I roughly evaluate the
471 height of a div according to title and description length.
472 */
473 $columns = array(array(), array(), array()); // Entries to display, for each column.
474 $fill = array(0, 0, 0); // Rough estimate of columns fill.
475 foreach ($data['linksToDisplay'] as $key => $bookmark) {
476 // Roughly estimate length of entry (by counting characters)
477 // Title: 30 chars = 1 line. 1 line is 30 pixels height.
478 // Description: 836 characters gives roughly 342 pixel height.
479 // This is not perfect, but it's usually OK.
480 $length = strlen($bookmark['title']) + (342 * strlen($bookmark['description'])) / 836;
481 if (! empty($bookmark['thumbnail'])) {
482 $length += 100; // 1 thumbnails roughly takes 100 pixels height.
483 }
484 // Then put in column which is the less filled:
485 $smallest = min($fill); // find smallest value in array.
486 $index = array_search($smallest, $fill); // find index of this smallest value.
487 array_push($columns[$index], $bookmark); // Put entry in this column.
488 $fill[$index] += $length;
489 }
490
491 $data['cols'] = $columns;
492
493 foreach ($data as $key => $value) {
494 $pageBuilder->assign($key, $value);
495 }
496
497 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
498 $pageBuilder->renderPage('daily');
499 exit;
500 }
501
502 /**
503 * Renders the linklist
504 *
505 * @param pageBuilder $PAGE pageBuilder instance.
506 * @param BookmarkServiceInterface $linkDb instance.
507 * @param ConfigManager $conf Configuration Manager instance.
508 * @param PluginManager $pluginManager Plugin Manager instance.
509 */
510 function showLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager)
511 {
512 buildLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager);
513 $PAGE->renderPage('linklist');
514 }
515
516 /**
517 * Render HTML page (according to URL parameters and user rights)
518 *
519 * @param ConfigManager $conf Configuration Manager instance.
520 * @param PluginManager $pluginManager Plugin Manager instance,
521 * @param BookmarkServiceInterface $bookmarkService
522 * @param History $history instance
523 * @param SessionManager $sessionManager SessionManager instance
524 * @param LoginManager $loginManager LoginManager instance
525 */
526 function renderPage($conf, $pluginManager, $bookmarkService, $history, $sessionManager, $loginManager)
527 {
528 $updater = new Updater(
529 UpdaterUtils::read_updates_file($conf->get('resource.updates')),
530 $bookmarkService,
531 $conf,
532 $loginManager->isLoggedIn()
533 );
534 try {
535 $newUpdates = $updater->update();
536 if (! empty($newUpdates)) {
537 UpdaterUtils::write_updates_file(
538 $conf->get('resource.updates'),
539 $updater->getDoneUpdates()
540 );
541 }
542 } catch (Exception $e) {
543 die($e->getMessage());
544 }
545
546 $PAGE = new PageBuilder($conf, $_SESSION, $bookmarkService, $sessionManager->generateToken(), $loginManager->isLoggedIn());
547 $PAGE->assign('linkcount', $bookmarkService->count(BookmarkFilter::$ALL));
548 $PAGE->assign('privateLinkcount', $bookmarkService->count(BookmarkFilter::$PRIVATE));
549 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
550
551 // Determine which page will be rendered.
552 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
553 $targetPage = Router::findPage($query, $_GET, $loginManager->isLoggedIn());
554
555 if (// if the user isn't logged in
556 !$loginManager->isLoggedIn() &&
557 // and Shaarli doesn't have public content...
558 $conf->get('privacy.hide_public_links') &&
559 // and is configured to enforce the login
560 $conf->get('privacy.force_login') &&
561 // and the current page isn't already the login page
562 $targetPage !== Router::$PAGE_LOGIN &&
563 // and the user is not requesting a feed (which would lead to a different content-type as expected)
564 $targetPage !== Router::$PAGE_FEED_ATOM &&
565 $targetPage !== Router::$PAGE_FEED_RSS
566 ) {
567 // force current page to be the login page
568 $targetPage = Router::$PAGE_LOGIN;
569 }
570
571 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
572 // Then assign generated data to RainTPL.
573 $common_hooks = array(
574 'includes',
575 'header',
576 'footer',
577 );
578
579 foreach ($common_hooks as $name) {
580 $plugin_data = array();
581 $pluginManager->executeHooks(
582 'render_' . $name,
583 $plugin_data,
584 array(
585 'target' => $targetPage,
586 'loggedin' => $loginManager->isLoggedIn()
587 )
588 );
589 $PAGE->assign('plugins_' . $name, $plugin_data);
590 }
591
592 // -------- Display login form.
593 if ($targetPage == Router::$PAGE_LOGIN) {
594 if ($conf->get('security.open_shaarli')) {
595 header('Location: ?');
596 exit;
597 } // No need to login for open Shaarli
598 if (isset($_GET['username'])) {
599 $PAGE->assign('username', escape($_GET['username']));
600 }
601 $PAGE->assign('returnurl', (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
602 // add default state of the 'remember me' checkbox
603 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
604 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
605 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
606 $PAGE->renderPage('loginform');
607 exit;
608 }
609 // -------- User wants to logout.
610 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) {
611 invalidateCaches($conf->get('resource.page_cache'));
612 $sessionManager->logout();
613 setcookie(LoginManager::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH);
614 header('Location: ?');
615 exit;
616 }
617
618 // -------- Picture wall
619 if ($targetPage == Router::$PAGE_PICWALL) {
620 $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
621 if (! $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) === Thumbnailer::MODE_NONE) {
622 $PAGE->assign('linksToDisplay', []);
623 $PAGE->renderPage('picwall');
624 exit;
625 }
626
627 // Optionally filter the results:
628 $links = $bookmarkService->search($_GET);
629 $linksToDisplay = [];
630
631 // Get only bookmarks which have a thumbnail.
632 // Note: we do not retrieve thumbnails here, the request is too heavy.
633 $factory = new FormatterFactory($conf);
634 $formatter = $factory->getFormatter();
635 foreach ($links as $key => $link) {
636 if ($link->getThumbnail() !== false) {
637 $linksToDisplay[] = $formatter->format($link);
638 }
639 }
640
641 $data = [
642 'linksToDisplay' => $linksToDisplay,
643 ];
644 $pluginManager->executeHooks('render_picwall', $data, ['loggedin' => $loginManager->isLoggedIn()]);
645
646 foreach ($data as $key => $value) {
647 $PAGE->assign($key, $value);
648 }
649
650 $PAGE->renderPage('picwall');
651 exit;
652 }
653
654 // -------- Tag cloud
655 if ($targetPage == Router::$PAGE_TAGCLOUD) {
656 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
657 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
658 $tags = $bookmarkService->bookmarksCountPerTag($filteringTags, $visibility);
659
660 // We sort tags alphabetically, then choose a font size according to count.
661 // First, find max value.
662 $maxcount = 0;
663 foreach ($tags as $value) {
664 $maxcount = max($maxcount, $value);
665 }
666
667 alphabetical_sort($tags, false, true);
668
669 $tagList = array();
670 foreach ($tags as $key => $value) {
671 if (in_array($key, $filteringTags)) {
672 continue;
673 }
674 // Tag font size scaling:
675 // default 15 and 30 logarithm bases affect scaling,
676 // 22 and 6 are arbitrary font sizes for max and min sizes.
677 $size = log($value, 15) / log($maxcount, 30) * 2.2 + 0.8;
678 $tagList[$key] = array(
679 'count' => $value,
680 'size' => number_format($size, 2, '.', ''),
681 );
682 }
683
684 $searchTags = implode(' ', escape($filteringTags));
685 $data = array(
686 'search_tags' => $searchTags,
687 'tags' => $tagList,
688 );
689 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
690
691 foreach ($data as $key => $value) {
692 $PAGE->assign($key, $value);
693 }
694
695 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
696 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
697 $PAGE->renderPage('tag.cloud');
698 exit;
699 }
700
701 // -------- Tag list
702 if ($targetPage == Router::$PAGE_TAGLIST) {
703 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
704 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
705 $tags = $bookmarkService->bookmarksCountPerTag($filteringTags, $visibility);
706 foreach ($filteringTags as $tag) {
707 if (array_key_exists($tag, $tags)) {
708 unset($tags[$tag]);
709 }
710 }
711
712 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
713 alphabetical_sort($tags, false, true);
714 }
715
716 $searchTags = implode(' ', escape($filteringTags));
717 $data = [
718 'search_tags' => $searchTags,
719 'tags' => $tags,
720 ];
721 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
722
723 foreach ($data as $key => $value) {
724 $PAGE->assign($key, $value);
725 }
726
727 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
728 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
729 $PAGE->renderPage('tag.list');
730 exit;
731 }
732
733 // Daily page.
734 if ($targetPage == Router::$PAGE_DAILY) {
735 showDaily($PAGE, $bookmarkService, $conf, $pluginManager, $loginManager);
736 }
737
738 // ATOM and RSS feed.
739 if ($targetPage == Router::$PAGE_FEED_ATOM || $targetPage == Router::$PAGE_FEED_RSS) {
740 $feedType = $targetPage == Router::$PAGE_FEED_RSS ? FeedBuilder::$FEED_RSS : FeedBuilder::$FEED_ATOM;
741 header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
742
743 // Cache system
744 $query = $_SERVER['QUERY_STRING'];
745 $cache = new CachedPage(
746 $conf->get('resource.page_cache'),
747 page_url($_SERVER),
748 startsWith($query, 'do='. $targetPage) && !$loginManager->isLoggedIn()
749 );
750 $cached = $cache->cachedVersion();
751 if (!empty($cached)) {
752 echo $cached;
753 exit;
754 }
755
756 $factory = new FormatterFactory($conf);
757 // Generate data.
758 $feedGenerator = new FeedBuilder(
759 $bookmarkService,
760 $factory->getFormatter(),
761 $feedType,
762 $_SERVER,
763 $_GET,
764 $loginManager->isLoggedIn()
765 );
766 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0)));
767 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
768 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
769 $data = $feedGenerator->buildData();
770
771 // Process plugin hook.
772 $pluginManager->executeHooks('render_feed', $data, array(
773 'loggedin' => $loginManager->isLoggedIn(),
774 'target' => $targetPage,
775 ));
776
777 // Render the template.
778 $PAGE->assignAll($data);
779 $PAGE->renderPage('feed.'. $feedType);
780 $cache->cache(ob_get_contents());
781 ob_end_flush();
782 exit;
783 }
784
785 // Display opensearch plugin (XML)
786 if ($targetPage == Router::$PAGE_OPENSEARCH) {
787 header('Content-Type: application/xml; charset=utf-8');
788 $PAGE->assign('serverurl', index_url($_SERVER));
789 $PAGE->renderPage('opensearch');
790 exit;
791 }
792
793 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
794 if (isset($_GET['addtag'])) {
795 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
796 if (empty($_SERVER['HTTP_REFERER'])) {
797 // In case browser does not send HTTP_REFERER
798 header('Location: ?searchtags='.urlencode($_GET['addtag']));
799 exit;
800 }
801 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
802
803 // Prevent redirection loop
804 if (isset($params['addtag'])) {
805 unset($params['addtag']);
806 }
807
808 // Check if this tag is already in the search query and ignore it if it is.
809 // Each tag is always separated by a space
810 if (isset($params['searchtags'])) {
811 $current_tags = explode(' ', $params['searchtags']);
812 } else {
813 $current_tags = array();
814 }
815 $addtag = true;
816 foreach ($current_tags as $value) {
817 if ($value === $_GET['addtag']) {
818 $addtag = false;
819 break;
820 }
821 }
822 // Append the tag if necessary
823 if (empty($params['searchtags'])) {
824 $params['searchtags'] = trim($_GET['addtag']);
825 } elseif ($addtag) {
826 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
827 }
828
829 // We also remove page (keeping the same page has no sense, since the
830 // results are different)
831 unset($params['page']);
832
833 header('Location: ?'.http_build_query($params));
834 exit;
835 }
836
837 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
838 if (isset($_GET['removetag'])) {
839 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
840 if (empty($_SERVER['HTTP_REFERER'])) {
841 header('Location: ?');
842 exit;
843 }
844
845 // In case browser does not send HTTP_REFERER
846 parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
847
848 // Prevent redirection loop
849 if (isset($params['removetag'])) {
850 unset($params['removetag']);
851 }
852
853 if (isset($params['searchtags'])) {
854 $tags = explode(' ', $params['searchtags']);
855 // Remove value from array $tags.
856 $tags = array_diff($tags, array($_GET['removetag']));
857 $params['searchtags'] = implode(' ', $tags);
858
859 if (empty($params['searchtags'])) {
860 unset($params['searchtags']);
861 }
862
863 // We also remove page (keeping the same page has no sense, since
864 // the results are different)
865 unset($params['page']);
866 }
867 header('Location: ?'.http_build_query($params));
868 exit;
869 }
870
871 // -------- User wants to change the number of bookmarks per page (linksperpage=...)
872 if (isset($_GET['linksperpage'])) {
873 if (is_numeric($_GET['linksperpage'])) {
874 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
875 }
876
877 if (! empty($_SERVER['HTTP_REFERER'])) {
878 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
879 } else {
880 $location = '?';
881 }
882 header('Location: '. $location);
883 exit;
884 }
885
886 // -------- User wants to see only private bookmarks (toggle)
887 if (isset($_GET['visibility'])) {
888 if ($_GET['visibility'] === 'private') {
889 // Visibility not set or not already private, set private, otherwise reset it
890 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
891 // See only private bookmarks
892 $_SESSION['visibility'] = 'private';
893 } else {
894 unset($_SESSION['visibility']);
895 }
896 } elseif ($_GET['visibility'] === 'public') {
897 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
898 // See only public bookmarks
899 $_SESSION['visibility'] = 'public';
900 } else {
901 unset($_SESSION['visibility']);
902 }
903 }
904
905 if (! empty($_SERVER['HTTP_REFERER'])) {
906 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
907 } else {
908 $location = '?';
909 }
910 header('Location: '. $location);
911 exit;
912 }
913
914 // -------- User wants to see only untagged bookmarks (toggle)
915 if (isset($_GET['untaggedonly'])) {
916 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
917
918 if (! empty($_SERVER['HTTP_REFERER'])) {
919 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
920 } else {
921 $location = '?';
922 }
923 header('Location: '. $location);
924 exit;
925 }
926
927 // -------- Handle other actions allowed for non-logged in users:
928 if (!$loginManager->isLoggedIn()) {
929 // User tries to post new link but is not logged in:
930 // Show login screen, then redirect to ?post=...
931 if (isset($_GET['post'])) {
932 header( // Redirect to login page, then back to post link.
933 'Location: ?do=login&post='.urlencode($_GET['post']).
934 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
935 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
936 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
937 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
938 );
939 exit;
940 }
941
942 showLinkList($PAGE, $bookmarkService, $conf, $pluginManager, $loginManager);
943 if (isset($_GET['edit_link'])) {
944 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
945 exit;
946 }
947
948 exit; // Never remove this one! All operations below are reserved for logged in user.
949 }
950
951 // -------- All other functions are reserved for the registered user:
952
953 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
954 if ($targetPage == Router::$PAGE_TOOLS) {
955 $data = [
956 'pageabsaddr' => index_url($_SERVER),
957 'sslenabled' => is_https($_SERVER),
958 ];
959 $pluginManager->executeHooks('render_tools', $data);
960
961 foreach ($data as $key => $value) {
962 $PAGE->assign($key, $value);
963 }
964
965 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
966 $PAGE->renderPage('tools');
967 exit;
968 }
969
970 // -------- User wants to change his/her password.
971 if ($targetPage == Router::$PAGE_CHANGEPASSWORD) {
972 if ($conf->get('security.open_shaarli')) {
973 die(t('You are not supposed to change a password on an Open Shaarli.'));
974 }
975
976 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) {
977 if (!$sessionManager->checkToken($_POST['token'])) {
978 die(t('Wrong token.')); // Go away!
979 }
980
981 // Make sure old password is correct.
982 $oldhash = sha1(
983 $_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt')
984 );
985 if ($oldhash != $conf->get('credentials.hash')) {
986 echo '<script>alert("'
987 . t('The old password is not correct.')
988 .'");document.location=\'?do=changepasswd\';</script>';
989 exit;
990 }
991 // Save new password
992 // Salt renders rainbow-tables attacks useless.
993 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
994 $conf->set(
995 'credentials.hash',
996 sha1(
997 $_POST['setpassword']
998 . $conf->get('credentials.login')
999 . $conf->get('credentials.salt')
1000 )
1001 );
1002 try {
1003 $conf->write($loginManager->isLoggedIn());
1004 } catch (Exception $e) {
1005 error_log(
1006 'ERROR while writing config file after changing password.' . PHP_EOL .
1007 $e->getMessage()
1008 );
1009
1010 // TODO: do not handle exceptions/errors in JS.
1011 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
1012 exit;
1013 }
1014 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
1015 exit;
1016 } else {
1017 // show the change password form.
1018 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
1019 $PAGE->renderPage('changepassword');
1020 exit;
1021 }
1022 }
1023
1024 // -------- User wants to change configuration
1025 if ($targetPage == Router::$PAGE_CONFIGURE) {
1026 if (!empty($_POST['title'])) {
1027 if (!$sessionManager->checkToken($_POST['token'])) {
1028 die(t('Wrong token.')); // Go away!
1029 }
1030 $tz = 'UTC';
1031 if (!empty($_POST['continent']) && !empty($_POST['city'])
1032 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1033 ) {
1034 $tz = $_POST['continent'] . '/' . $_POST['city'];
1035 }
1036 $conf->set('general.timezone', $tz);
1037 $conf->set('general.title', escape($_POST['title']));
1038 $conf->set('general.header_link', escape($_POST['titleLink']));
1039 $conf->set('general.retrieve_description', !empty($_POST['retrieveDescription']));
1040 $conf->set('resource.theme', escape($_POST['theme']));
1041 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
1042 $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
1043 $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
1044 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1045 $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
1046 $conf->set('api.enabled', !empty($_POST['enableApi']));
1047 $conf->set('api.secret', escape($_POST['apiSecret']));
1048 $conf->set('formatter', escape($_POST['formatter']));
1049
1050 if (! empty($_POST['language'])) {
1051 $conf->set('translation.language', escape($_POST['language']));
1052 }
1053
1054 $thumbnailsMode = extension_loaded('gd') ? $_POST['enableThumbnails'] : Thumbnailer::MODE_NONE;
1055 if ($thumbnailsMode !== Thumbnailer::MODE_NONE
1056 && $thumbnailsMode !== $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE)
1057 ) {
1058 $_SESSION['warnings'][] = t(
1059 'You have enabled or changed thumbnails mode. '
1060 .'<a href="?do=thumbs_update">Please synchronize them</a>.'
1061 );
1062 }
1063 $conf->set('thumbnails.mode', $thumbnailsMode);
1064
1065 try {
1066 $conf->write($loginManager->isLoggedIn());
1067 $history->updateSettings();
1068 invalidateCaches($conf->get('resource.page_cache'));
1069 } catch (Exception $e) {
1070 error_log(
1071 'ERROR while writing config file after configuration update.' . PHP_EOL .
1072 $e->getMessage()
1073 );
1074
1075 // TODO: do not handle exceptions/errors in JS.
1076 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
1077 exit;
1078 }
1079 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
1080 exit;
1081 } else {
1082 // Show the configuration form.
1083 $PAGE->assign('title', $conf->get('general.title'));
1084 $PAGE->assign('theme', $conf->get('resource.theme'));
1085 $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl')));
1086 $PAGE->assign('formatter_available', ['default', 'markdown']);
1087 list($continents, $cities) = generateTimeZoneData(
1088 timezone_identifiers_list(),
1089 $conf->get('general.timezone')
1090 );
1091 $PAGE->assign('continents', $continents);
1092 $PAGE->assign('cities', $cities);
1093 $PAGE->assign('retrieve_description', $conf->get('general.retrieve_description'));
1094 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
1095 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
1096 $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
1097 $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
1098 $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
1099 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1100 $PAGE->assign('api_secret', $conf->get('api.secret'));
1101 $PAGE->assign('languages', Languages::getAvailableLanguages());
1102 $PAGE->assign('gd_enabled', extension_loaded('gd'));
1103 $PAGE->assign('thumbnails_mode', $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE));
1104 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
1105 $PAGE->renderPage('configure');
1106 exit;
1107 }
1108 }
1109
1110 // -------- User wants to rename a tag or delete it
1111 if ($targetPage == Router::$PAGE_CHANGETAG) {
1112 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
1113 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
1114 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
1115 $PAGE->renderPage('changetag');
1116 exit;
1117 }
1118
1119 if (!$sessionManager->checkToken($_POST['token'])) {
1120 die(t('Wrong token.'));
1121 }
1122
1123 $toTag = isset($_POST['totag']) ? escape($_POST['totag']) : null;
1124 $fromTag = escape($_POST['fromtag']);
1125 $count = 0;
1126 $bookmarks = $bookmarkService->search(['searchtags' => $fromTag], BookmarkFilter::$ALL, true);
1127 foreach ($bookmarks as $bookmark) {
1128 if ($toTag) {
1129 $bookmark->renameTag($fromTag, $toTag);
1130 } else {
1131 $bookmark->deleteTag($fromTag);
1132 }
1133 $bookmarkService->set($bookmark, false);
1134 $history->updateLink($bookmark);
1135 $count++;
1136 }
1137 $bookmarkService->save();
1138 $delete = empty($_POST['totag']);
1139 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
1140 $alert = $delete
1141 ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d bookmarks.', $count), $count)
1142 : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d bookmarks.', $count), $count);
1143 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1144 exit;
1145 }
1146
1147 // -------- User wants to add a link without using the bookmarklet: Show form.
1148 if ($targetPage == Router::$PAGE_ADDLINK) {
1149 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
1150 $PAGE->renderPage('addlink');
1151 exit;
1152 }
1153
1154 // -------- User clicked the "Save" button when editing a link: Save link to database.
1155 if (isset($_POST['save_edit'])) {
1156 // Go away!
1157 if (! $sessionManager->checkToken($_POST['token'])) {
1158 die(t('Wrong token.'));
1159 }
1160
1161 // lf_id should only be present if the link exists.
1162 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : null;
1163 if ($id && $bookmarkService->exists($id)) {
1164 // Edit
1165 $bookmark = $bookmarkService->get($id);
1166 } else {
1167 // New link
1168 $bookmark = new Bookmark();
1169 }
1170
1171 $bookmark->setTitle($_POST['lf_title']);
1172 $bookmark->setDescription($_POST['lf_description']);
1173 $bookmark->setUrl($_POST['lf_url'], $conf->get('security.allowed_protocols'));
1174 $bookmark->setPrivate(isset($_POST['lf_private']));
1175 $bookmark->setTagsString($_POST['lf_tags']);
1176
1177 if ($conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE
1178 && ! $bookmark->isNote()
1179 ) {
1180 $thumbnailer = new Thumbnailer($conf);
1181 $bookmark->setThumbnail($thumbnailer->get($bookmark->getUrl()));
1182 }
1183 $bookmarkService->addOrSet($bookmark, false);
1184
1185 // To preserve backward compatibility with 3rd parties, plugins still use arrays
1186 $factory = new FormatterFactory($conf);
1187 $formatter = $factory->getFormatter('raw');
1188 $data = $formatter->format($bookmark);
1189 $pluginManager->executeHooks('save_link', $data);
1190
1191 $bookmark->fromArray($data);
1192 $bookmarkService->set($bookmark);
1193
1194 // If we are called from the bookmarklet, we must close the popup:
1195 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1196 echo '<script>self.close();</script>';
1197 exit;
1198 }
1199
1200 $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?';
1201 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
1202 // Scroll to the link which has been edited.
1203 $location .= '#' . $bookmark->getShortUrl();
1204 // After saving the link, redirect to the page the user was on.
1205 header('Location: '. $location);
1206 exit;
1207 }
1208
1209 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
1210 if ($targetPage == Router::$PAGE_DELETELINK) {
1211 if (! $sessionManager->checkToken($_GET['token'])) {
1212 die(t('Wrong token.'));
1213 }
1214
1215 $ids = trim($_GET['lf_linkdate']);
1216 if (strpos($ids, ' ') !== false) {
1217 // multiple, space-separated ids provided
1218 $ids = array_values(array_filter(
1219 preg_split('/\s+/', escape($ids)),
1220 function ($item) {
1221 return $item !== '';
1222 }
1223 ));
1224 } else {
1225 // only a single id provided
1226 $shortUrl = $bookmarkService->get($ids)->getShortUrl();
1227 $ids = [$ids];
1228 }
1229 // assert at least one id is given
1230 if (!count($ids)) {
1231 die('no id provided');
1232 }
1233 $factory = new FormatterFactory($conf);
1234 $formatter = $factory->getFormatter('raw');
1235 foreach ($ids as $id) {
1236 $id = (int) escape($id);
1237 $bookmark = $bookmarkService->get($id);
1238 $data = $formatter->format($bookmark);
1239 $pluginManager->executeHooks('delete_link', $data);
1240 $bookmarkService->remove($bookmark, false);
1241 }
1242 $bookmarkService->save();
1243
1244 // If we are called from the bookmarklet, we must close the popup:
1245 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1246 echo '<script>self.close();</script>';
1247 exit;
1248 }
1249
1250 $location = '?';
1251 if (isset($_SERVER['HTTP_REFERER'])) {
1252 // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
1253 $location = generateLocation(
1254 $_SERVER['HTTP_REFERER'],
1255 $_SERVER['HTTP_HOST'],
1256 ['delete_link', 'edit_link', ! empty($shortUrl) ? $shortUrl : null]
1257 );
1258 }
1259
1260 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1261 exit;
1262 }
1263
1264 // -------- User clicked either "Set public" or "Set private" bulk operation
1265 if ($targetPage == Router::$PAGE_CHANGE_VISIBILITY) {
1266 if (! $sessionManager->checkToken($_GET['token'])) {
1267 die(t('Wrong token.'));
1268 }
1269
1270 $ids = trim($_GET['ids']);
1271 if (strpos($ids, ' ') !== false) {
1272 // multiple, space-separated ids provided
1273 $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
1274 } else {
1275 // only a single id provided
1276 $ids = [$ids];
1277 }
1278
1279 // assert at least one id is given
1280 if (!count($ids)) {
1281 die('no id provided');
1282 }
1283 // assert that the visibility is valid
1284 if (!isset($_GET['newVisibility']) || !in_array($_GET['newVisibility'], ['public', 'private'])) {
1285 die('invalid visibility');
1286 } else {
1287 $private = $_GET['newVisibility'] === 'private';
1288 }
1289 $factory = new FormatterFactory($conf);
1290 $formatter = $factory->getFormatter('raw');
1291 foreach ($ids as $id) {
1292 $id = (int) escape($id);
1293 $bookmark = $bookmarkService->get($id);
1294 $bookmark->setPrivate($private);
1295
1296 // To preserve backward compatibility with 3rd parties, plugins still use arrays
1297 $data = $formatter->format($bookmark);
1298 $pluginManager->executeHooks('save_link', $data);
1299 $bookmark->fromArray($data);
1300
1301 $bookmarkService->set($bookmark);
1302 }
1303 $bookmarkService->save();
1304
1305 $location = '?';
1306 if (isset($_SERVER['HTTP_REFERER'])) {
1307 $location = generateLocation(
1308 $_SERVER['HTTP_REFERER'],
1309 $_SERVER['HTTP_HOST']
1310 );
1311 }
1312 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
1313 exit;
1314 }
1315
1316 // -------- User clicked the "EDIT" button on a link: Display link edit form.
1317 if (isset($_GET['edit_link'])) {
1318 $id = (int) escape($_GET['edit_link']);
1319 try {
1320 $link = $bookmarkService->get($id); // Read database
1321 } catch (BookmarkNotFoundException $e) {
1322 // Link not found in database.
1323 header('Location: ?');
1324 exit;
1325 }
1326
1327 $factory = new FormatterFactory($conf);
1328 $formatter = $factory->getFormatter('raw');
1329 $formattedLink = $formatter->format($link);
1330 $data = array(
1331 'link' => $formattedLink,
1332 'link_is_new' => false,
1333 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1334 'tags' => $bookmarkService->bookmarksCountPerTag(),
1335 );
1336 $pluginManager->executeHooks('render_editlink', $data);
1337
1338 foreach ($data as $key => $value) {
1339 $PAGE->assign($key, $value);
1340 }
1341
1342 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1343 $PAGE->renderPage('editlink');
1344 exit;
1345 }
1346
1347 // -------- User want to post a new link: Display link edit form.
1348 if (isset($_GET['post'])) {
1349 $url = cleanup_url($_GET['post']);
1350
1351 $link_is_new = false;
1352 // Check if URL is not already in database (in this case, we will edit the existing link)
1353 $bookmark = $bookmarkService->findByUrl($url);
1354 if (! $bookmark) {
1355 $link_is_new = true;
1356 // Get title if it was provided in URL (by the bookmarklet).
1357 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
1358 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
1359 $description = empty($_GET['description']) ? '' : escape($_GET['description']);
1360 $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
1361 $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
1362
1363 // If this is an HTTP(S) link, we try go get the page to extract
1364 // the title (otherwise we will to straight to the edit form.)
1365 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
1366 $retrieveDescription = $conf->get('general.retrieve_description');
1367 // Short timeout to keep the application responsive
1368 // The callback will fill $charset and $title with data from the downloaded page.
1369 get_http_response(
1370 $url,
1371 $conf->get('general.download_timeout', 30),
1372 $conf->get('general.download_max_size', 4194304),
1373 get_curl_download_callback($charset, $title, $description, $tags, $retrieveDescription)
1374 );
1375 if (! empty($title) && strtolower($charset) != 'utf-8') {
1376 $title = mb_convert_encoding($title, 'utf-8', $charset);
1377 }
1378 }
1379
1380 if ($url == '') {
1381 $title = $conf->get('general.default_note_title', t('Note: '));
1382 }
1383 $url = escape($url);
1384 $title = escape($title);
1385
1386 $link = [
1387 'title' => $title,
1388 'url' => $url,
1389 'description' => $description,
1390 'tags' => $tags,
1391 'private' => $private,
1392 ];
1393 } else {
1394 $factory = new FormatterFactory($conf);
1395 $formatter = $factory->getFormatter('raw');
1396 $link = $formatter->format($bookmark);
1397 }
1398
1399 $data = [
1400 'link' => $link,
1401 'link_is_new' => $link_is_new,
1402 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1403 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
1404 'tags' => $bookmarkService->bookmarksCountPerTag(),
1405 'default_private_links' => $conf->get('privacy.default_private_links', false),
1406 ];
1407 $pluginManager->executeHooks('render_editlink', $data);
1408
1409 foreach ($data as $key => $value) {
1410 $PAGE->assign($key, $value);
1411 }
1412
1413 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
1414 $PAGE->renderPage('editlink');
1415 exit;
1416 }
1417
1418 if ($targetPage == Router::$PAGE_PINLINK) {
1419 if (! isset($_GET['id']) || !$bookmarkService->exists($_GET['id'])) {
1420 // FIXME! Use a proper error system.
1421 $msg = t('Invalid link ID provided');
1422 echo '<script>alert("'. $msg .'");document.location=\''. index_url($_SERVER) .'\';</script>';
1423 exit;
1424 }
1425 if (! $sessionManager->checkToken($_GET['token'])) {
1426 die('Wrong token.');
1427 }
1428
1429 $link = $bookmarkService->get($_GET['id']);
1430 $link->setSticky(! $link->isSticky());
1431 $bookmarkService->set($link);
1432 header('Location: '.index_url($_SERVER));
1433 exit;
1434 }
1435
1436 if ($targetPage == Router::$PAGE_EXPORT) {
1437 // Export bookmarks as a Netscape Bookmarks file
1438
1439 if (empty($_GET['selection'])) {
1440 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
1441 $PAGE->renderPage('export');
1442 exit;
1443 }
1444
1445 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1446 $selection = $_GET['selection'];
1447 if (isset($_GET['prepend_note_url'])) {
1448 $prependNoteUrl = $_GET['prepend_note_url'];
1449 } else {
1450 $prependNoteUrl = false;
1451 }
1452
1453 try {
1454 $factory = new FormatterFactory($conf);
1455 $formatter = $factory->getFormatter('raw');
1456 $PAGE->assign(
1457 'links',
1458 NetscapeBookmarkUtils::filterAndFormat(
1459 $bookmarkService,
1460 $formatter,
1461 $selection,
1462 $prependNoteUrl,
1463 index_url($_SERVER)
1464 )
1465 );
1466 } catch (Exception $exc) {
1467 header('Content-Type: text/plain; charset=utf-8');
1468 echo $exc->getMessage();
1469 exit;
1470 }
1471 $now = new DateTime();
1472 header('Content-Type: text/html; charset=utf-8');
1473 header(
1474 'Content-disposition: attachment; filename=bookmarks_'
1475 .$selection.'_'.$now->format(Bookmark::LINK_DATE_FORMAT).'.html'
1476 );
1477 $PAGE->assign('date', $now->format(DateTime::RFC822));
1478 $PAGE->assign('eol', PHP_EOL);
1479 $PAGE->assign('selection', $selection);
1480 $PAGE->renderPage('export.bookmarks');
1481 exit;
1482 }
1483
1484 if ($targetPage == Router::$PAGE_IMPORT) {
1485 // Upload a Netscape bookmark dump to import its contents
1486
1487 if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
1488 // Show import dialog
1489 $PAGE->assign(
1490 'maxfilesize',
1491 get_max_upload_size(
1492 ini_get('post_max_size'),
1493 ini_get('upload_max_filesize'),
1494 false
1495 )
1496 );
1497 $PAGE->assign(
1498 'maxfilesizeHuman',
1499 get_max_upload_size(
1500 ini_get('post_max_size'),
1501 ini_get('upload_max_filesize'),
1502 true
1503 )
1504 );
1505 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
1506 $PAGE->renderPage('import');
1507 exit;
1508 }
1509
1510 // Import bookmarks from an uploaded file
1511 if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
1512 // The file is too big or some form field may be missing.
1513 $msg = sprintf(
1514 t(
1515 'The file you are trying to upload is probably bigger than what this webserver can accept'
1516 .' (%s). Please upload in smaller chunks.'
1517 ),
1518 get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
1519 );
1520 echo '<script>alert("'. $msg .'");document.location=\'?do='.Router::$PAGE_IMPORT .'\';</script>';
1521 exit;
1522 }
1523 if (! $sessionManager->checkToken($_POST['token'])) {
1524 die('Wrong token.');
1525 }
1526 $status = NetscapeBookmarkUtils::import(
1527 $_POST,
1528 $_FILES,
1529 $bookmarkService,
1530 $conf,
1531 $history
1532 );
1533 echo '<script>alert("'.$status.'");document.location=\'?do='
1534 .Router::$PAGE_IMPORT .'\';</script>';
1535 exit;
1536 }
1537
1538 // Plugin administration page
1539 if ($targetPage == Router::$PAGE_PLUGINSADMIN) {
1540 $pluginMeta = $pluginManager->getPluginsMeta();
1541
1542 // Split plugins into 2 arrays: ordered enabled plugins and disabled.
1543 $enabledPlugins = array_filter($pluginMeta, function ($v) {
1544 return $v['order'] !== false;
1545 });
1546 // Load parameters.
1547 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
1548 uasort(
1549 $enabledPlugins,
1550 function ($a, $b) {
1551 return $a['order'] - $b['order'];
1552 }
1553 );
1554 $disabledPlugins = array_filter($pluginMeta, function ($v) {
1555 return $v['order'] === false;
1556 });
1557
1558 $PAGE->assign('enabledPlugins', $enabledPlugins);
1559 $PAGE->assign('disabledPlugins', $disabledPlugins);
1560 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
1561 $PAGE->renderPage('pluginsadmin');
1562 exit;
1563 }
1564
1565 // Plugin administration form action
1566 if ($targetPage == Router::$PAGE_SAVE_PLUGINSADMIN) {
1567 try {
1568 if (isset($_POST['parameters_form'])) {
1569 $pluginManager->executeHooks('save_plugin_parameters', $_POST);
1570 unset($_POST['parameters_form']);
1571 foreach ($_POST as $param => $value) {
1572 $conf->set('plugins.'. $param, escape($value));
1573 }
1574 } else {
1575 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
1576 }
1577 $conf->write($loginManager->isLoggedIn());
1578 $history->updateSettings();
1579 } catch (Exception $e) {
1580 error_log(
1581 'ERROR while saving plugin configuration:.' . PHP_EOL .
1582 $e->getMessage()
1583 );
1584
1585 // TODO: do not handle exceptions/errors in JS.
1586 echo '<script>alert("'
1587 . $e->getMessage()
1588 .'");document.location=\'?do='
1589 . Router::$PAGE_PLUGINSADMIN
1590 .'\';</script>';
1591 exit;
1592 }
1593 header('Location: ?do='. Router::$PAGE_PLUGINSADMIN);
1594 exit;
1595 }
1596
1597 // Get a fresh token
1598 if ($targetPage == Router::$GET_TOKEN) {
1599 header('Content-Type:text/plain');
1600 echo $sessionManager->generateToken();
1601 exit;
1602 }
1603
1604 // -------- Thumbnails Update
1605 if ($targetPage == Router::$PAGE_THUMBS_UPDATE) {
1606 $ids = [];
1607 foreach ($bookmarkService->search() as $bookmark) {
1608 // A note or not HTTP(S)
1609 if ($bookmark->isNote() || ! startsWith(strtolower($bookmark->getUrl()), 'http')) {
1610 continue;
1611 }
1612 $ids[] = $bookmark->getId();
1613 }
1614 $PAGE->assign('ids', $ids);
1615 $PAGE->assign('pagetitle', t('Thumbnails update') .' - '. $conf->get('general.title', 'Shaarli'));
1616 $PAGE->renderPage('thumbnails');
1617 exit;
1618 }
1619
1620 // -------- Single Thumbnail Update
1621 if ($targetPage == Router::$AJAX_THUMB_UPDATE) {
1622 if (! isset($_POST['id']) || ! ctype_digit($_POST['id'])) {
1623 http_response_code(400);
1624 exit;
1625 }
1626 $id = (int) $_POST['id'];
1627 if (! $bookmarkService->exists($id)) {
1628 http_response_code(404);
1629 exit;
1630 }
1631 $thumbnailer = new Thumbnailer($conf);
1632 $bookmark = $bookmarkService->get($id);
1633 $bookmark->setThumbnail($thumbnailer->get($bookmark->getUrl()));
1634 $bookmarkService->set($bookmark);
1635
1636 $factory = new FormatterFactory($conf);
1637 echo json_encode($factory->getFormatter('raw')->format($bookmark));
1638 exit;
1639 }
1640
1641 // -------- Otherwise, simply display search form and bookmarks:
1642 showLinkList($PAGE, $bookmarkService, $conf, $pluginManager, $loginManager);
1643 exit;
1644 }
1645
1646 /**
1647 * Template for the list of bookmarks (<div id="linklist">)
1648 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
1649 *
1650 * @param pageBuilder $PAGE pageBuilder instance.
1651 * @param BookmarkServiceInterface $linkDb LinkDB instance.
1652 * @param ConfigManager $conf Configuration Manager instance.
1653 * @param PluginManager $pluginManager Plugin Manager instance.
1654 * @param LoginManager $loginManager LoginManager instance
1655 */
1656 function buildLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager)
1657 {
1658 $factory = new FormatterFactory($conf);
1659 $formatter = $factory->getFormatter();
1660
1661 // Used in templates
1662 if (isset($_GET['searchtags'])) {
1663 if (! empty($_GET['searchtags'])) {
1664 $searchtags = escape(normalize_spaces($_GET['searchtags']));
1665 } else {
1666 $searchtags = false;
1667 }
1668 } else {
1669 $searchtags = '';
1670 }
1671 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
1672
1673 // Smallhash filter
1674 if (! empty($_SERVER['QUERY_STRING'])
1675 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
1676 try {
1677 $linksToDisplay = $linkDb->findByHash($_SERVER['QUERY_STRING']);
1678 } catch (BookmarkNotFoundException $e) {
1679 $PAGE->render404($e->getMessage());
1680 exit;
1681 }
1682 } else {
1683 // Filter bookmarks according search parameters.
1684 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : null;
1685 $request = [
1686 'searchtags' => $searchtags,
1687 'searchterm' => $searchterm,
1688 ];
1689 $linksToDisplay = $linkDb->search($request, $visibility, false, !empty($_SESSION['untaggedonly']));
1690 }
1691
1692 // ---- Handle paging.
1693 $keys = array();
1694 foreach ($linksToDisplay as $key => $value) {
1695 $keys[] = $key;
1696 }
1697
1698 // Select articles according to paging.
1699 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
1700 $pagecount = $pagecount == 0 ? 1 : $pagecount;
1701 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
1702 $page = $page < 1 ? 1 : $page;
1703 $page = $page > $pagecount ? $pagecount : $page;
1704 // Start index.
1705 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
1706 $end = $i + $_SESSION['LINKS_PER_PAGE'];
1707
1708 $thumbnailsEnabled = $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE;
1709 if ($thumbnailsEnabled) {
1710 $thumbnailer = new Thumbnailer($conf);
1711 }
1712
1713 $linkDisp = array();
1714 while ($i<$end && $i<count($keys)) {
1715 $link = $formatter->format($linksToDisplay[$keys[$i]]);
1716
1717 // Logged in, thumbnails enabled, not a note,
1718 // and (never retrieved yet or no valid cache file)
1719 if ($loginManager->isLoggedIn()
1720 && $thumbnailsEnabled
1721 && !$linksToDisplay[$keys[$i]]->isNote()
1722 && $linksToDisplay[$keys[$i]]->getThumbnail() !== false
1723 && ! is_file($linksToDisplay[$keys[$i]]->getThumbnail())
1724 ) {
1725 $linksToDisplay[$keys[$i]]->setThumbnail($thumbnailer->get($link['url']));
1726 $linkDb->set($linksToDisplay[$keys[$i]], false);
1727 $updateDB = true;
1728 $link['thumbnail'] = $linksToDisplay[$keys[$i]]->getThumbnail();
1729 }
1730
1731 // Check for both signs of a note: starting with ? and 7 chars long.
1732 // if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
1733 // $link['url'] = index_url($_SERVER) . $link['url'];
1734 // }
1735
1736 $linkDisp[$keys[$i]] = $link;
1737 $i++;
1738 }
1739
1740 // If we retrieved new thumbnails, we update the database.
1741 if (!empty($updateDB)) {
1742 $linkDb->save();
1743 }
1744
1745 // Compute paging navigation
1746 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
1747 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
1748 $previous_page_url = '';
1749 if ($i != count($keys)) {
1750 $previous_page_url = '?page=' . ($page+1) . $searchtermUrl . $searchtagsUrl;
1751 }
1752 $next_page_url='';
1753 if ($page>1) {
1754 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
1755 }
1756
1757 // Fill all template fields.
1758 $data = array(
1759 'previous_page_url' => $previous_page_url,
1760 'next_page_url' => $next_page_url,
1761 'page_current' => $page,
1762 'page_max' => $pagecount,
1763 'result_count' => count($linksToDisplay),
1764 'search_term' => $searchterm,
1765 'search_tags' => $searchtags,
1766 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
1767 'links' => $linkDisp,
1768 );
1769
1770 // If there is only a single link, we change on-the-fly the title of the page.
1771 if (count($linksToDisplay) == 1) {
1772 $data['pagetitle'] = $linksToDisplay[$keys[0]]->getTitle() .' - '. $conf->get('general.title');
1773 } elseif (! empty($searchterm) || ! empty($searchtags)) {
1774 $data['pagetitle'] = t('Search: ');
1775 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
1776 $bracketWrap = function ($tag) {
1777 return '['. $tag .']';
1778 };
1779 $data['pagetitle'] .= ! empty($searchtags)
1780 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
1781 : '';
1782 $data['pagetitle'] .= '- '. $conf->get('general.title');
1783 }
1784
1785 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
1786
1787 foreach ($data as $key => $value) {
1788 $PAGE->assign($key, $value);
1789 }
1790
1791 return;
1792 }
1793
1794 /**
1795 * Installation
1796 * This function should NEVER be called if the file data/config.php exists.
1797 *
1798 * @param ConfigManager $conf Configuration Manager instance.
1799 * @param SessionManager $sessionManager SessionManager instance
1800 * @param LoginManager $loginManager LoginManager instance
1801 */
1802 function install($conf, $sessionManager, $loginManager)
1803 {
1804 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
1805 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
1806 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
1807 }
1808
1809
1810 // This part makes sure sessions works correctly.
1811 // (Because on some hosts, session.save_path may not be set correctly,
1812 // or we may not have write access to it.)
1813 if (isset($_GET['test_session'])
1814 && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
1815 // Step 2: Check if data in session is correct.
1816 $msg = t(
1817 '<pre>Sessions do not seem to work correctly on your server.<br>'.
1818 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
1819 'and that you have write access to it.<br>'.
1820 'It currently points to %s.<br>'.
1821 'On some browsers, accessing your server via a hostname like \'localhost\' '.
1822 'or any custom hostname without a dot causes cookie storage to fail. '.
1823 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
1824 );
1825 $msg = sprintf($msg, session_save_path());
1826 echo $msg;
1827 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
1828 die;
1829 }
1830 if (!isset($_SESSION['session_tested'])) {
1831 // Step 1 : Try to store data in session and reload page.
1832 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
1833 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
1834 }
1835 if (isset($_GET['test_session'])) {
1836 // Step 3: Sessions are OK. Remove test parameter from URL.
1837 header('Location: '.index_url($_SERVER));
1838 }
1839
1840
1841 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
1842 $tz = 'UTC';
1843 if (!empty($_POST['continent']) && !empty($_POST['city'])
1844 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1845 ) {
1846 $tz = $_POST['continent'].'/'.$_POST['city'];
1847 }
1848 $conf->set('general.timezone', $tz);
1849 $login = $_POST['setlogin'];
1850 $conf->set('credentials.login', $login);
1851 $salt = sha1(uniqid('', true) .'_'. mt_rand());
1852 $conf->set('credentials.salt', $salt);
1853 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
1854 if (!empty($_POST['title'])) {
1855 $conf->set('general.title', escape($_POST['title']));
1856 } else {
1857 $conf->set('general.title', 'Shared bookmarks on '.escape(index_url($_SERVER)));
1858 }
1859 $conf->set('translation.language', escape($_POST['language']));
1860 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
1861 $conf->set('api.enabled', !empty($_POST['enableApi']));
1862 $conf->set(
1863 'api.secret',
1864 generate_api_secret(
1865 $conf->get('credentials.login'),
1866 $conf->get('credentials.salt')
1867 )
1868 );
1869 try {
1870 // Everything is ok, let's create config file.
1871 $conf->write($loginManager->isLoggedIn());
1872 } catch (Exception $e) {
1873 error_log(
1874 'ERROR while writing config file after installation.' . PHP_EOL .
1875 $e->getMessage()
1876 );
1877
1878 // TODO: do not handle exceptions/errors in JS.
1879 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1880 exit;
1881 }
1882
1883 $history = new History($conf->get('resource.history'));
1884 $bookmarkService = new BookmarkFileService($conf, $history, true);
1885 if ($bookmarkService->count() === 0) {
1886 $bookmarkService->initialize();
1887 }
1888
1889 echo '<script>alert('
1890 .'"Shaarli is now configured. '
1891 .'Please enter your login/password and start shaaring your bookmarks!"'
1892 .');document.location=\'?do=login\';</script>';
1893 exit;
1894 }
1895
1896 $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
1897 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1898 $PAGE->assign('continents', $continents);
1899 $PAGE->assign('cities', $cities);
1900 $PAGE->assign('languages', Languages::getAvailableLanguages());
1901 $PAGE->renderPage('install');
1902 exit;
1903 }
1904
1905 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
1906 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
1907 }
1908
1909 try {
1910 $history = new History($conf->get('resource.history'));
1911 } catch (Exception $e) {
1912 die($e->getMessage());
1913 }
1914
1915 $linkDb = new BookmarkFileService($conf, $history, $loginManager->isLoggedIn());
1916
1917 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) {
1918 showDailyRSS($linkDb, $conf, $loginManager);
1919 exit;
1920 }
1921
1922 $container = new \Slim\Container();
1923 $container['conf'] = $conf;
1924 $container['plugins'] = $pluginManager;
1925 $container['history'] = $history;
1926 $app = new \Slim\App($container);
1927
1928 // REST API routes
1929 $app->group('/api/v1', function () {
1930 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
1931 $this->get('/bookmarks', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
1932 $this->get('/bookmarks/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
1933 $this->post('/bookmarks', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
1934 $this->put('/bookmarks/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
1935 $this->delete('/bookmarks/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
1936
1937 $this->get('/tags', '\Shaarli\Api\Controllers\Tags:getTags')->setName('getTags');
1938 $this->get('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:getTag')->setName('getTag');
1939 $this->put('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:putTag')->setName('putTag');
1940 $this->delete('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:deleteTag')->setName('deleteTag');
1941
1942 $this->get('/history', '\Shaarli\Api\Controllers\HistoryController:getHistory')->setName('getHistory');
1943 })->add('\Shaarli\Api\ApiMiddleware');
1944
1945 $response = $app->run(true);
1946
1947 // Hack to make Slim and Shaarli router work together:
1948 // If a Slim route isn't found and NOT API call, we call renderPage().
1949 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
1950 // We use UTF-8 for proper international characters handling.
1951 header('Content-Type: text/html; charset=utf-8');
1952 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
1953 } else {
1954 $response = $response
1955 ->withHeader('Access-Control-Allow-Origin', '*')
1956 ->withHeader(
1957 'Access-Control-Allow-Headers',
1958 'X-Requested-With, Content-Type, Accept, Origin, Authorization'
1959 )
1960 ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
1961 $app->respond($response);
1962 }