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