]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - index.php
Merge branch 'v0.11' into stable
[github/shaarli/Shaarli.git] / index.php
CommitLineData
45034273 1<?php
49e2b35b 2/**
83faedad 3<<<<<<< HEAD
c372fc96 4 * Shaarli v0.8.7 - Shaare your links...
49e2b35b 5 *
2d97aa77 6 * The personal, minimalist, super-fast, database free, bookmarking service.
83faedad 7=======
b786c883 8 * Shaarli - The personal, minimalist, super-fast, database free, bookmarking service.
83faedad 9>>>>>>> v0.9.7
49e2b35b
V
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 *
3947bbb0 20 * Requires: PHP 5.5.x
49e2b35b 21 */
afd7b77b
V
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
25if (date_default_timezone_get() == '') {
26 date_default_timezone_set('UTC');
27}
cb49ab94 28
28bb2b74
V
29/*
30 * PHP configuration
31 */
28bb2b74 32
ae00595b 33// http://server.com/x/shaarli --> /shaarli/
684e662a 34define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0)));
45034273 35
28bb2b74 36// High execution time in case of problematic imports/exports.
93bf0918 37ini_set('max_input_time', '60');
28bb2b74
V
38
39// Try to set max upload file size and read
40ini_set('memory_limit', '128M');
45034273
SS
41ini_set('post_max_size', '16M');
42ini_set('upload_max_filesize', '16M');
45034273 43
28bb2b74
V
44// See all error except warnings
45error_reporting(E_ALL^E_WARNING);
46// See all errors (for debugging only)
47//error_reporting(-1);
48
50c9a12e 49
a973afea 50// 3rd-party libraries
52831753
V
51if (! 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"
87f14312 57 ."- https://shaarli.readthedocs.io/en/master/Server-configuration/\n"
cc8f572b 58 ."- https://shaarli.readthedocs.io/en/master/Download-and-Installation/";
52831753
V
59 exit;
60}
a973afea
V
61require_once 'inc/rain.tpl.class.php';
62require_once __DIR__ . '/vendor/autoload.php';
63
ca74886f 64// Shaarli library
fe3713d2 65require_once 'application/bookmark/LinkUtils.php';
278d9ee2 66require_once 'application/config/ConfigPlugin.php';
dfc650aa 67require_once 'application/feed/Cache.php';
51753e40
V
68require_once 'application/http/HttpUtils.php';
69require_once 'application/http/UrlUtils.php';
bcf056c9 70require_once 'application/updater/UpdaterUtils.php';
2e28269b 71require_once 'application/FileUtils.php';
d1e2f8e5 72require_once 'application/TimeZone.php';
ca74886f 73require_once 'application/Utils.php';
f24896b2 74
9778a155 75use \Shaarli\ApplicationUtils;
6696729b 76use \Shaarli\Bookmark\Exception\LinkNotFoundException;
f24896b2 77use \Shaarli\Bookmark\LinkDB;
3c66e564 78use \Shaarli\Config\ConfigManager;
dfc650aa
V
79use \Shaarli\Feed\CachedPage;
80use \Shaarli\Feed\FeedBuilder;
81use \Shaarli\History;
12266213 82use \Shaarli\Languages;
349b0144 83use \Shaarli\Netscape\NetscapeBookmarkUtils;
e1850388 84use \Shaarli\Plugin\PluginManager;
8c0f19c7
V
85use \Shaarli\Render\PageBuilder;
86use \Shaarli\Render\ThemeUtils;
a932f486 87use \Shaarli\Router;
fab87c26
V
88use \Shaarli\Security\LoginManager;
89use \Shaarli\Security\SessionManager;
e85b7a05 90use \Shaarli\Thumbnailer;
9778a155 91use \Shaarli\Updater\Updater;
ca74886f 92
d1e2f8e5
V
93// Ensure the PHP version is supported
94try {
3947bbb0 95 ApplicationUtils::checkPHPVersion('5.5', PHP_VERSION);
93bf0918 96} catch (Exception $exc) {
d1e2f8e5 97 header('Content-Type: text/plain; charset=utf-8');
2e28269b 98 echo $exc->getMessage();
d1e2f8e5
V
99 exit;
100}
101
b3e1f92e 102define('SHAARLI_VERSION', ApplicationUtils::getVersion(__DIR__ .'/'. ApplicationUtils::$VERSION_FILE));
b786c883 103
06b6660a
A
104// Force cookie path (but do not change lifetime)
105$cookie = session_get_cookie_params();
106$cookiedir = '';
107if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
108 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
109}
110// Set default cookie expiration and path.
111session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
112// Set session parameters on server side.
06b6660a
A
113// Use cookies to store session.
114ini_set('session.use_cookies', 1);
115// Force cookies for session (phpsessionID forbidden in URL).
116ini_set('session.use_only_cookies', 1);
117// Prevent PHP form using sessionID in URL if cookies are disabled.
118ini_set('session.use_trans_sid', false);
119
06b6660a
A
120session_name('shaarli');
121// Start session if needed (Some server auto-start sessions).
f6380409 122if (session_status() == PHP_SESSION_NONE) {
06b6660a
A
123 session_start();
124}
125
68bc2135 126// Regenerate session ID if invalid or not defined in cookie.
fd7d8461 127if (isset($_COOKIE['shaarli']) && !SessionManager::checkId($_COOKIE['shaarli'])) {
68bc2135
V
128 session_regenerate_id(true);
129 $_COOKIE['shaarli'] = session_id();
130}
131
278d9ee2 132$conf = new ConfigManager();
ebd650c0 133$sessionManager = new SessionManager($_SESSION, $conf);
b49a04f7 134$loginManager = new LoginManager($conf, $sessionManager);
c689e108 135$loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
84742084 136$clientIpId = client_ip_id($_SERVER);
12266213 137
b7c412d4
A
138// LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
139if (! defined('LC_MESSAGES')) {
140 define('LC_MESSAGES', LC_COLLATE);
141}
142
12266213
A
143// Sniff browser language and set date format accordingly.
144if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
145 autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
146}
147
148new Languages(setlocale(LC_MESSAGES, 0), $conf);
149
7f179985 150$conf->setEmpty('general.timezone', date_default_timezone_get());
12266213 151$conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
adc4aee8 152RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
894a3c4b 153RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
45034273 154
278d9ee2 155$pluginManager = new PluginManager($conf);
da10377b 156$pluginManager->load($conf->get('general.enabled_plugins'));
6fc14d53 157
da10377b 158date_default_timezone_set($conf->get('general.timezone', 'UTC'));
d93d51b2 159
45034273
SS
160ob_start(); // Output buffering for the page cache.
161
45034273
SS
162// Prevent caching on client side or proxy: (yes, it's ugly)
163header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
164header("Cache-Control: no-store, no-cache, must-revalidate");
165header("Cache-Control: post-check=0, pre-check=0", false);
166header("Pragma: no-cache");
167
278d9ee2 168if (! is_file($conf->getConfigFileExt())) {
2e28269b 169 // Ensure Shaarli has proper access to its resources
278d9ee2 170 $errors = ApplicationUtils::checkResourcePermissions($conf);
2e28269b
V
171
172 if ($errors != array()) {
12266213 173 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
2e28269b
V
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
cad4251a 186 install($conf, $sessionManager, $loginManager);
50c9a12e 187}
8a80e4fe 188
c689e108 189$loginManager->checkLoginState($_COOKIE, $clientIpId);
8a80e4fe 190
278d9ee2 191/**
89ccc83b 192 * Adapter function to ensure compatibility with third-party templates
278d9ee2 193 *
89ccc83b 194 * @see https://github.com/shaarli/Shaarli/pull/1086
278d9ee2 195 *
89ccc83b 196 * @return bool true when the user is logged in, false otherwise
278d9ee2 197 */
45034273
SS
198function isLoggedIn()
199{
63ea23c2
V
200 global $loginManager;
201 return $loginManager->isLoggedIn();
ae00595b 202}
45034273
SS
203
204
45034273
SS
205// ------------------------------------------------------------------------------------------
206// Process login form: Check if login/password is correct.
db45a36a 207if (isset($_POST['login'])) {
44acf706
V
208 if (! $loginManager->canLogin($_SERVER)) {
209 die(t('I said: NO. You are banned for the moment. Go away.'));
210 }
278d9ee2 211 if (isset($_POST['password'])
ebd650c0 212 && $sessionManager->checkToken($_POST['token'])
84742084 213 && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
44acf706 214 ) {
44acf706
V
215 $loginManager->handleSuccessfulLogin($_SERVER);
216
51f0128c
V
217 $cookiedir = '';
218 if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
ad6c27b7 219 // Note: Never forget the trailing slash on the cookie path!
51f0128c 220 $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
45034273 221 }
51f0128c
V
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(
c689e108
V
229 $loginManager::$STAY_SIGNED_IN_COOKIE,
230 $loginManager->getStaySignedInToken(),
51f0128c
V
231 $expirationTime,
232 WEB_PATH
233 );
51f0128c
V
234 } else {
235 // Standard session expiration (=when browser closes)
236 $expirationTime = 0;
45034273 237 }
f4c84ad7 238
51f0128c
V
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
45034273 243 // Optional redirect after login:
5fbabbb9
A
244 if (isset($_GET['post'])) {
245 $uri = '?post='. urlencode($_GET['post']);
0b04f797 246 foreach (array('description', 'source', 'title', 'tags') as $param) {
5fbabbb9
A
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) {
e15f08d7 263 header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
5fbabbb9
A
264 exit;
265 }
45034273 266 }
93bf0918
V
267 header('Location: ?');
268 exit;
44acf706
V
269 } else {
270 $loginManager->handleFailedLogin($_SERVER);
aadec30e 271 $redir = '&username='. urlencode($_POST['login']);
5fbabbb9 272 if (isset($_GET['post'])) {
85c4bdc2 273 $redir .= '&post=' . urlencode($_GET['post']);
0b04f797 274 foreach (array('description', 'source', 'title', 'tags') as $param) {
5fbabbb9
A
275 if (!empty($_GET[$param])) {
276 $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
277 }
278 }
279 }
12266213
A
280 // Redirect to login screen.
281 echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
45034273
SS
282 exit;
283 }
284}
285
45034273
SS
286// ------------------------------------------------------------------------------------------
287// Token management for XSRF protection
288// Token should be used in any form which acts on data (create,update,delete,import...).
93bf0918
V
289if (!isset($_SESSION['tokens'])) {
290 $_SESSION['tokens']=array(); // Token are attached to the session.
291}
45034273 292
278d9ee2
A
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 *
63ea23c2
V
298 * @param ConfigManager $conf Configuration Manager instance
299 * @param LoginManager $loginManager LoginManager instance
278d9ee2 300 */
93bf0918
V
301function showDailyRSS($conf, $loginManager)
302{
45034273 303 // Cache system
5046bcb6 304 $query = $_SERVER['QUERY_STRING'];
01e48f26 305 $cache = new CachedPage(
684e662a 306 $conf->get('config.PAGE_CACHE'),
482d67bd 307 page_url($_SERVER),
93bf0918 308 startsWith($query, 'do=dailyrss') && !$loginManager->isLoggedIn()
01e48f26 309 );
f3b8f9f0
A
310 $cached = $cache->cachedVersion();
311 if (!empty($cached)) {
312 echo $cached;
313 exit;
314 }
9f15ca9e 315
f3b8f9f0
A
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).
9f15ca9e 318 $LINKSDB = new LinkDB(
894a3c4b 319 $conf->get('resource.datastore'),
63ea23c2 320 $loginManager->isLoggedIn(),
520d2957 321 $conf->get('privacy.hide_public_links')
9f15ca9e 322 );
bb8f712d 323
45034273 324 /* Some Shaarlies may have very few links, so we need to look
01878a75 325 back in time until we have enough days ($nb_of_days).
45034273 326 */
f3b8f9f0 327 $nb_of_days = 7; // We take 7 days.
684e662a 328 $today = date('Ymd');
f3b8f9f0
A
329 $days = array();
330
d592daea
A
331 foreach ($LINKSDB as $link) {
332 $day = $link['created']->format('Ymd'); // Extract day (without time)
01878a75 333 if (strcmp($day, $today) < 0) {
f3b8f9f0
A
334 if (empty($days[$day])) {
335 $days[$day] = array();
336 }
d592daea 337 $days[$day][] = $link;
f3b8f9f0
A
338 }
339
340 if (count($days) > $nb_of_days) {
341 break; // Have we collected enough days?
45034273 342 }
45034273 343 }
bb8f712d 344
45034273
SS
345 // Build the RSS feed.
346 header('Content-Type: application/rss+xml; charset=utf-8');
482d67bd 347 $pageaddr = escape(index_url($_SERVER));
45034273 348 echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
f3b8f9f0 349 echo '<channel>';
da10377b 350 echo '<title>Daily - '. $conf->get('general.title') . '</title>';
f3b8f9f0
A
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.
d592daea 357 foreach ($days as $day => $links) {
205a4277 358 $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
482d67bd 359 $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
bb8f712d 360
45034273 361 // We pre-format some fields for proper output.
d592daea 362 foreach ($links as &$link) {
520d2957 363 $link['formatedDescription'] = format_description($link['description']);
d592daea 364 $link['timestamp'] = $link['created']->getTimestamp();
a8e7da01 365 if (is_note($link['url'])) {
d592daea 366 $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
f3b8f9f0 367 }
45034273 368 }
f3b8f9f0 369
45034273 370 // Then build the HTML for this day:
bb8f712d 371 $tpl = new RainTPL;
da10377b 372 $tpl->assign('title', $conf->get('general.title'));
205a4277 373 $tpl->assign('daydate', $dayDate->getTimestamp());
f3b8f9f0
A
374 $tpl->assign('absurl', $absurl);
375 $tpl->assign('links', $links);
205a4277 376 $tpl->assign('rssdate', escape($dayDate->format(DateTime::RSS)));
894a3c4b 377 $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
bf3c9934 378 $tpl->assign('index_url', $pageaddr);
724f1e32 379 $html = $tpl->draw('dailyrss', true);
45034273 380
f3b8f9f0 381 echo $html . PHP_EOL;
bb8f712d 382 }
482d67bd 383 echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
bb8f712d 384
45034273
SS
385 $cache->cache(ob_get_contents());
386 ob_end_flush();
387 exit;
388}
389
38603b24
A
390/**
391 * Show the 'Daily' page.
392 *
278d9ee2
A
393 * @param PageBuilder $pageBuilder Template engine wrapper.
394 * @param LinkDB $LINKSDB LinkDB instance.
395 * @param ConfigManager $conf Configuration Manager instance.
89ccc83b
V
396 * @param PluginManager $pluginManager Plugin Manager instance.
397 * @param LoginManager $loginManager Login Manager instance
38603b24 398 */
89ccc83b 399function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
45034273 400{
5a0045be 401 if (isset($_GET['day'])) {
93bf0918 402 $day = $_GET['day'];
5321f704
A
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'));
5a0045be 411 }
bb8f712d 412
45034273 413 $days = $LINKSDB->days();
5a0045be
WE
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];
45034273 419 }
5a0045be
WE
420 $previousday = '';
421 $nextday = '';
45034273 422
5a0045be
WE
423 if ($i !== false) {
424 if ($i >= 1) {
425 $previousday=$days[$i - 1];
426 }
427 if ($i < count($days) - 1) {
93bf0918 428 $nextday = $days[$i + 1];
5a0045be
WE
429 }
430 }
9186ab95 431 try {
528a6f8a 432 $linksToDisplay = $LINKSDB->filterDay($day);
9186ab95
V
433 } catch (Exception $exc) {
434 error_log($exc);
d1e2f8e5 435 $linksToDisplay = array();
9186ab95
V
436 }
437
45034273 438 // We pre-format some fields for proper output.
93bf0918
V
439 foreach ($linksToDisplay as $key => $link) {
440 $taglist = explode(' ', $link['tags']);
dd62b9ba
SS
441 uasort($taglist, 'strcasecmp');
442 $linksToDisplay[$key]['taglist']=$taglist;
520d2957 443 $linksToDisplay[$key]['formatedDescription'] = format_description($link['description']);
01878a75 444 $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
45034273 445 }
bb8f712d 446
50142efd 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. */
63ea23c2 459 $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
50142efd 460
45034273 461 /* We need to spread the articles on 3 columns.
ad6c27b7 462 I did not want to use a JavaScript lib like http://masonry.desandro.com/
bb8f712d 463 so I manually spread entries with a simple method: I roughly evaluate the
45034273
SS
464 height of a div according to title and description length.
465 */
5a0045be
WE
466 $columns = array(array(), array(), array()); // Entries to display, for each column.
467 $fill = array(0, 0, 0); // Rough estimate of columns fill.
93bf0918 468 foreach ($data['linksToDisplay'] as $key => $link) {
45034273
SS
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.
ad6c27b7 472 // This is not perfect, but it's usually OK.
5a0045be
WE
473 $length = strlen($link['title']) + (342 * strlen($link['description'])) / 836;
474 if ($link['thumbnail']) {
93bf0918 475 $length += 100; // 1 thumbnails roughly takes 100 pixels height.
5a0045be 476 }
45034273 477 // Then put in column which is the less filled:
5a0045be
WE
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;
45034273 482 }
38603b24 483
50142efd 484 $data['cols'] = $columns;
6fc14d53
A
485
486 foreach ($data as $key => $value) {
38603b24 487 $pageBuilder->assign($key, $value);
6fc14d53
A
488 }
489
980efd6c 490 $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
38603b24 491 $pageBuilder->renderPage('daily');
45034273
SS
492 exit;
493}
494
278d9ee2
A
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 */
93bf0918
V
503function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
504{
505 buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
6fc14d53
A
506 $PAGE->renderPage('linklist');
507}
508
278d9ee2
A
509/**
510 * Render HTML page (according to URL parameters and user rights)
511 *
ebd650c0
V
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
44acf706 517 * @param LoginManager $loginManager LoginManager instance
278d9ee2 518 */
44acf706 519function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
45034273 520{
510377d2 521 $updater = new Updater(
894a3c4b 522 read_updates_file($conf->get('resource.updates')),
510377d2 523 $LINKSDB,
278d9ee2 524 $conf,
28f26524
A
525 $loginManager->isLoggedIn(),
526 $_SESSION
510377d2
A
527 );
528 try {
529 $newUpdates = $updater->update();
530 if (! empty($newUpdates)) {
531 write_updates_file(
894a3c4b 532 $conf->get('resource.updates'),
510377d2
A
533 $updater->getDoneUpdates()
534 );
535 }
93bf0918 536 } catch (Exception $e) {
510377d2
A
537 die($e->getMessage());
538 }
539
28f26524 540 $PAGE = new PageBuilder($conf, $_SESSION, $LINKSDB, $sessionManager->generateToken(), $loginManager->isLoggedIn());
141a86c5
A
541 $PAGE->assign('linkcount', count($LINKSDB));
542 $PAGE->assign('privateLinkcount', count_private($LINKSDB));
7fde6de1 543 $PAGE->assign('plugin_errors', $pluginManager->getErrors());
6fc14d53
A
544
545 // Determine which page will be rendered.
546 $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
63ea23c2 547 $targetPage = Router::findPage($query, $_GET, $loginManager->isLoggedIn());
6fc14d53 548
93bf0918 549 if (// if the user isn't logged in
63ea23c2 550 !$loginManager->isLoggedIn() &&
27e21231
WE
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
6fc14d53
A
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(
fea5db7a 568 'includes',
6fc14d53
A
569 'header',
570 'footer',
6fc14d53 571 );
278d9ee2 572
93bf0918 573 foreach ($common_hooks as $name) {
6fc14d53 574 $plugin_data = array();
93bf0918
V
575 $pluginManager->executeHooks(
576 'render_' . $name,
577 $plugin_data,
6fc14d53
A
578 array(
579 'target' => $targetPage,
63ea23c2 580 'loggedin' => $loginManager->isLoggedIn()
6fc14d53
A
581 )
582 );
583 $PAGE->assign('plugins_' . $name, $plugin_data);
584 }
585
45034273 586 // -------- Display login form.
93bf0918
V
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
85c4bdc2
A
592 if (isset($_GET['username'])) {
593 $PAGE->assign('username', escape($_GET['username']));
594 }
93bf0918 595 $PAGE->assign('returnurl', (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
2e07e775
WE
596 // add default state of the 'remember me' checkbox
597 $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
44acf706 598 $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
980efd6c 599 $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
600 $PAGE->renderPage('loginform');
601 exit;
602 }
603 // -------- User wants to logout.
93bf0918 604 if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) {
894a3c4b 605 invalidateCaches($conf->get('resource.page_cache'));
51f0128c 606 $sessionManager->logout();
c689e108 607 setcookie(LoginManager::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH);
45034273
SS
608 header('Location: ?');
609 exit;
610 }
611
612 // -------- Picture wall
93bf0918 613 if ($targetPage == Router::$PAGE_PICWALL) {
b302b3c5
A
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', []);
e85b7a05 617 $PAGE->renderPage('picwall');
1b93137e
A
618 exit;
619 }
620
ad6c27b7 621 // Optionally filter the results:
528a6f8a 622 $links = $LINKSDB->filterSearch($_GET);
822bffce 623 $linksToDisplay = array();
45034273
SS
624
625 // Get only links which have a thumbnail.
28f26524 626 // Note: we do not retrieve thumbnails here, the request is too heavy.
93bf0918 627 foreach ($links as $key => $link) {
1b93137e
A
628 if (isset($link['thumbnail']) && $link['thumbnail'] !== false) {
629 $linksToDisplay[] = $link; // Add to array.
45034273
SS
630 }
631 }
f3db3774 632
6fc14d53 633 $data = array(
6fc14d53
A
634 'linksToDisplay' => $linksToDisplay,
635 );
63ea23c2 636 $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => $loginManager->isLoggedIn()));
6fc14d53
A
637
638 foreach ($data as $key => $value) {
639 $PAGE->assign($key, $value);
640 }
641
7b4fea0e 642
45034273
SS
643 $PAGE->renderPage('picwall');
644 exit;
645 }
646
647 // -------- Tag cloud
93bf0918 648 if ($targetPage == Router::$PAGE_TAGCLOUD) {
9d4736a3 649 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
aa4797ba 650 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
6ccd0b21 651 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
a037ac69 652
45034273
SS
653 // We sort tags alphabetically, then choose a font size according to count.
654 // First, find max value.
f1e96a06
A
655 $maxcount = 0;
656 foreach ($tags as $value) {
657 $maxcount = max($maxcount, $value);
658 }
659
f32ec5fb 660 alphabetical_sort($tags, false, true);
f1e96a06 661
b0128609 662 $tagList = array();
93bf0918 663 foreach ($tags as $key => $value) {
49cc8e5d
LC
664 if (in_array($key, $filteringTags)) {
665 continue;
666 }
b0128609
A
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 );
45034273 675 }
6fc14d53 676
980efd6c 677 $searchTags = implode(' ', escape($filteringTags));
6fc14d53 678 $data = array(
980efd6c 679 'search_tags' => $searchTags,
6fc14d53
A
680 'tags' => $tagList,
681 );
63ea23c2 682 $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
6fc14d53
A
683
684 foreach ($data as $key => $value) {
685 $PAGE->assign($key, $value);
686 }
687
980efd6c
A
688 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
689 $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
5893529c 690 $PAGE->renderPage('tag.cloud');
bb8f712d 691 exit;
45034273
SS
692 }
693
49cc8e5d 694 // -------- Tag list
93bf0918 695 if ($targetPage == Router::$PAGE_TAGLIST) {
9d4736a3 696 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
aa4797ba
A
697 $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
698 $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
49cc8e5d
LC
699 foreach ($filteringTags as $tag) {
700 if (array_key_exists($tag, $tags)) {
701 unset($tags[$tag]);
702 }
703 }
aa4797ba
A
704
705 if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
706 alphabetical_sort($tags, false, true);
707 }
708
980efd6c 709 $searchTags = implode(' ', escape($filteringTags));
aa4797ba 710 $data = [
980efd6c 711 'search_tags' => $searchTags,
aa4797ba
A
712 'tags' => $tags,
713 ];
63ea23c2 714 $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
aa4797ba
A
715
716 foreach ($data as $key => $value) {
717 $PAGE->assign($key, $value);
718 }
719
980efd6c
A
720 $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
721 $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
aa4797ba 722 $PAGE->renderPage('tag.list');
bb8f712d 723 exit;
45034273
SS
724 }
725
38603b24
A
726 // Daily page.
727 if ($targetPage == Router::$PAGE_DAILY) {
89ccc83b 728 showDaily($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
38603b24
A
729 }
730
82e36802
A
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(
894a3c4b 739 $conf->get('resource.page_cache'),
82e36802 740 page_url($_SERVER),
93bf0918 741 startsWith($query, 'do='. $targetPage) && !$loginManager->isLoggedIn()
82e36802
A
742 );
743 $cached = $cache->cachedVersion();
5f143b72 744 if (!empty($cached)) {
82e36802
A
745 echo $cached;
746 exit;
747 }
69c474b9 748
82e36802 749 // Generate data.
63ea23c2 750 $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, $loginManager->isLoggedIn());
82e36802 751 $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0)));
63ea23c2 752 $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
894a3c4b 753 $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
82e36802
A
754 $data = $feedGenerator->buildData();
755
756 // Process plugin hook.
82e36802 757 $pluginManager->executeHooks('render_feed', $data, array(
63ea23c2 758 'loggedin' => $loginManager->isLoggedIn(),
82e36802
A
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;
e67712ba
A
768 }
769
18e67967 770 // Display opensearch plugin (XML)
8f8113b9
A
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
45034273 778 // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
93bf0918 779 if (isset($_GET['addtag'])) {
45034273 780 // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
93bf0918
V
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);
732e683b 787
775803a0
A
788 // Prevent redirection loop
789 if (isset($params['addtag'])) {
790 unset($params['addtag']);
791 }
792
732e683b
FE
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
6ac95d9c
A
795 if (isset($params['searchtags'])) {
796 $current_tags = explode(' ', $params['searchtags']);
797 } else {
798 $current_tags = array();
799 }
732e683b
FE
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']);
93bf0918 810 } elseif ($addtag) {
732e683b
FE
811 $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
812 }
813
9d9f6d75
V
814 // We also remove page (keeping the same page has no sense, since the
815 // results are different)
816 unset($params['page']);
817
45034273
SS
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=...)
775803a0 823 if (isset($_GET['removetag'])) {
45034273 824 // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
775803a0
A
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'])) {
822bffce 839 $tags = explode(' ', $params['searchtags']);
2c75f8e7
A
840 // Remove value from array $tags.
841 $tags = array_diff($tags, array($_GET['removetag']));
93bf0918 842 $params['searchtags'] = implode(' ', $tags);
2c75f8e7
A
843
844 if (empty($params['searchtags'])) {
775803a0 845 unset($params['searchtags']);
775803a0 846 }
2c75f8e7 847
9d9f6d75
V
848 // We also remove page (keeping the same page has no sense, since
849 // the results are different)
850 unset($params['page']);
45034273
SS
851 }
852 header('Location: ?'.http_build_query($params));
853 exit;
854 }
855
856 // -------- User wants to change the number of links per page (linksperpage=...)
775803a0
A
857 if (isset($_GET['linksperpage'])) {
858 if (is_numeric($_GET['linksperpage'])) {
859 $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
860 }
861
8bbf02e0
A
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);
45034273
SS
868 exit;
869 }
bb8f712d 870
45034273 871 // -------- User wants to see only private links (toggle)
9d4736a3 872 if (isset($_GET['visibility'])) {
9d4736a3 873 if ($_GET['visibility'] === 'private') {
d2f6d909
A
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 }
d2d4f993 881 } elseif ($_GET['visibility'] === 'public') {
d2f6d909
A
882 if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
883 // See only public links
884 $_SESSION['visibility'] = 'public';
885 } else {
886 unset($_SESSION['visibility']);
887 }
45034273 888 }
775803a0 889
8bbf02e0 890 if (! empty($_SERVER['HTTP_REFERER'])) {
9d4736a3 891 $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
8bbf02e0
A
892 } else {
893 $location = '?';
894 }
895 header('Location: '. $location);
45034273
SS
896 exit;
897 }
898
f210d94f
LC
899 // -------- User wants to see only untagged links (toggle)
900 if (isset($_GET['untaggedonly'])) {
c4925c1f 901 $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
f210d94f
LC
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);
45034273
SS
909 exit;
910 }
911
912 // -------- Handle other actions allowed for non-logged in users:
93bf0918 913 if (!$loginManager->isLoggedIn()) {
ad6c27b7 914 // User tries to post new link but is not logged in:
45034273 915 // Show login screen, then redirect to ?post=...
93bf0918 916 if (isset($_GET['post'])) {
0b04f797 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 );
45034273
SS
924 exit;
925 }
aedc912d 926
63ea23c2 927 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
5fbabbb9
A
928 if (isset($_GET['edit_link'])) {
929 header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
930 exit;
931 }
932
ad6c27b7 933 exit; // Never remove this one! All operations below are reserved for logged in user.
45034273
SS
934 }
935
936 // -------- All other functions are reserved for the registered user:
937
938 // -------- Display the Tools menu if requested (import/export/bookmarklet...)
93bf0918 939 if ($targetPage == Router::$PAGE_TOOLS) {
a3130d2c 940 $data = [
6fc14d53 941 'pageabsaddr' => index_url($_SERVER),
a3130d2c
A
942 'sslenabled' => is_https($_SERVER),
943 ];
6fc14d53
A
944 $pluginManager->executeHooks('render_tools', $data);
945
946 foreach ($data as $key => $value) {
947 $PAGE->assign($key, $value);
948 }
949
980efd6c 950 $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
951 $PAGE->renderPage('tools');
952 exit;
953 }
954
955 // -------- User wants to change his/her password.
93bf0918 956 if ($targetPage == Router::$PAGE_CHANGEPASSWORD) {
894a3c4b 957 if ($conf->get('security.open_shaarli')) {
12266213 958 die(t('You are not supposed to change a password on an Open Shaarli.'));
684e662a
A
959 }
960
93bf0918
V
961 if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) {
962 if (!$sessionManager->checkToken($_POST['token'])) {
963 die(t('Wrong token.')); // Go away!
964 }
45034273
SS
965
966 // Make sure old password is correct.
9d9f6d75
V
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>';
ebd650c0 974 exit;
12266213 975 }
45034273 976 // Save new password
684e662a 977 // Salt renders rainbow-tables attacks useless.
da10377b 978 $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
9d9f6d75
V
979 $conf->set(
980 'credentials.hash',
981 sha1(
982 $_POST['setpassword']
983 . $conf->get('credentials.login')
984 . $conf->get('credentials.salt')
985 )
986 );
dd484b90 987 try {
63ea23c2 988 $conf->write($loginManager->isLoggedIn());
93bf0918 989 } catch (Exception $e) {
dd484b90
A
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 }
12266213 999 echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
45034273 1000 exit;
93bf0918
V
1001 } else {
1002 // show the change password form.
980efd6c 1003 $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1004 $PAGE->renderPage('changepassword');
1005 exit;
1006 }
1007 }
1008
1009 // -------- User wants to change configuration
93bf0918
V
1010 if ($targetPage == Router::$PAGE_CONFIGURE) {
1011 if (!empty($_POST['title'])) {
ebd650c0 1012 if (!$sessionManager->checkToken($_POST['token'])) {
12266213 1013 die(t('Wrong token.')); // Go away!
12ff86c9 1014 }
45034273 1015 $tz = 'UTC';
12ff86c9
A
1016 if (!empty($_POST['continent']) && !empty($_POST['city'])
1017 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1018 ) {
1019 $tz = $_POST['continent'] . '/' . $_POST['city'];
1020 }
da10377b 1021 $conf->set('general.timezone', $tz);
7f179985
A
1022 $conf->set('general.title', escape($_POST['title']));
1023 $conf->set('general.header_link', escape($_POST['titleLink']));
6a487252 1024 $conf->set('general.retrieve_description', !empty($_POST['retrieveDescription']));
adc4aee8 1025 $conf->set('resource.theme', escape($_POST['theme']));
da10377b 1026 $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
894a3c4b
A
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']));
76be95e1 1031 $conf->set('api.enabled', !empty($_POST['enableApi']));
cbfdcff2 1032 $conf->set('api.secret', escape($_POST['apiSecret']));
f39580c6
A
1033 $conf->set('translation.language', escape($_POST['language']));
1034
b302b3c5 1035 $thumbnailsMode = extension_loaded('gd') ? $_POST['enableThumbnails'] : Thumbnailer::MODE_NONE;
7b4fea0e
A
1036 if ($thumbnailsMode !== Thumbnailer::MODE_NONE
1037 && $thumbnailsMode !== $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE)
1038 ) {
28f26524 1039 $_SESSION['warnings'][] = t(
9d9f6d75
V
1040 'You have enabled or changed thumbnails mode. '
1041 .'<a href="?do=thumbs_update">Please synchronize them</a>.'
28f26524
A
1042 );
1043 }
b302b3c5 1044 $conf->set('thumbnails.mode', $thumbnailsMode);
f39580c6 1045
dd484b90 1046 try {
63ea23c2 1047 $conf->write($loginManager->isLoggedIn());
4306b184 1048 $history->updateSettings();
adc4aee8 1049 invalidateCaches($conf->get('resource.page_cache'));
93bf0918 1050 } catch (Exception $e) {
dd484b90
A
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.
684e662a 1057 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
dd484b90
A
1058 exit;
1059 }
12266213 1060 echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
45034273 1061 exit;
93bf0918
V
1062 } else {
1063 // Show the configuration form.
da10377b 1064 $PAGE->assign('title', $conf->get('general.title'));
adc4aee8 1065 $PAGE->assign('theme', $conf->get('resource.theme'));
a0df0651 1066 $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl')));
ae3aa968
A
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);
6a487252 1073 $PAGE->assign('retrieve_description', $conf->get('general.retrieve_description'));
894a3c4b 1074 $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
2e193ad3 1075 $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
894a3c4b
A
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));
cbfdcff2
A
1079 $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
1080 $PAGE->assign('api_secret', $conf->get('api.secret'));
f39580c6 1081 $PAGE->assign('languages', Languages::getAvailableLanguages());
787faa42 1082 $PAGE->assign('gd_enabled', extension_loaded('gd'));
b302b3c5 1083 $PAGE->assign('thumbnails_mode', $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE));
980efd6c 1084 $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1085 $PAGE->renderPage('configure');
1086 exit;
1087 }
1088 }
1089
1090 // -------- User wants to rename a tag or delete it
93bf0918 1091 if ($targetPage == Router::$PAGE_CHANGETAG) {
6a6aa2b9 1092 if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
aa4797ba 1093 $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
980efd6c 1094 $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1095 $PAGE->renderPage('changetag');
1096 exit;
1097 }
6a6aa2b9 1098
ebd650c0 1099 if (!$sessionManager->checkToken($_POST['token'])) {
12266213 1100 die(t('Wrong token.'));
6a6aa2b9 1101 }
45034273 1102
4fa9a3c5
A
1103 $toTag = isset($_POST['totag']) ? escape($_POST['totag']) : null;
1104 $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), $toTag);
d99aef53 1105 $LINKSDB->save($conf->get('resource.page_cache'));
3b67b222
A
1106 foreach ($alteredLinks as $link) {
1107 $history->updateLink($link);
45034273 1108 }
3b67b222 1109 $delete = empty($_POST['totag']);
d99aef53 1110 $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
f39580c6 1111 $count = count($alteredLinks);
d99aef53 1112 $alert = $delete
f39580c6
A
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);
d99aef53
A
1115 echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
1116 exit;
45034273
SS
1117 }
1118
ad6c27b7 1119 // -------- User wants to add a link without using the bookmarklet: Show form.
93bf0918 1120 if ($targetPage == Router::$PAGE_ADDLINK) {
980efd6c 1121 $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1122 $PAGE->renderPage('addlink');
1123 exit;
1124 }
1125
1126 // -------- User clicked the "Save" button when editing a link: Save link to database.
93bf0918 1127 if (isset($_POST['save_edit'])) {
5a23950c 1128 // Go away!
ebd650c0 1129 if (! $sessionManager->checkToken($_POST['token'])) {
12266213 1130 die(t('Wrong token.'));
5a23950c 1131 }
01878a75
A
1132
1133 // lf_id should only be present if the link exists.
b712ab0a 1134 $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
81cae5f5 1135 $link['id'] = $id;
01878a75
A
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
1cafacfe 1139 // See: https://shaarli.readthedocs.io/en/master/guides/various-hacks/#changing-the-timestamp-for-a-shaare
01878a75 1140 $linkdate = escape($_POST['lf_linkdate']);
81cae5f5 1141 $link['created'] = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
01878a75
A
1142 if (isset($LINKSDB[$id])) {
1143 // Edit
81cae5f5
A
1144 $link['updated'] = new DateTime();
1145 $link['shorturl'] = $LINKSDB[$id]['shorturl'];
1146 $link['sticky'] = isset($LINKSDB[$id]['sticky']) ? $LINKSDB[$id]['sticky'] : false;
4306b184 1147 $new = false;
01878a75
A
1148 } else {
1149 // New link
81cae5f5
A
1150 $link['updated'] = null;
1151 $link['shorturl'] = link_small_hash($link['created'], $id);
1152 $link['sticky'] = false;
4306b184 1153 $new = true;
01878a75
A
1154 }
1155
5a23950c
A
1156 // Remove multiple spaces.
1157 $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
ce354bf1
A
1158 // Remove first '-' char in tags.
1159 $tags = preg_replace('/(^| )\-/', '$1', $tags);
5a23950c
A
1160 // Remove duplicates.
1161 $tags = implode(' ', array_unique(explode(' ', $tags)));
9646b7da 1162
c27f2f36
A
1163 if (empty(trim($_POST['lf_url']))) {
1164 $_POST['lf_url'] = '?' . smallHash($linkdate . $id);
5a23950c 1165 }
86ceea05 1166 $url = whitelist_protocols(trim($_POST['lf_url']), $conf->get('security.allowed_protocols'));
5a23950c 1167
81cae5f5 1168 $link = array_merge($link, [
5a23950c
A
1169 'title' => trim($_POST['lf_title']),
1170 'url' => $url,
ed853da7 1171 'description' => $_POST['lf_description'],
5a23950c 1172 'private' => (isset($_POST['lf_private']) ? 1 : 0),
d592daea 1173 'tags' => str_replace(',', ' ', $tags),
81cae5f5 1174 ]);
01878a75 1175
5a23950c
A
1176 // If title is empty, use the URL as title.
1177 if ($link['title'] == '') {
1178 $link['title'] = $link['url'];
1179 }
6fc14d53 1180
a8e7da01
A
1181 if ($conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE
1182 && ! is_note($link['url'])
1183 ) {
1b93137e
A
1184 $thumbnailer = new Thumbnailer($conf);
1185 $link['thumbnail'] = $thumbnailer->get($url);
1186 }
1187
1cc5eaf9
V
1188 $link['sticky'] = isset($link['sticky']) ? $link['sticky'] : false;
1189
6fc14d53
A
1190 $pluginManager->executeHooks('save_link', $link);
1191
01878a75 1192 $LINKSDB[$id] = $link;
f21abf32 1193 $LINKSDB->save($conf->get('resource.page_cache'));
4306b184
A
1194 if ($new) {
1195 $history->addLink($link);
1196 } else {
1197 $history->updateLink($link);
1198 }
45034273
SS
1199
1200 // If we are called from the bookmarklet, we must close the popup:
d01c2342
A
1201 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1202 echo '<script>self.close();</script>';
1203 exit;
1204 }
1205
fd50e14c 1206 $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?';
775803a0 1207 $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
5a23950c 1208 // Scroll to the link which has been edited.
d592daea 1209 $location .= '#' . $link['shorturl'];
5a23950c
A
1210 // After saving the link, redirect to the page the user was on.
1211 header('Location: '. $location);
45034273
SS
1212 exit;
1213 }
1214
1215 // -------- User clicked the "Cancel" button when editing a link.
93bf0918 1216 if (isset($_POST['cancel_edit'])) {
b712ab0a
A
1217 $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
1218 if (! isset($LINKSDB[$id])) {
1219 header('Location: ?');
1220 }
ad6c27b7 1221 // If we are called from the bookmarklet, we must close the popup:
93bf0918
V
1222 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1223 echo '<script>self.close();</script>';
1224 exit;
1225 }
b712ab0a 1226 $link = $LINKSDB[$id];
45034273 1227 $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
01878a75 1228 // Scroll to the link which has been edited.
d592daea 1229 $returnurl .= '#'. $link['shorturl'];
775803a0 1230 $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
45034273
SS
1231 header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
1232 exit;
1233 }
1234
ad6c27b7 1235 // -------- User clicked the "Delete" button when editing a link: Delete link from database.
93bf0918 1236 if ($targetPage == Router::$PAGE_DELETELINK) {
ebd650c0 1237 if (! $sessionManager->checkToken($_GET['token'])) {
12266213 1238 die(t('Wrong token.'));
f4ebd5fe 1239 }
01878a75 1240
a74f52a8
WE
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))));
29a837f3 1245 } else {
a74f52a8
WE
1246 // only a single id provided
1247 $ids = [$ids];
1248 }
1249 // assert at least one id is given
93bf0918 1250 if (!count($ids)) {
a74f52a8 1251 die('no id provided');
29a837f3
A
1252 }
1253 foreach ($ids as $id) {
1254 $id = (int) escape($id);
1255 $link = $LINKSDB[$id];
1256 $pluginManager->executeHooks('delete_link', $link);
b54faf4f 1257 $history->deleteLink($link);
29a837f3
A
1258 unset($LINKSDB[$id]);
1259 }
f4ebd5fe 1260 $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
45034273
SS
1261
1262 // If we are called from the bookmarklet, we must close the popup:
93bf0918
V
1263 if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
1264 echo '<script>self.close();</script>';
1265 exit;
1266 }
95e5add4
A
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(
93bf0918
V
1272 $_SERVER['HTTP_REFERER'],
1273 $_SERVER['HTTP_HOST'],
1274 ['delete_link', 'edit_link', $link['shorturl']]
95e5add4 1275 );
d528433d 1276 }
1277
1278 header('Location: ' . $location); // After deleting the link, redirect to appropriate location
45034273
SS
1279 exit;
1280 }
1281
8d03f705
A
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
45034273
SS
1324 exit;
1325 }
1326
1327 // -------- User clicked the "EDIT" button on a link: Display link edit form.
93bf0918 1328 if (isset($_GET['edit_link'])) {
01878a75
A
1329 $id = (int) escape($_GET['edit_link']);
1330 $link = $LINKSDB[$id]; // Read database
93bf0918
V
1331 if (!$link) {
1332 header('Location: ?');
1333 exit;
1334 } // Link not found in database.
d592daea 1335 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
6fc14d53 1336 $data = array(
6fc14d53
A
1337 'link' => $link,
1338 'link_is_new' => false,
6fc14d53 1339 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
6ccd0b21 1340 'tags' => $LINKSDB->linksCountPerTag(),
6fc14d53
A
1341 );
1342 $pluginManager->executeHooks('render_editlink', $data);
1343
1344 foreach ($data as $key => $value) {
1345 $PAGE->assign($key, $value);
1346 }
1347
980efd6c 1348 $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1349 $PAGE->renderPage('editlink');
1350 exit;
1351 }
1352
1353 // -------- User want to post a new link: Display link edit form.
d9d776af 1354 if (isset($_GET['post'])) {
ce7b0b64 1355 $url = cleanup_url($_GET['post']);
45034273
SS
1356
1357 $link_is_new = false;
9e1724f1 1358 // Check if URL is not already in database (in this case, we will edit the existing link)
ef591e7e 1359 $link = $LINKSDB->getLinkFromUrl($url);
93bf0918 1360 if (! $link) {
9e1724f1 1361 $link_is_new = true;
d592daea 1362 $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT));
9e1724f1 1363 // Get title if it was provided in URL (by the bookmarklet).
739dc243 1364 $title = empty($_GET['title']) ? '' : escape($_GET['title']);
9e1724f1 1365 // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
739dc243
A
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;
9d9f6d75
V
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.)
ef591e7e 1372 if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
6a487252 1373 $retrieveDescription = $conf->get('general.retrieve_description');
451314eb 1374 // Short timeout to keep the application responsive
d65342e3 1375 // The callback will fill $charset and $title with data from the downloaded page.
4ff3ed1c
A
1376 get_http_response(
1377 $url,
4ff3ed1c 1378 $conf->get('general.download_timeout', 30),
8d2cac1b 1379 $conf->get('general.download_max_size', 4194304),
6a487252 1380 get_curl_download_callback($charset, $title, $description, $tags, $retrieveDescription)
4ff3ed1c 1381 );
d65342e3
A
1382 if (! empty($title) && strtolower($charset) != 'utf-8') {
1383 $title = mb_convert_encoding($title, 'utf-8', $charset);
9e1724f1 1384 }
45034273 1385 }
1557cefb 1386
9e1724f1 1387 if ($url == '') {
d592daea 1388 $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
f39580c6 1389 $title = $conf->get('general.default_note_title', t('Note: '));
27646ca5 1390 }
ce7b0b64
A
1391 $url = escape($url);
1392 $title = escape($title);
1557cefb 1393
9e1724f1
A
1394 $link = array(
1395 'linkdate' => $linkdate,
1396 'title' => $title,
ef591e7e 1397 'url' => $url,
9e1724f1
A
1398 'description' => $description,
1399 'tags' => $tags,
807cade6 1400 'private' => $private,
9e1724f1 1401 );
01878a75 1402 } else {
d592daea 1403 $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
45034273
SS
1404 }
1405
6fc14d53 1406 $data = array(
6fc14d53
A
1407 'link' => $link,
1408 'link_is_new' => $link_is_new,
6fc14d53
A
1409 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
1410 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
6ccd0b21 1411 'tags' => $LINKSDB->linksCountPerTag(),
cdbc8180 1412 'default_private_links' => $conf->get('privacy.default_private_links', false),
6fc14d53
A
1413 );
1414 $pluginManager->executeHooks('render_editlink', $data);
1415
1416 foreach ($data as $key => $value) {
1417 $PAGE->assign($key, $value);
1418 }
1419
980efd6c 1420 $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1421 $PAGE->renderPage('editlink');
1422 exit;
1423 }
1424
4154c25b
A
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
cd5327be 1444 if ($targetPage == Router::$PAGE_EXPORT) {
bb4a23aa
V
1445 // Export links as a Netscape Bookmarks file
1446
cd5327be 1447 if (empty($_GET['selection'])) {
980efd6c 1448 $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
45034273
SS
1449 $PAGE->renderPage('export');
1450 exit;
1451 }
45034273 1452
cd5327be
V
1453 // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
1454 $selection = $_GET['selection'];
bb4a23aa
V
1455 if (isset($_GET['prepend_note_url'])) {
1456 $prependNoteUrl = $_GET['prepend_note_url'];
1457 } else {
1458 $prependNoteUrl = false;
1459 }
1460
cd5327be
V
1461 try {
1462 $PAGE->assign(
1463 'links',
bb4a23aa
V
1464 NetscapeBookmarkUtils::filterAndFormat(
1465 $LINKSDB,
1466 $selection,
1467 $prependNoteUrl,
1468 index_url($_SERVER)
1469 )
cd5327be
V
1470 );
1471 } catch (Exception $exc) {
1472 header('Content-Type: text/plain; charset=utf-8');
1473 echo $exc->getMessage();
1474 exit;
45034273 1475 }
cd5327be
V
1476 $now = new DateTime();
1477 header('Content-Type: text/html; charset=utf-8');
1478 header(
1479 'Content-disposition: attachment; filename=bookmarks_'
93bf0918 1480 .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html'
cd5327be
V
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;
45034273
SS
1487 }
1488
a973afea
V
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
6a19124a
A
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 );
980efd6c 1510 $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
a973afea 1511 $PAGE->renderPage('import');
45034273
SS
1512 exit;
1513 }
45034273 1514
a973afea
V
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.
12266213
A
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>';
a973afea
V
1526 exit;
1527 }
ebd650c0 1528 if (! $sessionManager->checkToken($_POST['token'])) {
a973afea
V
1529 die('Wrong token.');
1530 }
1531 $status = NetscapeBookmarkUtils::import(
1532 $_POST,
1533 $_FILES,
1534 $LINKSDB,
4306b184
A
1535 $conf,
1536 $history
a973afea
V
1537 );
1538 echo '<script>alert("'.$status.'");document.location=\'?do='
1539 .Router::$PAGE_IMPORT .'\';</script>';
45034273
SS
1540 exit;
1541 }
1542
dea0ba28
A
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.
93bf0918
V
1548 $enabledPlugins = array_filter($pluginMeta, function ($v) {
1549 return $v['order'] !== false;
1550 });
dea0ba28 1551 // Load parameters.
684e662a 1552 $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
dea0ba28
A
1553 uasort(
1554 $enabledPlugins,
93bf0918
V
1555 function ($a, $b) {
1556 return $a['order'] - $b['order'];
1557 }
dea0ba28 1558 );
93bf0918
V
1559 $disabledPlugins = array_filter($pluginMeta, function ($v) {
1560 return $v['order'] === false;
1561 });
dea0ba28
A
1562
1563 $PAGE->assign('enabledPlugins', $enabledPlugins);
1564 $PAGE->assign('disabledPlugins', $disabledPlugins);
980efd6c 1565 $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
dea0ba28
A
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'])) {
a5a0c039 1574 $pluginManager->executeHooks('save_plugin_parameters', $_POST);
dea0ba28
A
1575 unset($_POST['parameters_form']);
1576 foreach ($_POST as $param => $value) {
684e662a 1577 $conf->set('plugins.'. $param, escape($value));
dea0ba28 1578 }
93bf0918 1579 } else {
da10377b 1580 $conf->set('general.enabled_plugins', save_plugin_config($_POST));
dea0ba28 1581 }
63ea23c2 1582 $conf->write($loginManager->isLoggedIn());
b86aeccf 1583 $history->updateSettings();
93bf0918 1584 } catch (Exception $e) {
dea0ba28
A
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.
9d9f6d75
V
1591 echo '<script>alert("'
1592 . $e->getMessage()
1593 .'");document.location=\'?do='
1594 . Router::$PAGE_PLUGINSADMIN
1595 .'\';</script>';
dea0ba28
A
1596 exit;
1597 }
1598 header('Location: ?do='. Router::$PAGE_PLUGINSADMIN);
1599 exit;
1600 }
1601
986a5210
A
1602 // Get a fresh token
1603 if ($targetPage == Router::$GET_TOKEN) {
1604 header('Content-Type:text/plain');
ebd650c0 1605 echo $sessionManager->generateToken($conf);
986a5210
A
1606 exit;
1607 }
1608
28f26524
A
1609 // -------- Thumbnails Update
1610 if ($targetPage == Router::$PAGE_THUMBS_UPDATE) {
1611 $ids = [];
1612 foreach ($LINKSDB as $link) {
1613 // A note or not HTTP(S)
a8e7da01 1614 if (is_note($link['url']) || ! startsWith(strtolower($link['url']), 'http')) {
28f26524
A
1615 continue;
1616 }
1617 $ids[] = $link['id'];
1618 }
1619 $PAGE->assign('ids', $ids);
7b4fea0e 1620 $PAGE->assign('pagetitle', t('Thumbnails update') .' - '. $conf->get('general.title', 'Shaarli'));
28f26524
A
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
45034273 1646 // -------- Otherwise, simply display search form and links:
63ea23c2 1647 showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
45034273
SS
1648 exit;
1649}
1650
528a6f8a
A
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 *
278d9ee2
A
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.
63ea23c2 1659 * @param LoginManager $loginManager LoginManager instance
528a6f8a 1660 */
63ea23c2 1661function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
45034273 1662{
528a6f8a 1663 // Used in templates
7d86f40b
A
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 }
b3051a6a 1673 $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
822bffce 1674
528a6f8a
A
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());
45034273
SS
1682 exit;
1683 }
528a6f8a
A
1684 } else {
1685 // Filter links according search parameters.
9d4736a3 1686 $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
7d86f40b
A
1687 $request = [
1688 'searchtags' => $searchtags,
1689 'searchterm' => $searchterm,
1690 ];
f210d94f 1691 $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
45034273
SS
1692 }
1693
1694 // ---- Handle paging.
822bffce
A
1695 $keys = array();
1696 foreach ($linksToDisplay as $key => $value) {
1697 $keys[] = $key;
1698 }
45034273 1699
45034273 1700 // Select articles according to paging.
822bffce
A
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'];
1b93137e 1709
b302b3c5
A
1710 $thumbnailsEnabled = $conf->get('thumbnails.mode', Thumbnailer::MODE_NONE) !== Thumbnailer::MODE_NONE;
1711 if ($thumbnailsEnabled) {
1b93137e
A
1712 $thumbnailer = new Thumbnailer($conf);
1713 }
1714
822bffce 1715 $linkDisp = array();
93bf0918 1716 while ($i<$end && $i<count($keys)) {
45034273 1717 $link = $linksToDisplay[$keys[$i]];
520d2957 1718 $link['description'] = format_description($link['description']);
822bffce
A
1719 $classLi = ($i % 2) != 0 ? '' : 'publicLinkHightLight';
1720 $link['class'] = $link['private'] == 0 ? $classLi : 'private';
01878a75 1721 $link['timestamp'] = $link['created']->getTimestamp();
9646b7da 1722 if (! empty($link['updated'])) {
01878a75 1723 $link['updated_timestamp'] = $link['updated']->getTimestamp();
9646b7da
A
1724 } else {
1725 $link['updated_timestamp'] = '';
1726 }
b3051a6a 1727 $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY);
a5752e77 1728 uasort($taglist, 'strcasecmp');
822bffce 1729 $link['taglist'] = $taglist;
1b93137e 1730
b5c368b8 1731 // Logged in, thumbnails enabled, not a note,
1b93137e 1732 // and (never retrieved yet or no valid cache file)
b5c368b8 1733 if ($loginManager->isLoggedIn() && $thumbnailsEnabled && $link['url'][0] != '?'
1b93137e
A
1734 && (! isset($link['thumbnail']) || ($link['thumbnail'] !== false && ! is_file($link['thumbnail'])))
1735 ) {
e85b7a05
A
1736 $elem = $LINKSDB[$keys[$i]];
1737 $elem['thumbnail'] = $thumbnailer->get($link['url']);
1738 $LINKSDB[$keys[$i]] = $elem;
1b93137e 1739 $updateDB = true;
787faa42 1740 $link['thumbnail'] = $elem['thumbnail'];
1b93137e
A
1741 }
1742
822bffce 1743 // Check for both signs of a note: starting with ? and 7 chars long.
1b93137e 1744 if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
822bffce 1745 $link['url'] = index_url($_SERVER) . $link['url'];
b47f515a 1746 }
d33c5d4c 1747
45034273
SS
1748 $linkDisp[$keys[$i]] = $link;
1749 $i++;
1750 }
bb8f712d 1751
1b93137e
A
1752 // If we retrieved new thumbnails, we update the database.
1753 if (!empty($updateDB)) {
1754 $LINKSDB->save($conf->get('resource.page_cache'));
1755 }
1756
45034273 1757 // Compute paging navigation
7d86f40b 1758 $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
c51fae92 1759 $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
822bffce
A
1760 $previous_page_url = '';
1761 if ($i != count($keys)) {
c51fae92 1762 $previous_page_url = '?page=' . ($page+1) . $searchtermUrl . $searchtagsUrl;
822bffce
A
1763 }
1764 $next_page_url='';
1765 if ($page>1) {
c51fae92 1766 $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
822bffce 1767 }
45034273 1768
45034273 1769 // Fill all template fields.
6fc14d53 1770 $data = array(
6fc14d53
A
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),
c51fae92
A
1776 'search_term' => $searchterm,
1777 'search_tags' => $searchtags,
9d4736a3 1778 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
6fc14d53 1779 'links' => $linkDisp,
6fc14d53 1780 );
97ef33bb
A
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');
980efd6c
A
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');
18cca483 1795 }
6fc14d53 1796
63ea23c2 1797 $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
6fc14d53
A
1798
1799 foreach ($data as $key => $value) {
1800 $PAGE->assign($key, $value);
1801 }
1802
45034273
SS
1803 return;
1804}
1805
278d9ee2
A
1806/**
1807 * Installation
1808 * This function should NEVER be called if the file data/config.php exists.
1809 *
ebd650c0
V
1810 * @param ConfigManager $conf Configuration Manager instance.
1811 * @param SessionManager $sessionManager SessionManager instance
cad4251a 1812 * @param LoginManager $loginManager LoginManager instance
278d9ee2 1813 */
93bf0918
V
1814function install($conf, $sessionManager, $loginManager)
1815{
45034273 1816 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
93bf0918
V
1817 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
1818 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
1819 }
45034273 1820
f37664a2
SS
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.)
9d9f6d75
V
1825 if (isset($_GET['test_session'])
1826 && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
12266213
A
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>';
f37664a2
SS
1840 die;
1841 }
93bf0918
V
1842 if (!isset($_SESSION['session_tested'])) {
1843 // Step 1 : Try to store data in session and reload page.
f37664a2 1844 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
482d67bd 1845 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
f37664a2 1846 }
93bf0918
V
1847 if (isset($_GET['test_session'])) {
1848 // Step 3: Sessions are OK. Remove test parameter from URL.
482d67bd 1849 header('Location: '.index_url($_SERVER));
f37664a2
SS
1850 }
1851
1852
93bf0918 1853 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
45034273 1854 $tz = 'UTC';
12ff86c9
A
1855 if (!empty($_POST['continent']) && !empty($_POST['city'])
1856 && isTimeZoneValid($_POST['continent'], $_POST['city'])
1857 ) {
1858 $tz = $_POST['continent'].'/'.$_POST['city'];
d1e2f8e5 1859 }
da10377b 1860 $conf->set('general.timezone', $tz);
684e662a 1861 $login = $_POST['setlogin'];
da10377b 1862 $conf->set('credentials.login', $login);
684e662a 1863 $salt = sha1(uniqid('', true) .'_'. mt_rand());
da10377b
A
1864 $conf->set('credentials.salt', $salt);
1865 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
684e662a 1866 if (!empty($_POST['title'])) {
7f179985 1867 $conf->set('general.title', escape($_POST['title']));
684e662a 1868 } else {
da10377b 1869 $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
684e662a 1870 }
f39580c6 1871 $conf->set('translation.language', escape($_POST['language']));
894a3c4b 1872 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
cbfdcff2
A
1873 $conf->set('api.enabled', !empty($_POST['enableApi']));
1874 $conf->set(
1875 'api.secret',
1876 generate_api_secret(
e3a430ba
A
1877 $conf->get('credentials.login'),
1878 $conf->get('credentials.salt')
cbfdcff2
A
1879 )
1880 );
dd484b90 1881 try {
684e662a 1882 // Everything is ok, let's create config file.
63ea23c2 1883 $conf->write($loginManager->isLoggedIn());
93bf0918 1884 } catch (Exception $e) {
dd484b90 1885 error_log(
93bf0918 1886 'ERROR while writing config file after installation.' . PHP_EOL .
dd484b90 1887 $e->getMessage()
93bf0918 1888 );
dd484b90
A
1889
1890 // TODO: do not handle exceptions/errors in JS.
1891 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
1892 exit;
1893 }
9d9f6d75
V
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>';
45034273
SS
1898 exit;
1899 }
1900
28f26524 1901 $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
ae3aa968
A
1902 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
1903 $PAGE->assign('continents', $continents);
1904 $PAGE->assign('cities', $cities);
f39580c6 1905 $PAGE->assign('languages', Languages::getAvailableLanguages());
45034273
SS
1906 $PAGE->renderPage('install');
1907 exit;
1908}
1909
bf3c9934
A
1910if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) {
1911 showDailyRSS($conf, $loginManager);
1912 exit;
45034273
SS
1913}
1914
684e662a 1915if (!isset($_SESSION['LINKS_PER_PAGE'])) {
da10377b 1916 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
684e662a 1917}
18e67967 1918
3b67b222
A
1919try {
1920 $history = new History($conf->get('resource.history'));
93bf0918 1921} catch (Exception $e) {
3b67b222
A
1922 die($e->getMessage());
1923}
1924
18e67967
A
1925$linkDb = new LinkDB(
1926 $conf->get('resource.datastore'),
63ea23c2 1927 $loginManager->isLoggedIn(),
520d2957 1928 $conf->get('privacy.hide_public_links')
18e67967
A
1929);
1930
1931$container = new \Slim\Container();
1932$container['conf'] = $conf;
1933$container['plugins'] = $pluginManager;
813849e5 1934$container['history'] = $history;
18e67967
A
1935$app = new \Slim\App($container);
1936
1937// REST API routes
93bf0918 1938$app->group('/api/v1', function () {
68016e37
A
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');
cf9181dd 1943 $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
0843848c 1944 $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
d3f42ca4
A
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
18d2d3ae 1951 $this->get('/history', '\Shaarli\Api\Controllers\HistoryController:getHistory')->setName('getHistory');
465b1c40 1952})->add('\Shaarli\Api\ApiMiddleware');
18e67967
A
1953
1954$response = $app->run(true);
5d9bc40d 1955
18e67967 1956// Hack to make Slim and Shaarli router work together:
16e3d006
A
1957// If a Slim route isn't found and NOT API call, we call renderPage().
1958if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
18e67967
A
1959 // We use UTF-8 for proper international characters handling.
1960 header('Content-Type: text/html; charset=utf-8');
44acf706 1961 renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
18e67967 1962} else {
5d9bc40d
A
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');
18e67967
A
1970 $app->respond($response);
1971}