]> git.immae.eu Git - github/shaarli/Shaarli.git/blob - index.php
Process token retrieve through Slim controller
[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/http/HttpUtils.php';
57 require_once 'application/http/UrlUtils.php';
58 require_once 'application/updater/UpdaterUtils.php';
59 require_once 'application/FileUtils.php';
60 require_once 'application/TimeZone.php';
61 require_once 'application/Utils.php';
62
63 use Shaarli\ApplicationUtils;
64 use Shaarli\Bookmark\Bookmark;
65 use Shaarli\Bookmark\BookmarkFileService;
66 use Shaarli\Bookmark\BookmarkFilter;
67 use Shaarli\Bookmark\BookmarkServiceInterface;
68 use Shaarli\Bookmark\Exception\BookmarkNotFoundException;
69 use Shaarli\Config\ConfigManager;
70 use Shaarli\Container\ContainerBuilder;
71 use Shaarli\Feed\CachedPage;
72 use Shaarli\Feed\FeedBuilder;
73 use Shaarli\Formatter\BookmarkMarkdownFormatter;
74 use Shaarli\Formatter\FormatterFactory;
75 use Shaarli\History;
76 use Shaarli\Languages;
77 use Shaarli\Netscape\NetscapeBookmarkUtils;
78 use Shaarli\Plugin\PluginManager;
79 use Shaarli\Render\PageBuilder;
80 use Shaarli\Render\PageCacheManager;
81 use Shaarli\Render\ThemeUtils;
82 use Shaarli\Router;
83 use Shaarli\Security\LoginManager;
84 use Shaarli\Security\SessionManager;
85 use Shaarli\Thumbnailer;
86 use Shaarli\Updater\Updater;
87 use Shaarli\Updater\UpdaterUtils;
88 use Slim\App;
89
90 // Ensure the PHP version is supported
91 try {
92 ApplicationUtils::checkPHPVersion('7.1', PHP_VERSION);
93 } catch (Exception $exc) {
94 header('Content-Type: text/plain; charset=utf-8');
95 echo $exc->getMessage();
96 exit;
97 }
98
99 define('SHAARLI_VERSION', ApplicationUtils::getVersion(__DIR__ .'/'. ApplicationUtils::$VERSION_FILE));
100
101 // Force cookie path (but do not change lifetime)
102 $cookie = session_get_cookie_params();
103 $cookiedir = '';
104 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
105 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
106 }
107 // Set default cookie expiration and path.
108 session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
109 // Set session parameters on server side.
110 // Use cookies to store session.
111 ini_set('session.use_cookies', 1);
112 // Force cookies for session (phpsessionID forbidden in URL).
113 ini_set('session.use_only_cookies', 1);
114 // Prevent PHP form using sessionID in URL if cookies are disabled.
115 ini_set('session.use_trans_sid', false);
116
117 session_name('shaarli');
118 // Start session if needed (Some server auto-start sessions).
119 if (session_status() == PHP_SESSION_NONE) {
120 session_start();
121 }
122
123 // Regenerate session ID if invalid or not defined in cookie.
124 if (isset($_COOKIE['shaarli']) && !SessionManager::checkId($_COOKIE['shaarli'])) {
125 session_regenerate_id(true);
126 $_COOKIE['shaarli'] = session_id();
127 }
128
129 $conf = new ConfigManager();
130
131 // In dev mode, throw exception on any warning
132 if ($conf->get('dev.debug', false)) {
133 // See all errors (for debugging only)
134 error_reporting(-1);
135
136 set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
137 throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
138 });
139 }
140
141 $sessionManager = new SessionManager($_SESSION, $conf);
142 $loginManager = new LoginManager($conf, $sessionManager);
143 $loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
144 $clientIpId = client_ip_id($_SERVER);
145
146 // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
147 if (! defined('LC_MESSAGES')) {
148 define('LC_MESSAGES', LC_COLLATE);
149 }
150
151 // Sniff browser language and set date format accordingly.
152 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
153 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
154 }
155
156 new Languages(setlocale(LC_MESSAGES, 0), $conf);
157
158 $conf->setEmpty('general.timezone', date_default_timezone_get());
159 $conf->setEmpty('general.title', t('Shared bookmarks on '). escape(index_url($_SERVER)));
160 RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
161 RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
162
163 $pluginManager = new PluginManager($conf);
164 $pluginManager->load($conf->get('general.enabled_plugins'));
165
166 date_default_timezone_set($conf->get('general.timezone', 'UTC'));
167
168 ob_start(); // Output buffering for the page cache.
169
170 // Prevent caching on client side or proxy: (yes, it's ugly)
171 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
172 header("Cache-Control: no-store, no-cache, must-revalidate");
173 header("Cache-Control: post-check=0, pre-check=0", false);
174 header("Pragma: no-cache");
175
176 if (! is_file($conf->getConfigFileExt())) {
177 // Ensure Shaarli has proper access to its resources
178 $errors = ApplicationUtils::checkResourcePermissions($conf);
179
180 if ($errors != array()) {
181 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
182
183 foreach ($errors as $error) {
184 $message .= '<li>'.$error.'</li>';
185 }
186 $message .= '</ul>';
187
188 header('Content-Type: text/html; charset=utf-8');
189 echo $message;
190 exit;
191 }
192
193 // Display the installation form if no existing config is found
194 install($conf, $sessionManager, $loginManager);
195 }
196
197 $loginManager->checkLoginState($_COOKIE, $clientIpId);
198
199 /**
200 * Adapter function to ensure compatibility with third-party templates
201 *
202 * @see https://github.com/shaarli/Shaarli/pull/1086
203 *
204 * @return bool true when the user is logged in, false otherwise
205 */
206 function isLoggedIn()
207 {
208 global $loginManager;
209 return $loginManager->isLoggedIn();
210 }
211
212
213 // ------------------------------------------------------------------------------------------
214 // Process login form: Check if login/password is correct.
215 if (isset($_POST['login'])) {
216 if (! $loginManager->canLogin($_SERVER)) {
217 die(t('I said: NO. You are banned for the moment. Go away.'));
218 }
219 if (isset($_POST['password'])
220 && $sessionManager->checkToken($_POST['token'])
221 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
222 ) {
223 $loginManager->handleSuccessfulLogin($_SERVER);
224
225 $cookiedir = '';
226 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
227 // Note: Never forget the trailing slash on the cookie path!
228 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
229 }
230
231 if (!empty($_POST['longlastingsession'])) {
232 // Keep the session cookie even after the browser closes
233 $sessionManager->setStaySignedIn(true);
234 $expirationTime = $sessionManager->extendSession();
235
236 setcookie(
237 $loginManager::$STAY_SIGNED_IN_COOKIE,
238 $loginManager->getStaySignedInToken(),
239 $expirationTime,
240 WEB_PATH
241 );
242 } else {
243 // Standard session expiration (=when browser closes)
244 $expirationTime = 0;
245 }
246
247 // Send cookie with the new expiration date to the browser
248 session_destroy();
249 session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
250 session_start();
251 session_regenerate_id(true);
252
253 // Optional redirect after login:
254 if (isset($_GET['post'])) {
255 $uri = './?post='. urlencode($_GET['post']);
256 foreach (array('description', 'source', 'title', 'tags') as $param) {
257 if (!empty($_GET[$param])) {
258 $uri .= '&'.$param.'='.urlencode($_GET[$param]);
259 }
260 }
261 header('Location: '. $uri);
262 exit;
263 }
264
265 if (isset($_GET['edit_link'])) {
266 header('Location: ./?edit_link='. escape($_GET['edit_link']));
267 exit;
268 }
269
270 if (isset($_POST['returnurl'])) {
271 // Prevent loops over login screen.
272 if (strpos($_POST['returnurl'], '/login') === false) {
273 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
274 exit;
275 }
276 }
277 header('Location: ./?');
278 exit;
279 } else {
280 $loginManager->handleFailedLogin($_SERVER);
281 $redir = '?username='. urlencode($_POST['login']);
282 if (isset($_GET['post'])) {
283 $redir .= '&post=' . urlencode($_GET['post']);
284 foreach (array('description', 'source', 'title', 'tags') as $param) {
285 if (!empty($_GET[$param])) {
286 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
287 }
288 }
289 }
290 // Redirect to login screen.
291 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'./login'.$redir.'\';</script>';
292 exit;
293 }
294 }
295
296 // ------------------------------------------------------------------------------------------
297 // Token management for XSRF protection
298 // Token should be used in any form which acts on data (create,update,delete,import...).
299 if (!isset($_SESSION['tokens'])) {
300 $_SESSION['tokens']=array(); // Token are attached to the session.
301 }
302
303 /**
304 * Renders the linklist
305 *
306 * @param pageBuilder $PAGE pageBuilder instance.
307 * @param BookmarkServiceInterface $linkDb instance.
308 * @param ConfigManager $conf Configuration Manager instance.
309 * @param PluginManager $pluginManager Plugin Manager instance.
310 */
311 function showLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager)
312 {
313 buildLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager);
314 $PAGE->renderPage('linklist');
315 }
316
317 /**
318 * Render HTML page (according to URL parameters and user rights)
319 *
320 * @param ConfigManager $conf Configuration Manager instance.
321 * @param PluginManager $pluginManager Plugin Manager instance,
322 * @param BookmarkServiceInterface $bookmarkService
323 * @param History $history instance
324 * @param SessionManager $sessionManager SessionManager instance
325 * @param LoginManager $loginManager LoginManager instance
326 */
327 function renderPage($conf, $pluginManager, $bookmarkService, $history, $sessionManager, $loginManager)
328 {
329 $pageCacheManager = new PageCacheManager($conf->get('resource.page_cache'), $loginManager->isLoggedIn());
330 $updater = new Updater(
331 UpdaterUtils::read_updates_file($conf->get('resource.updates')),
332 $bookmarkService,
333 $conf,
334 $loginManager->isLoggedIn()
335 );
336 try {
337 $newUpdates = $updater->update();
338 if (! empty($newUpdates)) {
339 UpdaterUtils::write_updates_file(
340 $conf->get('resource.updates'),
341 $updater->getDoneUpdates()
342 );
343
344 $pageCacheManager->invalidateCaches();
345 }
346 } catch (Exception $e) {
347 die($e->getMessage());
348 }
349
350 $PAGE = new PageBuilder($conf, $_SESSION, $bookmarkService, $sessionManager->generateToken(), $loginManager->isLoggedIn());
351 $PAGE->assign('linkcount', $bookmarkService->count(BookmarkFilter::$ALL));
352 $PAGE->assign('privateLinkcount', $bookmarkService->count(BookmarkFilter::$PRIVATE));
353 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
354
355 // Determine which page will be rendered.
356 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
357 $targetPage = Router::findPage($query, $_GET, $loginManager->isLoggedIn());
358
359 if (// if the user isn't logged in
360 !$loginManager->isLoggedIn() &&
361 // and Shaarli doesn't have public content...
362 $conf->get('privacy.hide_public_links') &&
363 // and is configured to enforce the login
364 $conf->get('privacy.force_login') &&
365 // and the current page isn't already the login page
366 $targetPage !== Router::$PAGE_LOGIN &&
367 // and the user is not requesting a feed (which would lead to a different content-type as expected)
368 $targetPage !== Router::$PAGE_FEED_ATOM &&
369 $targetPage !== Router::$PAGE_FEED_RSS
370 ) {
371 // force current page to be the login page
372 $targetPage = Router::$PAGE_LOGIN;
373 }
374
375 // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
376 // Then assign generated data to RainTPL.
377 $common_hooks = array(
378 'includes',
379 'header',
380 'footer',
381 );
382
383 foreach ($common_hooks as $name) {
384 $plugin_data = array();
385 $pluginManager->executeHooks(
386 'render_' . $name,
387 $plugin_data,
388 array(
389 'target' => $targetPage,
390 'loggedin' => $loginManager->isLoggedIn()
391 )
392 );
393 $PAGE->assign('plugins_' . $name, $plugin_data);
394 }
395
396 // -------- Display login form.
397 if ($targetPage == Router::$PAGE_LOGIN) {
398 header('Location: ./login');
399 exit;
400 }
401 // -------- User wants to logout.
402 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) {
403 header('Location: ./logout');
404 exit;
405 }
406
407 // -------- Picture wall
408 if ($targetPage == Router::$PAGE_PICWALL) {
409 header('Location: ./picture-wall');
410 exit;
411 }
412
413 // -------- Tag cloud
414 if ($targetPage == Router::$PAGE_TAGCLOUD) {
415 header('Location: ./tags/cloud');
416 exit;
417 }
418
419 // -------- Tag list
420 if ($targetPage == Router::$PAGE_TAGLIST) {
421 header('Location: ./tags/list');
422 exit;
423 }
424
425 // Daily page.
426 if ($targetPage == Router::$PAGE_DAILY) {
427 $dayParam = !empty($_GET['day']) ? '?day=' . escape($_GET['day']) : '';
428 header('Location: ./daily'. $dayParam);
429 exit;
430 }
431
432 // ATOM and RSS feed.
433 if ($targetPage == Router::$PAGE_FEED_ATOM || $targetPage == Router::$PAGE_FEED_RSS) {
434 $feedType = $targetPage == Router::$PAGE_FEED_RSS ? FeedBuilder::$FEED_RSS : FeedBuilder::$FEED_ATOM;
435
436 header('Location: ./feed/'. $feedType .'?'. http_build_query($_GET));
437 exit;
438 }
439
440 // Display opensearch plugin (XML)
441 if ($targetPage == Router::$PAGE_OPENSEARCH) {
442 header('Location: ./open-search');
443 exit;
444 }
445
446 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
447 if (isset($_GET['addtag'])) {
448 header('Location: ./add-tag/'. $_GET['addtag']);
449 exit;
450 }
451
452 // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
453 if (isset($_GET['removetag'])) {
454 header('Location: ./remove-tag/'. $_GET['removetag']);
455 exit;
456 }
457
458 // -------- User wants to change the number of bookmarks per page (linksperpage=...)
459 if (isset($_GET['linksperpage'])) {
460 header('Location: ./links-per-page?nb='. $_GET['linksperpage']);
461 exit;
462 }
463
464 // -------- User wants to see only private bookmarks (toggle)
465 if (isset($_GET['visibility'])) {
466 header('Location: ./visibility/'. $_GET['visibility']);
467 exit;
468 }
469
470 // -------- User wants to see only untagged bookmarks (toggle)
471 if (isset($_GET['untaggedonly'])) {
472 header('Location: ./untagged-only');
473 exit;
474 }
475
476 // -------- Handle other actions allowed for non-logged in users:
477 if (!$loginManager->isLoggedIn()) {
478 // User tries to post new link but is not logged in:
479 // Show login screen, then redirect to ?post=...
480 if (isset($_GET['post'])) {
481 header( // Redirect to login page, then back to post link.
482 'Location: ./login?post='.urlencode($_GET['post']).
483 (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
484 (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
485 (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
486 (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
487 );
488 exit;
489 }
490
491 showLinkList($PAGE, $bookmarkService, $conf, $pluginManager, $loginManager);
492 if (isset($_GET['edit_link'])) {
493 header('Location: ./login?edit_link='. escape($_GET['edit_link']));
494 exit;
495 }
496
497 exit; // Never remove this one! All operations below are reserved for logged in user.
498 }
499
500 // -------- All other functions are reserved for the registered user:
501
502 // TODO: Remove legacy admin route redirections. We'll only keep public URL.
503
504 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
505 if ($targetPage == Router::$PAGE_TOOLS) {
506 header('Location: ./admin/tools');
507 exit;
508 }
509
510 // -------- User wants to change his/her password.
511 if ($targetPage == Router::$PAGE_CHANGEPASSWORD) {
512 header('Location: ./admin/password');
513 exit;
514 }
515
516 // -------- User wants to change configuration
517 if ($targetPage == Router::$PAGE_CONFIGURE) {
518 header('Location: ./admin/configure');
519 exit;
520 }
521
522 // -------- User wants to rename a tag or delete it
523 if ($targetPage == Router::$PAGE_CHANGETAG) {
524 header('Location: ./admin/tags');
525 exit;
526 }
527
528 // -------- User wants to add a link without using the bookmarklet: Show form.
529 if ($targetPage == Router::$PAGE_ADDLINK) {
530 header('Location: ./admin/shaare');
531 exit;
532 }
533
534 // -------- User clicked the "Save" button when editing a link: Save link to database.
535 if (isset($_POST['save_edit'])) {
536 // This route is no longer supported in legacy mode
537 header('Location: ./');
538 exit;
539 }
540
541 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
542 if ($targetPage == Router::$PAGE_DELETELINK) {
543 $ids = $_GET['lf_linkdate'] ?? '';
544 $token = $_GET['token'] ?? '';
545
546 header('Location: ./admin/shaare/delete?id=' . $ids . '&token=' . $token);
547 exit;
548 }
549
550 // -------- User clicked either "Set public" or "Set private" bulk operation
551 if ($targetPage == Router::$PAGE_CHANGE_VISIBILITY) {
552 header('Location: ./admin/shaare/visibility?id=' . $_GET['token']);
553 exit;
554 }
555
556 // -------- User clicked the "EDIT" button on a link: Display link edit form.
557 if (isset($_GET['edit_link'])) {
558 $id = (int) escape($_GET['edit_link']);
559 header('Location: ./admin/shaare/' . $id);
560 exit;
561 }
562
563 // -------- User want to post a new link: Display link edit form.
564 if (isset($_GET['post'])) {
565 header('Location: ./admin/shaare?' . http_build_query($_GET));
566 exit;
567 }
568
569 if ($targetPage == Router::$PAGE_PINLINK) {
570 // This route is no longer supported in legacy mode
571 header('Location: ./');
572 exit;
573 }
574
575 if ($targetPage == Router::$PAGE_EXPORT) {
576 header('Location: ./admin/export');
577 exit;
578 }
579
580 if ($targetPage == Router::$PAGE_IMPORT) {
581 header('Location: ./admin/import');
582 exit;
583 }
584
585 // Plugin administration page
586 if ($targetPage == Router::$PAGE_PLUGINSADMIN) {
587 header('Location: ./admin/plugins');
588 exit;
589 }
590
591 // Plugin administration form action
592 if ($targetPage == Router::$PAGE_SAVE_PLUGINSADMIN) {
593 // This route is no longer supported in legacy mode
594 header('Location: ./admin/plugins');
595 exit;
596 }
597
598 // Get a fresh token
599 if ($targetPage == Router::$GET_TOKEN) {
600 header('Location: ./admin/token');
601 exit;
602 }
603
604 // -------- Thumbnails Update
605 if ($targetPage == Router::$PAGE_THUMBS_UPDATE) {
606 $ids = [];
607 foreach ($bookmarkService->search() as $bookmark) {
608 // A note or not HTTP(S)
609 if ($bookmark->isNote() || ! startsWith(strtolower($bookmark->getUrl()), 'http')) {
610 continue;
611 }
612 $ids[] = $bookmark->getId();
613 }
614 $PAGE->assign('ids', $ids);
615 $PAGE->assign('pagetitle', t('Thumbnails update') .' - '. $conf->get('general.title', 'Shaarli'));
616 $PAGE->renderPage('thumbnails');
617 exit;
618 }
619
620 // -------- Single Thumbnail Update
621 if ($targetPage == Router::$AJAX_THUMB_UPDATE) {
622 if (! isset($_POST['id']) || ! ctype_digit($_POST['id'])) {
623 http_response_code(400);
624 exit;
625 }
626 $id = (int) $_POST['id'];
627 if (! $bookmarkService->exists($id)) {
628 http_response_code(404);
629 exit;
630 }
631 $thumbnailer = new Thumbnailer($conf);
632 $bookmark = $bookmarkService->get($id);
633 $bookmark->setThumbnail($thumbnailer->get($bookmark->getUrl()));
634 $bookmarkService->set($bookmark);
635
636 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
637 echo json_encode($factory->getFormatter('raw')->format($bookmark));
638 exit;
639 }
640
641 // -------- Otherwise, simply display search form and bookmarks:
642 showLinkList($PAGE, $bookmarkService, $conf, $pluginManager, $loginManager);
643 exit;
644 }
645
646 /**
647 * Template for the list of bookmarks (<div id="linklist">)
648 * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
649 *
650 * @param pageBuilder $PAGE pageBuilder instance.
651 * @param BookmarkServiceInterface $linkDb LinkDB instance.
652 * @param ConfigManager $conf Configuration Manager instance.
653 * @param PluginManager $pluginManager Plugin Manager instance.
654 * @param LoginManager $loginManager LoginManager instance
655 */
656 function buildLinkList($PAGE, $linkDb, $conf, $pluginManager, $loginManager)
657 {
658 $factory = new FormatterFactory($conf, $loginManager->isLoggedIn());
659 $formatter = $factory->getFormatter();
660
661 // Used in templates
662 if (isset($_GET['searchtags'])) {
663 if (! empty($_GET['searchtags'])) {
664 $searchtags = escape(normalize_spaces($_GET['searchtags']));
665 } else {
666 $searchtags = false;
667 }
668 } else {
669 $searchtags = '';
670 }
671 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
672
673 // Smallhash filter
674 if (! empty($_SERVER['QUERY_STRING'])
675 && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
676 try {
677 $linksToDisplay = $linkDb->findByHash($_SERVER['QUERY_STRING']);
678 } catch (BookmarkNotFoundException $e) {
679 $PAGE->render404($e->getMessage());
680 exit;
681 }
682 } else {
683 // Filter bookmarks according search parameters.
684 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : null;
685 $request = [
686 'searchtags' => $searchtags,
687 'searchterm' => $searchterm,
688 ];
689 $linksToDisplay = $linkDb->search($request, $visibility, false, !empty($_SESSION['untaggedonly']));
690 }
691
692 // ---- Handle paging.
693 $keys = array();
694 foreach ($linksToDisplay as $key => $value) {
695 $keys[] = $key;
696 }
697
698 // Select articles according to paging.
699 $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
700 $pagecount = $pagecount == 0 ? 1 : $pagecount;
701 $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
702 $page = $page < 1 ? 1 : $page;
703 $page = $page > $pagecount ? $pagecount : $page;
704 // Start index.
705 $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
706 $end = $i + $_SESSION['LINKS_PER_PAGE'];
707
708 $thumbnailsEnabled = $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE;
709 if ($thumbnailsEnabled) {
710 $thumbnailer = new Thumbnailer($conf);
711 }
712
713 $linkDisp = array();
714 while ($i<$end && $i<count($keys)) {
715 $link = $formatter->format($linksToDisplay[$keys[$i]]);
716
717 // Logged in, thumbnails enabled, not a note,
718 // and (never retrieved yet or no valid cache file)
719 if ($loginManager->isLoggedIn()
720 && $thumbnailsEnabled
721 && !$linksToDisplay[$keys[$i]]->isNote()
722 && $linksToDisplay[$keys[$i]]->getThumbnail() !== false
723 && ! is_file($linksToDisplay[$keys[$i]]->getThumbnail())
724 ) {
725 $linksToDisplay[$keys[$i]]->setThumbnail($thumbnailer->get($link['url']));
726 $linkDb->set($linksToDisplay[$keys[$i]], false);
727 $updateDB = true;
728 $link['thumbnail'] = $linksToDisplay[$keys[$i]]->getThumbnail();
729 }
730
731 // Check for both signs of a note: starting with ? and 7 chars long.
732 // if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
733 // $link['url'] = index_url($_SERVER) . $link['url'];
734 // }
735
736 $linkDisp[$keys[$i]] = $link;
737 $i++;
738 }
739
740 // If we retrieved new thumbnails, we update the database.
741 if (!empty($updateDB)) {
742 $linkDb->save();
743 }
744
745 // Compute paging navigation
746 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
747 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
748 $previous_page_url = '';
749 if ($i != count($keys)) {
750 $previous_page_url = '?page=' . ($page+1) . $searchtermUrl . $searchtagsUrl;
751 }
752 $next_page_url='';
753 if ($page>1) {
754 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
755 }
756
757 // Fill all template fields.
758 $data = array(
759 'previous_page_url' => $previous_page_url,
760 'next_page_url' => $next_page_url,
761 'page_current' => $page,
762 'page_max' => $pagecount,
763 'result_count' => count($linksToDisplay),
764 'search_term' => $searchterm,
765 'search_tags' => $searchtags,
766 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
767 'links' => $linkDisp,
768 );
769
770 // If there is only a single link, we change on-the-fly the title of the page.
771 if (count($linksToDisplay) == 1) {
772 $data['pagetitle'] = $linksToDisplay[$keys[0]]->getTitle() .' - '. $conf->get('general.title');
773 } elseif (! empty($searchterm) || ! empty($searchtags)) {
774 $data['pagetitle'] = t('Search: ');
775 $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
776 $bracketWrap = function ($tag) {
777 return '['. $tag .']';
778 };
779 $data['pagetitle'] .= ! empty($searchtags)
780 ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
781 : '';
782 $data['pagetitle'] .= '- '. $conf->get('general.title');
783 }
784
785 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
786
787 foreach ($data as $key => $value) {
788 $PAGE->assign($key, $value);
789 }
790
791 return;
792 }
793
794 /**
795 * Installation
796 * This function should NEVER be called if the file data/config.php exists.
797 *
798 * @param ConfigManager $conf Configuration Manager instance.
799 * @param SessionManager $sessionManager SessionManager instance
800 * @param LoginManager $loginManager LoginManager instance
801 */
802 function install($conf, $sessionManager, $loginManager)
803 {
804 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
805 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
806 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
807 }
808
809
810 // This part makes sure sessions works correctly.
811 // (Because on some hosts, session.save_path may not be set correctly,
812 // or we may not have write access to it.)
813 if (isset($_GET['test_session'])
814 && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
815 // Step 2: Check if data in session is correct.
816 $msg = t(
817 '<pre>Sessions do not seem to work correctly on your server.<br>'.
818 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
819 'and that you have write access to it.<br>'.
820 'It currently points to %s.<br>'.
821 'On some browsers, accessing your server via a hostname like \'localhost\' '.
822 'or any custom hostname without a dot causes cookie storage to fail. '.
823 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
824 );
825 $msg = sprintf($msg, session_save_path());
826 echo $msg;
827 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
828 die;
829 }
830 if (!isset($_SESSION['session_tested'])) {
831 // Step 1 : Try to store data in session and reload page.
832 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
833 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
834 }
835 if (isset($_GET['test_session'])) {
836 // Step 3: Sessions are OK. Remove test parameter from URL.
837 header('Location: '.index_url($_SERVER));
838 }
839
840
841 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
842 $tz = 'UTC';
843 if (!empty($_POST['continent']) && !empty($_POST['city'])
844 && isTimeZoneValid($_POST['continent'], $_POST['city'])
845 ) {
846 $tz = $_POST['continent'].'/'.$_POST['city'];
847 }
848 $conf->set('general.timezone', $tz);
849 $login = $_POST['setlogin'];
850 $conf->set('credentials.login', $login);
851 $salt = sha1(uniqid('', true) .'_'. mt_rand());
852 $conf->set('credentials.salt', $salt);
853 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
854 if (!empty($_POST['title'])) {
855 $conf->set('general.title', escape($_POST['title']));
856 } else {
857 $conf->set('general.title', 'Shared bookmarks on '.escape(index_url($_SERVER)));
858 }
859 $conf->set('translation.language', escape($_POST['language']));
860 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
861 $conf->set('api.enabled', !empty($_POST['enableApi']));
862 $conf->set(
863 'api.secret',
864 generate_api_secret(
865 $conf->get('credentials.login'),
866 $conf->get('credentials.salt')
867 )
868 );
869 try {
870 // Everything is ok, let's create config file.
871 $conf->write($loginManager->isLoggedIn());
872 } catch (Exception $e) {
873 error_log(
874 'ERROR while writing config file after installation.' . PHP_EOL .
875 $e->getMessage()
876 );
877
878 // TODO: do not handle exceptions/errors in JS.
879 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
880 exit;
881 }
882
883 $history = new History($conf->get('resource.history'));
884 $bookmarkService = new BookmarkFileService($conf, $history, true);
885 if ($bookmarkService->count() === 0) {
886 $bookmarkService->initialize();
887 }
888
889 echo '<script>alert('
890 .'"Shaarli is now configured. '
891 .'Please enter your login/password and start shaaring your bookmarks!"'
892 .');document.location=\'./login\';</script>';
893 exit;
894 }
895
896 $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
897 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
898 $PAGE->assign('continents', $continents);
899 $PAGE->assign('cities', $cities);
900 $PAGE->assign('languages', Languages::getAvailableLanguages());
901 $PAGE->renderPage('install');
902 exit;
903 }
904
905 if (!isset($_SESSION['LINKS_PER_PAGE'])) {
906 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
907 }
908
909 try {
910 $history = new History($conf->get('resource.history'));
911 } catch (Exception $e) {
912 die($e->getMessage());
913 }
914
915 $linkDb = new BookmarkFileService($conf, $history, $loginManager->isLoggedIn());
916
917 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) {
918 header('Location: ./daily-rss');
919 exit;
920 }
921
922 $containerBuilder = new ContainerBuilder($conf, $sessionManager, $loginManager);
923 $container = $containerBuilder->build();
924 $app = new App($container);
925
926 // REST API routes
927 $app->group('/api/v1', function () {
928 $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
929 $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
930 $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
931 $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
932 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
933 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
934
935 $this->get('/tags', '\Shaarli\Api\Controllers\Tags:getTags')->setName('getTags');
936 $this->get('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:getTag')->setName('getTag');
937 $this->put('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:putTag')->setName('putTag');
938 $this->delete('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:deleteTag')->setName('deleteTag');
939
940 $this->get('/history', '\Shaarli\Api\Controllers\HistoryController:getHistory')->setName('getHistory');
941 })->add('\Shaarli\Api\ApiMiddleware');
942
943 $app->group('', function () {
944 /* -- PUBLIC --*/
945 $this->get('/login', '\Shaarli\Front\Controller\Visitor\LoginController:index');
946 $this->get('/picture-wall', '\Shaarli\Front\Controller\Visitor\PictureWallController:index');
947 $this->get('/tags/cloud', '\Shaarli\Front\Controller\Visitor\TagCloudController:cloud');
948 $this->get('/tags/list', '\Shaarli\Front\Controller\Visitor\TagCloudController:list');
949 $this->get('/daily', '\Shaarli\Front\Controller\Visitor\DailyController:index');
950 $this->get('/daily-rss', '\Shaarli\Front\Controller\Visitor\DailyController:rss');
951 $this->get('/feed/atom', '\Shaarli\Front\Controller\Visitor\FeedController:atom');
952 $this->get('/feed/rss', '\Shaarli\Front\Controller\Visitor\FeedController:rss');
953 $this->get('/open-search', '\Shaarli\Front\Controller\Visitor\OpenSearchController:index');
954
955 $this->get('/add-tag/{newTag}', '\Shaarli\Front\Controller\Visitor\TagController:addTag');
956 $this->get('/remove-tag/{tag}', '\Shaarli\Front\Controller\Visitor\TagController:removeTag');
957
958 /* -- LOGGED IN -- */
959 $this->get('/logout', '\Shaarli\Front\Controller\Admin\LogoutController:index');
960 $this->get('/admin/tools', '\Shaarli\Front\Controller\Admin\ToolsController:index');
961 $this->get('/admin/password', '\Shaarli\Front\Controller\Admin\PasswordController:index');
962 $this->post('/admin/password', '\Shaarli\Front\Controller\Admin\PasswordController:change');
963 $this->get('/admin/configure', '\Shaarli\Front\Controller\Admin\ConfigureController:index');
964 $this->post('/admin/configure', '\Shaarli\Front\Controller\Admin\ConfigureController:save');
965 $this->get('/admin/tags', '\Shaarli\Front\Controller\Admin\ManageTagController:index');
966 $this->post('/admin/tags', '\Shaarli\Front\Controller\Admin\ManageTagController:save');
967 $this->get('/admin/add-shaare', '\Shaarli\Front\Controller\Admin\ManageShaareController:addShaare');
968 $this->get('/admin/shaare', '\Shaarli\Front\Controller\Admin\ManageShaareController:displayCreateForm');
969 $this->get('/admin/shaare/{id:[0-9]+}', '\Shaarli\Front\Controller\Admin\ManageShaareController:displayEditForm');
970 $this->post('/admin/shaare', '\Shaarli\Front\Controller\Admin\ManageShaareController:save');
971 $this->get('/admin/shaare/delete', '\Shaarli\Front\Controller\Admin\ManageShaareController:deleteBookmark');
972 $this->get('/admin/shaare/visibility', '\Shaarli\Front\Controller\Admin\ManageShaareController:changeVisibility');
973 $this->get('/admin/shaare/{id:[0-9]+}/pin', '\Shaarli\Front\Controller\Admin\ManageShaareController:pinBookmark');
974 $this->get('/admin/export', '\Shaarli\Front\Controller\Admin\ExportController:index');
975 $this->post('/admin/export', '\Shaarli\Front\Controller\Admin\ExportController:export');
976 $this->get('/admin/import', '\Shaarli\Front\Controller\Admin\ImportController:index');
977 $this->post('/admin/import', '\Shaarli\Front\Controller\Admin\ImportController:import');
978 $this->get('/admin/plugins', '\Shaarli\Front\Controller\Admin\PluginsController:index');
979 $this->post('/admin/plugins', '\Shaarli\Front\Controller\Admin\PluginsController:save');
980 $this->get('/admin/token', '\Shaarli\Front\Controller\Admin\TokenController:getToken');
981
982 $this->get('/links-per-page', '\Shaarli\Front\Controller\Admin\SessionFilterController:linksPerPage');
983 $this->get('/visibility/{visibility}', '\Shaarli\Front\Controller\Admin\SessionFilterController:visibility');
984 $this->get('/untagged-only', '\Shaarli\Front\Controller\Admin\SessionFilterController:untaggedOnly');
985 })->add('\Shaarli\Front\ShaarliMiddleware');
986
987 $response = $app->run(true);
988
989 // Hack to make Slim and Shaarli router work together:
990 // If a Slim route isn't found and NOT API call, we call renderPage().
991 if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
992 // We use UTF-8 for proper international characters handling.
993 header('Content-Type: text/html; charset=utf-8');
994 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
995 } else {
996 $response = $response
997 ->withHeader('Access-Control-Allow-Origin', '*')
998 ->withHeader(
999 'Access-Control-Allow-Headers',
1000 'X-Requested-With, Content-Type, Accept, Origin, Authorization'
1001 )
1002 ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
1003 $app->respond($response);
1004 }