8172309f81f7e98b794c93b26dcc848066ed6c38
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Controller / LoginController.php
1 <?php
2 namespace TYPO3\CMS\Backend\Controller;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Psr\Http\Message\ResponseInterface;
18 use Psr\Http\Message\ServerRequestInterface;
19 use TYPO3\CMS\Backend\Exception;
20 use TYPO3\CMS\Backend\LoginProvider\LoginProviderInterface;
21 use TYPO3\CMS\Backend\Utility\BackendUtility;
22 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
23 use TYPO3\CMS\Core\Database\ConnectionPool;
24 use TYPO3\CMS\Core\FormProtection\BackendFormProtection;
25 use TYPO3\CMS\Core\FormProtection\FormProtectionFactory;
26 use TYPO3\CMS\Core\Localization\Locales;
27 use TYPO3\CMS\Core\Page\PageRenderer;
28 use TYPO3\CMS\Core\Utility\GeneralUtility;
29 use TYPO3\CMS\Core\Utility\HttpUtility;
30 use TYPO3\CMS\Core\Utility\PathUtility;
31 use TYPO3\CMS\Fluid\View\StandaloneView;
32
33 /**
34 * Script Class for rendering the login form
35 */
36 class LoginController
37 {
38 /**
39 * The URL to redirect to after login.
40 *
41 * @var string
42 */
43 protected $redirectUrl;
44
45 /**
46 * Set to the redirect URL of the form (may be redirect_url or "index.php?M=main")
47 *
48 * @var string
49 */
50 protected $redirectToURL;
51
52 /**
53 * the active login provider identifier
54 *
55 * @var string
56 */
57 protected $loginProviderIdentifier = null;
58
59 /**
60 * List of registered and sorted login providers
61 *
62 * @var array
63 */
64 protected $loginProviders = [];
65
66 /**
67 * Login-refresh bool; The backend will call this script
68 * with this value set when the login is close to being expired
69 * and the form needs to be redrawn.
70 *
71 * @var bool
72 */
73 protected $loginRefresh;
74
75 /**
76 * Value of forms submit button for login.
77 *
78 * @var string
79 */
80 protected $submitValue;
81
82 /**
83 * @var StandaloneView
84 */
85 protected $view;
86
87 /**
88 * Initialize the login box. Will also react on a &L=OUT flag and exit.
89 */
90 public function __construct()
91 {
92 $this->validateAndSortLoginProviders();
93
94 // We need a PHP session session for most login levels
95 session_start();
96 $this->redirectUrl = GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('redirect_url'));
97 $this->loginProviderIdentifier = $this->detectLoginProvider();
98
99 $this->loginRefresh = (bool)GeneralUtility::_GP('loginRefresh');
100 // Value of "Login" button. If set, the login button was pressed.
101 $this->submitValue = GeneralUtility::_GP('commandLI');
102
103 // Try to get the preferred browser language
104 /** @var Locales $locales */
105 $locales = GeneralUtility::makeInstance(Locales::class);
106 $preferredBrowserLanguage = $locales
107 ->getPreferredClientLanguage(GeneralUtility::getIndpEnv('HTTP_ACCEPT_LANGUAGE'));
108
109 // If we found a $preferredBrowserLanguage and it is not the default language and no be_user is logged in
110 // initialize $this->getLanguageService() again with $preferredBrowserLanguage
111 if ($preferredBrowserLanguage !== 'default' && empty($this->getBackendUserAuthentication()->user['uid'])) {
112 $this->getLanguageService()->init($preferredBrowserLanguage);
113 GeneralUtility::makeInstance(PageRenderer::class)->setLanguage($preferredBrowserLanguage);
114 }
115
116 $this->getLanguageService()->includeLLFile('EXT:lang/locallang_login.xlf');
117
118 // Setting the redirect URL to "index.php?M=main" if no alternative input is given
119 $this->redirectToURL = $this->redirectUrl ?: BackendUtility::getModuleUrl('main');
120
121 // If "L" is "OUT", then any logged in is logged out. If redirect_url is given, we redirect to it
122 if (GeneralUtility::_GP('L') === 'OUT' && is_object($this->getBackendUserAuthentication())) {
123 $this->getBackendUserAuthentication()->logoff();
124 HttpUtility::redirect($this->redirectUrl);
125 }
126
127 $this->view = $this->getFluidTemplateObject();
128 }
129
130 /**
131 * Injects the request and response objects for the current request or subrequest
132 * As this controller goes only through the main() method, it is rather simple for now
133 *
134 * @param ServerRequestInterface $request the current request
135 * @param ResponseInterface $response the current response
136 * @return ResponseInterface the finished response with the content
137 */
138 public function formAction(ServerRequestInterface $request, ResponseInterface $response)
139 {
140 $content = $this->main();
141 $response->getBody()->write($content);
142 return $response;
143 }
144
145 /**
146 * Main function - creating the login/logout form
147 *
148 * @throws Exception
149 * @return string The content to output
150 */
151 public function main()
152 {
153 /** @var $pageRenderer PageRenderer */
154 $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
155 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Login');
156
157 // Checking, if we should make a redirect.
158 // Might set JavaScript in the header to close window.
159 $this->checkRedirect();
160
161 // Extension Configuration
162 $extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['backend'], ['allowed_classes' => false]);
163
164 // Background Image
165 if (!empty($extConf['loginBackgroundImage'])) {
166 $backgroundImage = $this->getUriForFileName($extConf['loginBackgroundImage']);
167 $this->getDocumentTemplate()->inDocStylesArray[] = '
168 @media (min-width: 768px){
169 .typo3-login-carousel-control.right,
170 .typo3-login-carousel-control.left,
171 .panel-login { border: 0; }
172 .typo3-login { background-image: url("' . $backgroundImage . '"); }
173 }
174 ';
175 }
176
177 // Add additional css to use the highlight color in the login screen
178 if (!empty($extConf['loginHighlightColor'])) {
179 $this->getDocumentTemplate()->inDocStylesArray[] = '
180 .btn-login.disabled, .btn-login[disabled], fieldset[disabled] .btn-login,
181 .btn-login.disabled:hover, .btn-login[disabled]:hover, fieldset[disabled] .btn-login:hover,
182 .btn-login.disabled:focus, .btn-login[disabled]:focus, fieldset[disabled] .btn-login:focus,
183 .btn-login.disabled.focus, .btn-login[disabled].focus, fieldset[disabled] .btn-login.focus,
184 .btn-login.disabled:active, .btn-login[disabled]:active, fieldset[disabled] .btn-login:active,
185 .btn-login.disabled.active, .btn-login[disabled].active, fieldset[disabled] .btn-login.active,
186 .btn-login:hover, .btn-login:focus, .btn-login:active,
187 .btn-login:active:hover, .btn-login:active:focus,
188 .btn-login { background-color: ' . $extConf['loginHighlightColor'] . '; }
189 .panel-login .panel-body { border-color: ' . $extConf['loginHighlightColor'] . '; }
190 ';
191 }
192
193 // Logo
194 if (!empty($extConf['loginLogo'])) {
195 $logo = $extConf['loginLogo'];
196 } else {
197 // Use TYPO3 logo depending on highlight color
198 if (!empty($extConf['loginHighlightColor'])) {
199 $logo = 'EXT:backend/Resources/Public/Images/typo3_black.svg';
200 } else {
201 $logo = 'EXT:backend/Resources/Public/Images/typo3_orange.svg';
202 }
203 $this->getDocumentTemplate()->inDocStylesArray[] = '
204 .typo3-login-logo .typo3-login-image { max-width: 150px; }
205 ';
206 }
207 $logo = $this->getUriForFileName($logo);
208
209 // Start form
210 $formType = empty($this->getBackendUserAuthentication()->user['uid']) ? 'LoginForm' : 'LogoutForm';
211 $this->view->assignMultiple(array(
212 'backendUser' => $this->getBackendUserAuthentication()->user,
213 'hasLoginError' => $this->isLoginInProgress(),
214 'formType' => $formType,
215 'logo' => $logo,
216 'images' => array(
217 'capslock' => $this->getUriForFileName('EXT:backend/Resources/Public/Images/icon_capslock.svg'),
218 'typo3' => $this->getUriForFileName('EXT:backend/Resources/Public/Images/typo3_orange.svg'),
219 ),
220 'copyright' => BackendUtility::TYPO3_copyRightNotice(),
221 'loginNewsItems' => $this->getSystemNews(),
222 'loginProviderIdentifier' => $this->loginProviderIdentifier,
223 'loginProviders' => $this->loginProviders
224 ));
225
226 // Initialize interface selectors:
227 $this->makeInterfaceSelectorBox();
228
229 /** @var LoginProviderInterface $loginProvider */
230 $loginProvider = GeneralUtility::makeInstance($this->loginProviders[$this->loginProviderIdentifier]['provider']);
231 $loginProvider->render($this->view, $pageRenderer, $this);
232
233 $content = $this->getDocumentTemplate()->startPage('TYPO3 CMS Login: ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']);
234 $content .= $this->view->render();
235 $content .= $this->getDocumentTemplate()->endPage();
236
237 return $content;
238 }
239
240 /**
241 * Checking, if we should perform some sort of redirection OR closing of windows.
242 *
243 * Do redirect:
244 *
245 * If a user is logged in AND
246 * a) if either the login is just done (isLoginInProgress) or
247 * b) a loginRefresh is done
248 *
249 * @throws \RuntimeException
250 * @throws \UnexpectedValueException
251 */
252 protected function checkRedirect()
253 {
254 if (
255 empty($this->getBackendUserAuthentication()->user['uid'])
256 && ($this->isLoginInProgress() || !$this->loginRefresh)
257 ) {
258 return;
259 }
260
261 /*
262 * If no cookie has been set previously, we tell people that this is a problem.
263 * This assumes that a cookie-setting script (like this one) has been hit at
264 * least once prior to this instance.
265 */
266 if (!$_COOKIE[BackendUserAuthentication::getCookieName()]) {
267 if ($this->submitValue === 'setCookie') {
268 /*
269 * we tried it a second time but still no cookie
270 * 26/4 2005: This does not work anymore, because the saving of challenge values
271 * in $_SESSION means the system will act as if the password was wrong.
272 */
273 throw new \RuntimeException('Login-error: Yeah, that\'s a classic. No cookies, no TYPO3. ' .
274 'Please accept cookies from TYPO3 - otherwise you\'ll not be able to use the system.', 1294586846);
275 } else {
276 // try it once again - that might be needed for auto login
277 $this->redirectToURL = 'index.php?commandLI=setCookie';
278 }
279 }
280 $redirectToUrl = (string)$this->getBackendUserAuthentication()->getTSConfigVal('auth.BE.redirectToURL');
281 if (empty($redirectToUrl)) {
282 // Based on the interface we set the redirect script
283 switch (GeneralUtility::_GP('interface')) {
284 case 'frontend':
285 $interface = 'frontend';
286 $this->redirectToURL = '../';
287 break;
288 case 'backend':
289 $interface = 'backend';
290 $this->redirectToURL = BackendUtility::getModuleUrl('main');
291 break;
292 default:
293 $interface = '';
294 }
295 } else {
296 $this->redirectToURL = $redirectToUrl;
297 $interface = '';
298 }
299 // store interface
300 $this->getBackendUserAuthentication()->uc['interfaceSetup'] = $interface;
301 $this->getBackendUserAuthentication()->writeUC();
302
303 $formProtection = FormProtectionFactory::get();
304 if (!$formProtection instanceof BackendFormProtection) {
305 throw new \RuntimeException('The Form Protection retrieved does not match the expected one.', 1432080411);
306 }
307 if ($this->loginRefresh) {
308 $formProtection->setSessionTokenFromRegistry();
309 $formProtection->persistSessionToken();
310 $this->getDocumentTemplate()->JScode .= $this->getDocumentTemplate()->wrapScriptTags('
311 if (parent.opener && parent.opener.TYPO3 && parent.opener.TYPO3.LoginRefresh) {
312 parent.opener.TYPO3.LoginRefresh.startTask();
313 parent.close();
314 }
315 ');
316 } else {
317 $formProtection->storeSessionTokenInRegistry();
318 HttpUtility::redirect($this->redirectToURL);
319 }
320 }
321
322 /**
323 * Making interface selector:
324 *
325 * @return void
326 */
327 public function makeInterfaceSelectorBox()
328 {
329 // If interfaces are defined AND no input redirect URL in GET vars:
330 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['interfaces'] && ($this->isLoginInProgress() || !$this->redirectUrl)) {
331 $parts = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['BE']['interfaces']);
332 if (count($parts) > 1) {
333 // Only if more than one interface is defined we will show the selector
334 $interfaces = array(
335 'backend' => array(
336 'label' => $this->getLanguageService()->getLL('interface.backend'),
337 'jumpScript' => BackendUtility::getModuleUrl('main'),
338 'interface' => 'backend'
339 ),
340 'frontend' => array(
341 'label' => $this->getLanguageService()->getLL('interface.frontend'),
342 'jumpScript' => '../',
343 'interface' => 'frontend'
344 )
345 );
346
347 $this->view->assign('showInterfaceSelector', true);
348 $this->view->assign('interfaces', $interfaces);
349 } elseif (!$this->redirectUrl) {
350 // If there is only ONE interface value set and no redirect_url is present
351 $this->view->assign('showInterfaceSelector', false);
352 $this->view->assign('interface', $parts[0]);
353 }
354 }
355 }
356
357 /**
358 * Gets news from sys_news and converts them into a format suitable for
359 * showing them at the login screen.
360 *
361 * @return array An array of login news.
362 */
363 protected function getSystemNews()
364 {
365 $systemNewsTable = 'sys_news';
366 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
367 ->getQueryBuilderForTable($systemNewsTable);
368 $systemNews = array();
369 $systemNewsRecords = $queryBuilder
370 ->select('title', 'content', 'crdate')
371 ->from($systemNewsTable)
372 ->orderBy('crdate', 'DESC')
373 ->execute()
374 ->fetchAll();
375 foreach ($systemNewsRecords as $systemNewsRecord) {
376 $systemNews[] = array(
377 'date' => date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $systemNewsRecord['crdate']),
378 'header' => $systemNewsRecord['title'],
379 'content' => $systemNewsRecord['content']
380 );
381 }
382 return $systemNews;
383 }
384
385 /**
386 * Returns the uri of a relative reference, resolves the "EXT:" prefix
387 * (way of referring to files inside extensions) and checks that the file is inside
388 * the PATH_site of the TYPO3 installation
389 *
390 * @param string $filename The input filename/filepath to evaluate
391 * @return string Returns the filename of $filename if valid, otherwise blank string.
392 * @internal
393 */
394 private function getUriForFileName($filename)
395 {
396 if (strpos($filename, '://')) {
397 return $filename;
398 }
399 $urlPrefix = '';
400 if (strpos($filename, 'EXT:') === 0) {
401 $absoluteFilename = GeneralUtility::getFileAbsFileName($filename);
402 $filename = '';
403 if ($absoluteFilename !== '') {
404 $filename = PathUtility::getAbsoluteWebPath($absoluteFilename);
405 }
406 } elseif (strpos($filename, '/') !== 0) {
407 $urlPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
408 }
409 return $urlPrefix . $filename;
410 }
411
412 /**
413 * Checks if login credentials are currently submitted
414 *
415 * @return bool
416 */
417 protected function isLoginInProgress()
418 {
419 $username = GeneralUtility::_GP('username');
420 return !empty($username) || !empty($this->submitValue);
421 }
422
423 /**
424 * returns a new standalone view, shorthand function
425 *
426 * @return StandaloneView
427 */
428 protected function getFluidTemplateObject()
429 {
430 /** @var StandaloneView $view */
431 $view = GeneralUtility::makeInstance(StandaloneView::class);
432 $view->setLayoutRootPaths(array(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Layouts')));
433 $view->setPartialRootPaths(array(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Partials')));
434 $view->setTemplateRootPaths(array(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates')));
435
436 $view->getRequest()->setControllerExtensionName('Backend');
437 return $view;
438 }
439
440 /**
441 * Validates the registered login providers
442 *
443 * @throws \RuntimeException
444 */
445 protected function validateAndSortLoginProviders()
446 {
447 if (
448 !isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['backend']['loginProviders'])
449 || !is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['backend']['loginProviders'])
450 || empty($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['backend']['loginProviders'])
451 ) {
452 throw new \RuntimeException('No login providers are registered in $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXTCONF\'][\'backend\'][\'loginProviders\'].', 1433417281);
453 }
454 $providers = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['backend']['loginProviders'];
455 foreach ($providers as $identifier => $configuration) {
456 if (empty($configuration) || !is_array($configuration)) {
457 throw new \RuntimeException('Missing configuration for login provider "' . $identifier . '".', 1433416043);
458 }
459 if (!is_string($configuration['provider']) || empty($configuration['provider']) || !class_exists($configuration['provider']) || !is_subclass_of($configuration['provider'], LoginProviderInterface::class)) {
460 throw new \RuntimeException('The login provider "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . LoginProviderInterface::class . '".', 1460977275);
461 }
462 if (empty($configuration['label'])) {
463 throw new \RuntimeException('Missing label definition for login provider "' . $identifier . '".', 1433416044);
464 }
465 if (empty($configuration['icon-class'])) {
466 throw new \RuntimeException('Missing icon definition for login provider "' . $identifier . '".', 1433416045);
467 }
468 if (!isset($configuration['sorting'])) {
469 throw new \RuntimeException('Missing sorting definition for login provider "' . $identifier . '".', 1433416046);
470 }
471 }
472 // sort providers
473 uasort($providers, function ($a, $b) {
474 return $b['sorting'] - $a['sorting'];
475 });
476 $this->loginProviders = $providers;
477 }
478
479 /**
480 * Detect the login provider, get from request or choose the
481 * first one as default
482 *
483 * @return string
484 */
485 protected function detectLoginProvider()
486 {
487 $loginProvider = GeneralUtility::_GP('loginProvider');
488 if ((empty($loginProvider) || !isset($this->loginProviders[$loginProvider])) && !empty($_COOKIE['be_lastLoginProvider'])) {
489 $loginProvider = $_COOKIE['be_lastLoginProvider'];
490 }
491 if (empty($loginProvider) || !isset($this->loginProviders[$loginProvider])) {
492 reset($this->loginProviders);
493 $loginProvider = key($this->loginProviders);
494 }
495 setcookie('be_lastLoginProvider', $loginProvider, $GLOBALS['EXEC_TIME'] + 7776000); // 90 days
496 return $loginProvider;
497 }
498
499 /**
500 * @return string
501 */
502 public function getLoginProviderIdentifier()
503 {
504 return $this->loginProviderIdentifier;
505 }
506
507 /**
508 * Returns LanguageService
509 *
510 * @return \TYPO3\CMS\Lang\LanguageService
511 */
512 protected function getLanguageService()
513 {
514 return $GLOBALS['LANG'];
515 }
516
517 /**
518 * @return BackendUserAuthentication
519 */
520 protected function getBackendUserAuthentication()
521 {
522 return $GLOBALS['BE_USER'];
523 }
524
525 /**
526 * Returns an instance of DocumentTemplate
527 *
528 * @return \TYPO3\CMS\Backend\Template\DocumentTemplate
529 */
530 protected function getDocumentTemplate()
531 {
532 return $GLOBALS['TBE_TEMPLATE'];
533 }
534 }