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