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