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