aboutsummaryrefslogtreecommitdiffhomepage
path: root/index.php
diff options
context:
space:
mode:
Diffstat (limited to 'index.php')
-rw-r--r--index.php153
1 files changed, 12 insertions, 141 deletions
diff --git a/index.php b/index.php
index 2737c22c..4627438e 100644
--- a/index.php
+++ b/index.php
@@ -61,13 +61,11 @@ require_once 'application/TimeZone.php';
61require_once 'application/Utils.php'; 61require_once 'application/Utils.php';
62 62
63use Shaarli\ApplicationUtils; 63use Shaarli\ApplicationUtils;
64use Shaarli\Bookmark\BookmarkFileService;
65use Shaarli\Config\ConfigManager; 64use Shaarli\Config\ConfigManager;
66use Shaarli\Container\ContainerBuilder; 65use Shaarli\Container\ContainerBuilder;
67use Shaarli\History;
68use Shaarli\Languages; 66use Shaarli\Languages;
69use Shaarli\Plugin\PluginManager; 67use Shaarli\Plugin\PluginManager;
70use Shaarli\Render\PageBuilder; 68use Shaarli\Security\CookieManager;
71use Shaarli\Security\LoginManager; 69use Shaarli\Security\LoginManager;
72use Shaarli\Security\SessionManager; 70use Shaarli\Security\SessionManager;
73use Slim\App; 71use Slim\App;
@@ -118,13 +116,14 @@ if ($conf->get('dev.debug', false)) {
118 // See all errors (for debugging only) 116 // See all errors (for debugging only)
119 error_reporting(-1); 117 error_reporting(-1);
120 118
121 set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) { 119 set_error_handler(function ($errno, $errstr, $errfile, $errline, array $errcontext) {
122 throw new ErrorException($errstr, 0, $errno, $errfile, $errline); 120 throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
123 }); 121 });
124} 122}
125 123
126$sessionManager = new SessionManager($_SESSION, $conf); 124$sessionManager = new SessionManager($_SESSION, $conf, session_save_path());
127$loginManager = new LoginManager($conf, $sessionManager); 125$cookieManager = new CookieManager($_COOKIE);
126$loginManager = new LoginManager($conf, $sessionManager, $cookieManager);
128$loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']); 127$loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
129$clientIpId = client_ip_id($_SERVER); 128$clientIpId = client_ip_id($_SERVER);
130 129
@@ -158,28 +157,7 @@ header("Cache-Control: no-store, no-cache, must-revalidate");
158header("Cache-Control: post-check=0, pre-check=0", false); 157header("Cache-Control: post-check=0, pre-check=0", false);
159header("Pragma: no-cache"); 158header("Pragma: no-cache");
160 159
161if (! is_file($conf->getConfigFileExt())) { 160$loginManager->checkLoginState($clientIpId);
162 // Ensure Shaarli has proper access to its resources
163 $errors = ApplicationUtils::checkResourcePermissions($conf);
164
165 if ($errors != array()) {
166 $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
167
168 foreach ($errors as $error) {
169 $message .= '<li>'.$error.'</li>';
170 }
171 $message .= '</ul>';
172
173 header('Content-Type: text/html; charset=utf-8');
174 echo $message;
175 exit;
176 }
177
178 // Display the installation form if no existing config is found
179 install($conf, $sessionManager, $loginManager);
180}
181
182$loginManager->checkLoginState($_COOKIE, $clientIpId);
183 161
184// ------------------------------------------------------------------------------------------ 162// ------------------------------------------------------------------------------------------
185// Process login form: Check if login/password is correct. 163// Process login form: Check if login/password is correct.
@@ -205,7 +183,7 @@ if (isset($_POST['login'])) {
205 $expirationTime = $sessionManager->extendSession(); 183 $expirationTime = $sessionManager->extendSession();
206 184
207 setcookie( 185 setcookie(
208 $loginManager::$STAY_SIGNED_IN_COOKIE, 186 CookieManager::STAY_SIGNED_IN,
209 $loginManager->getStaySignedInToken(), 187 $loginManager->getStaySignedInToken(),
210 $expirationTime, 188 $expirationTime,
211 WEB_PATH 189 WEB_PATH
@@ -271,122 +249,11 @@ if (!isset($_SESSION['tokens'])) {
271 $_SESSION['tokens']=array(); // Token are attached to the session. 249 $_SESSION['tokens']=array(); // Token are attached to the session.
272} 250}
273 251
274/**
275 * Installation
276 * This function should NEVER be called if the file data/config.php exists.
277 *
278 * @param ConfigManager $conf Configuration Manager instance.
279 * @param SessionManager $sessionManager SessionManager instance
280 * @param LoginManager $loginManager LoginManager instance
281 */
282function install($conf, $sessionManager, $loginManager)
283{
284 // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
285 if (endsWith($_SERVER['HTTP_HOST'], '.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) {
286 mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions', 0705);
287 }
288
289
290 // This part makes sure sessions works correctly.
291 // (Because on some hosts, session.save_path may not be set correctly,
292 // or we may not have write access to it.)
293 if (isset($_GET['test_session'])
294 && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working')) {
295 // Step 2: Check if data in session is correct.
296 $msg = t(
297 '<pre>Sessions do not seem to work correctly on your server.<br>'.
298 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
299 'and that you have write access to it.<br>'.
300 'It currently points to %s.<br>'.
301 'On some browsers, accessing your server via a hostname like \'localhost\' '.
302 'or any custom hostname without a dot causes cookie storage to fail. '.
303 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
304 );
305 $msg = sprintf($msg, session_save_path());
306 echo $msg;
307 echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
308 die;
309 }
310 if (!isset($_SESSION['session_tested'])) {
311 // Step 1 : Try to store data in session and reload page.
312 $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
313 header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
314 }
315 if (isset($_GET['test_session'])) {
316 // Step 3: Sessions are OK. Remove test parameter from URL.
317 header('Location: '.index_url($_SERVER));
318 }
319
320
321 if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) {
322 $tz = 'UTC';
323 if (!empty($_POST['continent']) && !empty($_POST['city'])
324 && isTimeZoneValid($_POST['continent'], $_POST['city'])
325 ) {
326 $tz = $_POST['continent'].'/'.$_POST['city'];
327 }
328 $conf->set('general.timezone', $tz);
329 $login = $_POST['setlogin'];
330 $conf->set('credentials.login', $login);
331 $salt = sha1(uniqid('', true) .'_'. mt_rand());
332 $conf->set('credentials.salt', $salt);
333 $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
334 if (!empty($_POST['title'])) {
335 $conf->set('general.title', escape($_POST['title']));
336 } else {
337 $conf->set('general.title', 'Shared bookmarks on '.escape(index_url($_SERVER)));
338 }
339 $conf->set('translation.language', escape($_POST['language']));
340 $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
341 $conf->set('api.enabled', !empty($_POST['enableApi']));
342 $conf->set(
343 'api.secret',
344 generate_api_secret(
345 $conf->get('credentials.login'),
346 $conf->get('credentials.salt')
347 )
348 );
349 try {
350 // Everything is ok, let's create config file.
351 $conf->write($loginManager->isLoggedIn());
352 } catch (Exception $e) {
353 error_log(
354 'ERROR while writing config file after installation.' . PHP_EOL .
355 $e->getMessage()
356 );
357
358 // TODO: do not handle exceptions/errors in JS.
359 echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
360 exit;
361 }
362
363 $history = new History($conf->get('resource.history'));
364 $bookmarkService = new BookmarkFileService($conf, $history, true);
365 if ($bookmarkService->count() === 0) {
366 $bookmarkService->initialize();
367 }
368
369 echo '<script>alert('
370 .'"Shaarli is now configured. '
371 .'Please enter your login/password and start shaaring your bookmarks!"'
372 .');document.location=\'./login\';</script>';
373 exit;
374 }
375
376 $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
377 list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
378 $PAGE->assign('continents', $continents);
379 $PAGE->assign('cities', $cities);
380 $PAGE->assign('languages', Languages::getAvailableLanguages());
381 $PAGE->renderPage('install');
382 exit;
383}
384
385if (!isset($_SESSION['LINKS_PER_PAGE'])) { 252if (!isset($_SESSION['LINKS_PER_PAGE'])) {
386 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20); 253 $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
387} 254}
388 255
389$containerBuilder = new ContainerBuilder($conf, $sessionManager, $loginManager); 256$containerBuilder = new ContainerBuilder($conf, $sessionManager, $cookieManager, $loginManager);
390$container = $containerBuilder->build(); 257$container = $containerBuilder->build();
391$app = new App($container); 258$app = new App($container);
392 259
@@ -408,6 +275,10 @@ $app->group('/api/v1', function () {
408})->add('\Shaarli\Api\ApiMiddleware'); 275})->add('\Shaarli\Api\ApiMiddleware');
409 276
410$app->group('', function () { 277$app->group('', function () {
278 $this->get('/install', '\Shaarli\Front\Controller\Visitor\InstallController:index')->setName('displayInstall');
279 $this->get('/install/session-test', '\Shaarli\Front\Controller\Visitor\InstallController:sessionTest');
280 $this->post('/install', '\Shaarli\Front\Controller\Visitor\InstallController:save')->setName('saveInstall');
281
411 /* -- PUBLIC --*/ 282 /* -- PUBLIC --*/
412 $this->get('/', '\Shaarli\Front\Controller\Visitor\BookmarkListController:index'); 283 $this->get('/', '\Shaarli\Front\Controller\Visitor\BookmarkListController:index');
413 $this->get('/shaare/{hash}', '\Shaarli\Front\Controller\Visitor\BookmarkListController:permalink'); 284 $this->get('/shaare/{hash}', '\Shaarli\Front\Controller\Visitor\BookmarkListController:permalink');