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