TYPO3  7.6
LoginController.php
Go to the documentation of this file.
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 
30 
35 {
41  protected $redirectUrl;
42 
48  protected $redirectToURL;
49 
55  protected $loginProviderIdentifier = null;
56 
62  protected $loginProviders = [];
63 
71  protected $loginRefresh;
72 
78  protected $submitValue;
79 
83  protected $view;
84 
88  public function __construct()
89  {
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 
134  {
135  $content = $this->main();
136  $response->getBody()->write($content);
137  return $response;
138  }
139 
146  public function main()
147  {
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 
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 
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 
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 
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 
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 
415  protected function isLoginInProgress()
416  {
417  $username = GeneralUtility::_GP('username');
418  return !empty($username) || !empty($this->submitValue);
419  }
420 
426  protected function getFluidTemplateObject()
427  {
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 
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 
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 
500  public function getLoginProviderIdentifier()
501  {
503  }
504 
510  protected function getLanguageService()
511  {
512  return $GLOBALS['LANG'];
513  }
514 
518  protected function getBackendUserAuthentication()
519  {
520  return $GLOBALS['BE_USER'];
521  }
522 
528  protected function getDatabaseConnection()
529  {
530  return $GLOBALS['TYPO3_DB'];
531  }
532 
538  protected function getDocumentTemplate()
539  {
540  return $GLOBALS['TBE_TEMPLATE'];
541  }
542 }