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