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