[TASK] Drop Placeholders.js that supports placeholder tag for IE9 and lower
[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 GeneralUtility::makeInstance(PageRenderer::class)->setLanguage($preferredBrowserLanguage);
110 }
111
112 $this->getLanguageService()->includeLLFile('EXT:lang/locallang_login.xlf');
113
114 // Setting the redirect URL to "index.php?M=main" if no alternative input is given
115 $this->redirectToURL = $this->redirectUrl ?: BackendUtility::getModuleUrl('main');
116
117 // If "L" is "OUT", then any logged in is logged out. If redirect_url is given, we redirect to it
118 if (GeneralUtility::_GP('L') === 'OUT' && is_object($this->getBackendUserAuthentication())) {
119 $this->getBackendUserAuthentication()->logoff();
120 HttpUtility::redirect($this->redirectUrl);
121 }
122
123 $this->view = $this->getFluidTemplateObject();
124 }
125
126 /**
127 * Injects the request and response objects for the current request or subrequest
128 * As this controller goes only through the main() method, it is rather simple for now
129 *
130 * @param ServerRequestInterface $request the current request
131 * @param ResponseInterface $response the current response
132 * @return ResponseInterface the finished response with the content
133 */
134 public function formAction(ServerRequestInterface $request, ResponseInterface $response)
135 {
136 $content = $this->main();
137 $response->getBody()->write($content);
138 return $response;
139 }
140
141 /**
142 * Main function - creating the login/logout form
143 *
144 * @throws Exception
145 * @return string The content to output
146 */
147 public function main()
148 {
149 /** @var $pageRenderer PageRenderer */
150 $pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
151 $pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Login');
152
153 // Checking, if we should make a redirect.
154 // Might set JavaScript in the header to close window.
155 $this->checkRedirect();
156
157 // Extension Configuration
158 $extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['backend']);
159
160 // Background Image
161 if (!empty($extConf['loginBackgroundImage'])) {
162 $backgroundImage = $this->getUriForFileName($extConf['loginBackgroundImage']);
163 $this->getDocumentTemplate()->inDocStylesArray[] = '
164 @media (min-width: 768px){
165 .typo3-login-carousel-control.right,
166 .typo3-login-carousel-control.left,
167 .panel-login { border: 0; }
168 .typo3-login { background-image: url("' . $backgroundImage . '"); }
169 }
170 ';
171 }
172
173 // Add additional css to use the highlight color in the login screen
174 if (!empty($extConf['loginHighlightColor'])) {
175 $this->getDocumentTemplate()->inDocStylesArray[] = '
176 .btn-login.disabled, .btn-login[disabled], fieldset[disabled] .btn-login,
177 .btn-login.disabled:hover, .btn-login[disabled]:hover, fieldset[disabled] .btn-login:hover,
178 .btn-login.disabled:focus, .btn-login[disabled]:focus, fieldset[disabled] .btn-login:focus,
179 .btn-login.disabled.focus, .btn-login[disabled].focus, fieldset[disabled] .btn-login.focus,
180 .btn-login.disabled:active, .btn-login[disabled]:active, fieldset[disabled] .btn-login:active,
181 .btn-login.disabled.active, .btn-login[disabled].active, fieldset[disabled] .btn-login.active,
182 .btn-login:hover, .btn-login:focus, .btn-login:active,
183 .btn-login:active:hover, .btn-login:active:focus,
184 .btn-login { background-color: ' . $extConf['loginHighlightColor'] . '; }
185 .panel-login .panel-body { border-color: ' . $extConf['loginHighlightColor'] . '; }
186 ';
187 }
188
189 // Logo
190 if (!empty($extConf['loginLogo'])) {
191 $logo = $extConf['loginLogo'];
192 } elseif (!empty($GLOBALS['TBE_STYLES']['logo_login'])) {
193 // Fallback to old TBE_STYLES login logo
194 $logo = $GLOBALS['TBE_STYLES']['logo_login'];
195 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.');
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 $systemNews = array();
367 $systemNewsRecords = $this->getDatabaseConnection()->exec_SELECTgetRows('title, content, crdate', $systemNewsTable, '1=1' . BackendUtility::BEenableFields($systemNewsTable) . BackendUtility::deleteClause($systemNewsTable), '', 'crdate DESC');
368 foreach ($systemNewsRecords as $systemNewsRecord) {
369 $systemNews[] = array(
370 'date' => date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $systemNewsRecord['crdate']),
371 'header' => $systemNewsRecord['title'],
372 'content' => $systemNewsRecord['content']
373 );
374 }
375 return $systemNews;
376 }
377
378 /**
379 * Returns the uri of a relative reference, resolves the "EXT:" prefix
380 * (way of referring to files inside extensions) and checks that the file is inside
381 * the PATH_site of the TYPO3 installation
382 *
383 * @param string $filename The input filename/filepath to evaluate
384 * @return string Returns the filename of $filename if valid, otherwise blank string.
385 * @internal
386 */
387 private function getUriForFileName($filename)
388 {
389 if (strpos($filename, '://')) {
390 return $filename;
391 }
392 $urlPrefix = '';
393 if (strpos($filename, 'EXT:') === 0) {
394 $absoluteFilename = GeneralUtility::getFileAbsFileName($filename);
395 $filename = '';
396 if ($absoluteFilename !== '') {
397 $filename = PathUtility::getAbsoluteWebPath($absoluteFilename);
398 }
399 } elseif (strpos($filename, '/') !== 0) {
400 $urlPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
401 }
402 return $urlPrefix . $filename;
403 }
404
405 /**
406 * Checks if login credentials are currently submitted
407 *
408 * @return bool
409 */
410 protected function isLoginInProgress()
411 {
412 $username = GeneralUtility::_GP('username');
413 return !empty($username) || !empty($this->submitValue);
414 }
415
416 /**
417 * returns a new standalone view, shorthand function
418 *
419 * @return StandaloneView
420 */
421 protected function getFluidTemplateObject()
422 {
423 /** @var StandaloneView $view */
424 $view = GeneralUtility::makeInstance(StandaloneView::class);
425 $view->setLayoutRootPaths(array(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Layouts')));
426 $view->setPartialRootPaths(array(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Partials')));
427 $view->setTemplateRootPaths(array(GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Private/Templates')));
428
429 $view->getRequest()->setControllerExtensionName('Backend');
430 return $view;
431 }
432
433 /**
434 * Validates the registered login providers
435 *
436 * @throws \RuntimeException
437 */
438 protected function validateAndSortLoginProviders()
439 {
440 if (
441 !isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['backend']['loginProviders'])
442 || !is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['backend']['loginProviders'])
443 || empty($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['backend']['loginProviders'])
444 ) {
445 throw new \RuntimeException('No login providers are registered in $GLOBALS[\'TYPO3_CONF_VARS\'][\'EXTCONF\'][\'backend\'][\'loginProviders\'].', 1433417281);
446 }
447 $providers = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['backend']['loginProviders'];
448 foreach ($providers as $identifier => $configuration) {
449 if (empty($configuration) || !is_array($configuration)) {
450 throw new \RuntimeException('Missing configuration for login provider "' . $identifier . '".', 1433416043);
451 }
452 if (!is_string($configuration['provider']) || empty($configuration['provider']) || !class_exists($configuration['provider']) || !is_subclass_of($configuration['provider'], LoginProviderInterface::class)) {
453 throw new \RuntimeException('The login provider "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . LoginProviderInterface::class . '".', 1433416043);
454 }
455 if (empty($configuration['label'])) {
456 throw new \RuntimeException('Missing label definition for login provider "' . $identifier . '".', 1433416044);
457 }
458 if (empty($configuration['icon-class'])) {
459 throw new \RuntimeException('Missing icon definition for login provider "' . $identifier . '".', 1433416045);
460 }
461 if (!isset($configuration['sorting'])) {
462 throw new \RuntimeException('Missing sorting definition for login provider "' . $identifier . '".', 1433416046);
463 }
464 }
465 // sort providers
466 uasort($providers, function ($a, $b) {
467 return $b['sorting'] - $a['sorting'];
468 });
469 $this->loginProviders = $providers;
470 }
471
472 /**
473 * Detect the login provider, get from request or choose the
474 * first one as default
475 *
476 * @return string
477 */
478 protected function detectLoginProvider()
479 {
480 $loginProvider = GeneralUtility::_GP('loginProvider');
481 if ((empty($loginProvider) || !isset($this->loginProviders[$loginProvider])) && !empty($_COOKIE['be_lastLoginProvider'])) {
482 $loginProvider = $_COOKIE['be_lastLoginProvider'];
483 }
484 if (empty($loginProvider) || !isset($this->loginProviders[$loginProvider])) {
485 reset($this->loginProviders);
486 $loginProvider = key($this->loginProviders);
487 }
488 setcookie('be_lastLoginProvider', $loginProvider, $GLOBALS['EXEC_TIME'] + 7776000); // 90 days
489 return $loginProvider;
490 }
491
492 /**
493 * @return string
494 */
495 public function getLoginProviderIdentifier()
496 {
497 return $this->loginProviderIdentifier;
498 }
499
500 /**
501 * Returns LanguageService
502 *
503 * @return \TYPO3\CMS\Lang\LanguageService
504 */
505 protected function getLanguageService()
506 {
507 return $GLOBALS['LANG'];
508 }
509
510 /**
511 * @return BackendUserAuthentication
512 */
513 protected function getBackendUserAuthentication()
514 {
515 return $GLOBALS['BE_USER'];
516 }
517
518 /**
519 * Returns the database connection
520 *
521 * @return \TYPO3\CMS\Core\Database\DatabaseConnection
522 */
523 protected function getDatabaseConnection()
524 {
525 return $GLOBALS['TYPO3_DB'];
526 }
527
528 /**
529 * Returns an instance of DocumentTemplate
530 *
531 * @return \TYPO3\CMS\Backend\Template\DocumentTemplate
532 */
533 protected function getDocumentTemplate()
534 {
535 return $GLOBALS['TBE_TEMPLATE'];
536 }
537 }