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