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