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