d4fe68f4adc3ac6e1908b56d3012e990b5a16d2e
[Packages/TYPO3.CMS.git] / typo3 / sysext / felogin / Classes / Controller / FrontendLoginController.php
1 <?php
2 namespace TYPO3\CMS\Felogin\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\Core\Crypto\Random;
18 use TYPO3\CMS\Core\Database\ConnectionPool;
19 use TYPO3\CMS\Core\Database\Query\QueryBuilder;
20 use TYPO3\CMS\Core\Utility\GeneralUtility;
21 use TYPO3\CMS\Core\Utility\StringUtility;
22
23 /**
24 * Plugin 'Website User Login' for the 'felogin' extension.
25 */
26 class FrontendLoginController extends \TYPO3\CMS\Frontend\Plugin\AbstractPlugin
27 {
28 /**
29 * Same as class name
30 *
31 * @var string
32 */
33 public $prefixId = 'tx_felogin_pi1';
34
35 /**
36 * The extension key.
37 *
38 * @var string
39 */
40 public $extKey = 'felogin';
41
42 /**
43 * @var bool
44 */
45 public $pi_checkCHash = false;
46
47 /**
48 * @var bool
49 */
50 public $pi_USER_INT_obj = true;
51
52 /**
53 * Is user logged in?
54 *
55 * @var bool
56 */
57 protected $userIsLoggedIn;
58
59 /**
60 * Holds the template for FE rendering
61 *
62 * @var string
63 */
64 protected $template;
65
66 /**
67 * Upload directory, used for flexform template files
68 *
69 * @var string
70 */
71 protected $uploadDir;
72
73 /**
74 * URL for the redirect
75 *
76 * @var string
77 */
78 protected $redirectUrl;
79
80 /**
81 * Flag for disable the redirect
82 *
83 * @var bool
84 */
85 protected $noRedirect = false;
86
87 /**
88 * Logintype (given as GPvar), possible: login, logout
89 *
90 * @var string
91 */
92 protected $logintype;
93
94 /**
95 * A list of page UIDs, either an integer or a comma-separated list of integers
96 *
97 * @var string
98 */
99 public $spid;
100
101 /**
102 * Referrer
103 *
104 * @var string
105 */
106 public $referer;
107
108 /**
109 * The main method of the plugin
110 *
111 * @param string $content The PlugIn content
112 * @param array $conf The PlugIn configuration
113 * @return string The content that is displayed on the website
114 * @throws \RuntimeException when no storage PID was configured.
115 */
116 public function main($content, $conf)
117 {
118 // Loading TypoScript array into object variable:
119 $this->conf = $conf;
120 $this->uploadDir = 'uploads/tx_felogin/';
121 // Loading default pivars
122 $this->pi_setPiVarDefaults();
123 // Loading language-labels
124 $this->pi_loadLL('EXT:felogin/Resources/Private/Language/locallang.xlf');
125 // Init FlexForm configuration for plugin:
126 $this->pi_initPIflexForm();
127 $this->mergeflexFormValuesIntoConf();
128 // Get storage PIDs:
129 if ($this->conf['storagePid']) {
130 if ((int)$this->conf['recursive']) {
131 $this->spid = $this->pi_getPidList($this->conf['storagePid'], (int)$this->conf['recursive']);
132 } else {
133 $this->spid = $this->conf['storagePid'];
134 }
135 } else {
136 throw new \RuntimeException('No storage folder (option storagePid) for frontend users given.', 1450904202);
137 }
138 // GPvars:
139 $this->logintype = GeneralUtility::_GP('logintype');
140 $this->referer = $this->validateRedirectUrl(GeneralUtility::_GP('referer'));
141 $this->noRedirect = $this->piVars['noredirect'] || $this->conf['redirectDisable'];
142 // If config.typolinkLinkAccessRestrictedPages is set, the var is return_url
143 $returnUrl = GeneralUtility::_GP('return_url');
144 if ($returnUrl) {
145 $this->redirectUrl = $returnUrl;
146 } else {
147 $this->redirectUrl = GeneralUtility::_GP('redirect_url');
148 }
149 $this->redirectUrl = $this->validateRedirectUrl($this->redirectUrl);
150 // Get Template
151 $templateFile = $this->conf['templateFile'] ?: 'EXT:felogin/Resources/Private/Templates/FrontendLogin.html';
152 $this->template = $this->cObj->fileResource($templateFile);
153 // Is user logged in?
154 $this->userIsLoggedIn = $this->frontendController->loginUser;
155 // Redirect
156 if ($this->conf['redirectMode'] && !$this->conf['redirectDisable'] && !$this->noRedirect) {
157 $redirectUrl = $this->processRedirect();
158 if (!empty($redirectUrl)) {
159 $this->redirectUrl = $this->conf['redirectFirstMethod'] ? array_shift($redirectUrl) : array_pop($redirectUrl);
160 } else {
161 $this->redirectUrl = '';
162 }
163 }
164 // What to display
165 $content = '';
166 if ($this->piVars['forgot'] && $this->conf['showForgotPasswordLink']) {
167 $content .= $this->showForgot();
168 } elseif ($this->piVars['forgothash']) {
169 $content .= $this->changePassword();
170 } else {
171 if ($this->userIsLoggedIn && !$this->logintype) {
172 $content .= $this->showLogout();
173 } else {
174 $content .= $this->showLogin();
175 }
176 }
177 // Process the redirect
178 if (($this->logintype === 'login' || $this->logintype === 'logout') && $this->redirectUrl && !$this->noRedirect) {
179 if (!$this->frontendController->fe_user->isCookieSet() && $this->userIsLoggedIn) {
180 $content .= $this->cObj->stdWrap($this->pi_getLL('cookie_warning'), $this->conf['cookieWarning_stdWrap.']);
181 } else {
182 // Add hook for extra processing before redirect
183 if (
184 isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['beforeRedirect']) &&
185 is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['beforeRedirect'])
186 ) {
187 $_params = array(
188 'loginType' => $this->logintype,
189 'redirectUrl' => &$this->redirectUrl
190 );
191 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['beforeRedirect'] as $_funcRef) {
192 if ($_funcRef) {
193 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
194 }
195 }
196 }
197 \TYPO3\CMS\Core\Utility\HttpUtility::redirect($this->redirectUrl);
198 }
199 }
200 // Adds hook for processing of extra item markers / special
201 if (
202 isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['postProcContent'])
203 && is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['postProcContent'])
204 ) {
205 $_params = array(
206 'content' => $content
207 );
208 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['postProcContent'] as $_funcRef) {
209 $content = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
210 }
211 }
212 return $this->conf['wrapContentInBaseClass'] ? $this->pi_wrapInBaseClass($content) : $content;
213 }
214
215 /**
216 * Shows the forgot password form
217 *
218 * @return string Content
219 */
220 protected function showForgot()
221 {
222 $subpart = $this->cObj->getSubpart($this->template, '###TEMPLATE_FORGOT###');
223 $subpartArray = ($linkpartArray = array());
224 $postData = GeneralUtility::_POST($this->prefixId);
225 if ($postData['forgot_email']) {
226 // Get hashes for compare
227 $postedHash = $postData['forgot_hash'];
228 $hashData = $this->frontendController->fe_user->getKey('ses', 'forgot_hash');
229 if ($postedHash === $hashData['forgot_hash']) {
230
231 /** @var QueryBuilder $queryBuilder */
232 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('fe_users');
233 $row = $queryBuilder
234 ->select('uid', 'username', 'password', 'email')
235 ->from('fe_users')
236 ->where(
237 $queryBuilder->expr()->andX(
238 $queryBuilder->expr()->orX(
239 $queryBuilder->expr()->eq(
240 'email',
241 $queryBuilder->createNamedParameter($this->piVars['forgot_email'])
242 ),
243 $queryBuilder->expr()->eq(
244 'username',
245 $queryBuilder->createNamedParameter($this->piVars['forgot_email'])
246 )
247 ),
248 $queryBuilder->expr()->in('pid', GeneralUtility::intExplode(',', $this->spid))
249 )
250 )
251 ->execute()
252 ->fetch();
253
254 $error = null;
255 if ($row) {
256 // Generate an email with the hashed link
257 $error = $this->generateAndSendHash($row);
258 } elseif ($this->conf['exposeNonexistentUserInForgotPasswordDialog']) {
259 $error = $this->pi_getLL('ll_forgot_reset_message_error');
260 }
261 // Generate message
262 if ($error) {
263 $markerArray['###STATUS_MESSAGE###'] = $this->cObj->stdWrap($error, $this->conf['forgotErrorMessage_stdWrap.']);
264 } else {
265 $markerArray['###STATUS_MESSAGE###'] = $this->cObj->stdWrap(
266 $this->pi_getLL('ll_forgot_reset_message_emailSent'),
267 $this->conf['forgotResetMessageEmailSentMessage_stdWrap.']
268 );
269 }
270 $subpartArray['###FORGOT_FORM###'] = '';
271 } else {
272 // Wrong email
273 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('forgot_reset_message', $this->conf['forgotMessage_stdWrap.']);
274 $markerArray['###BACKLINK_LOGIN###'] = '';
275 }
276 } else {
277 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('forgot_reset_message', $this->conf['forgotMessage_stdWrap.']);
278 $markerArray['###BACKLINK_LOGIN###'] = '';
279 }
280 $markerArray['###BACKLINK_LOGIN###'] = $this->getPageLink($this->pi_getLL('ll_forgot_header_backToLogin', '', true), array());
281 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('forgot_header', $this->conf['forgotHeader_stdWrap.']);
282 $markerArray['###LEGEND###'] = $this->pi_getLL('legend', $this->pi_getLL('reset_password'), true);
283 $markerArray['###ACTION_URI###'] = $this->getPageLink('', array($this->prefixId . '[forgot]' => 1), true);
284 $markerArray['###EMAIL_LABEL###'] = $this->pi_getLL('your_email', '', true);
285 $markerArray['###FORGOT_PASSWORD_ENTEREMAIL###'] = $this->pi_getLL('forgot_password_enterEmail', '', true);
286 $markerArray['###FORGOT_EMAIL###'] = $this->prefixId . '[forgot_email]';
287 $markerArray['###SEND_PASSWORD###'] = $this->pi_getLL('reset_password', '', true);
288 $markerArray['###DATA_LABEL###'] = $this->pi_getLL('ll_enter_your_data', '', true);
289 $markerArray = array_merge($markerArray, $this->getUserFieldMarkers());
290 // Generate hash
291 $hash = md5($this->generatePassword(3));
292 $markerArray['###FORGOTHASH###'] = $hash;
293 // Set hash in feuser session
294 $this->frontendController->fe_user->setKey('ses', 'forgot_hash', array('forgot_hash' => $hash));
295 return $this->cObj->substituteMarkerArrayCached($subpart, $markerArray, $subpartArray, $linkpartArray);
296 }
297
298 /**
299 * This function checks the hash from link and checks the validity. If it's valid it shows the form for
300 * changing the password and process the change of password after submit, if not valid it returns the error message
301 *
302 * @return string The content.
303 */
304 protected function changePassword()
305 {
306 $subpartArray = ($linkpartArray = array());
307 $done = false;
308 $minLength = (int)$this->conf['newPasswordMinLength'] ?: 6;
309 $subpart = $this->cObj->getSubpart($this->template, '###TEMPLATE_CHANGEPASSWORD###');
310 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('change_password_header', $this->conf['changePasswordHeader_stdWrap.']);
311 $markerArray['###STATUS_MESSAGE###'] = sprintf($this->getDisplayText(
312 'change_password_message',
313 $this->conf['changePasswordMessage_stdWrap.']
314 ), $minLength);
315
316 $markerArray['###BACKLINK_LOGIN###'] = '';
317 $uid = $this->piVars['user'];
318 $piHash = $this->piVars['forgothash'];
319 $hash = explode('|', rawurldecode($piHash));
320 if ((int)$uid === 0) {
321 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText(
322 'change_password_notvalid_message',
323 $this->conf['changePasswordNotValidMessage_stdWrap.']
324 );
325 $subpartArray['###CHANGEPASSWORD_FORM###'] = '';
326 } else {
327 $user = $this->pi_getRecord('fe_users', (int)$uid);
328 $userHash = $user['felogin_forgotHash'];
329 $compareHash = explode('|', $userHash);
330 if (!$compareHash || !$compareHash[1] || $compareHash[0] < time() || $hash[0] != $compareHash[0] || md5($hash[1]) != $compareHash[1]) {
331 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText(
332 'change_password_notvalid_message',
333 $this->conf['changePasswordNotValidMessage_stdWrap.']
334 );
335 $subpartArray['###CHANGEPASSWORD_FORM###'] = '';
336 } else {
337 // All is fine, continue with new password
338 $postData = GeneralUtility::_POST($this->prefixId);
339 if (isset($postData['changepasswordsubmit'])) {
340 if (strlen($postData['password1']) < $minLength) {
341 $markerArray['###STATUS_MESSAGE###'] = sprintf($this->getDisplayText(
342 'change_password_tooshort_message',
343 $this->conf['changePasswordTooShortMessage_stdWrap.']),
344 $minLength
345 );
346 } elseif ($postData['password1'] != $postData['password2']) {
347 $markerArray['###STATUS_MESSAGE###'] = sprintf($this->getDisplayText(
348 'change_password_notequal_message',
349 $this->conf['changePasswordNotEqualMessage_stdWrap.']),
350 $minLength
351 );
352 } else {
353 $newPass = $postData['password1'];
354 if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['password_changed']) {
355 $_params = array(
356 'user' => $user,
357 'newPassword' => $newPass,
358 'newPasswordUnencrypted' => $newPass
359 );
360 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['password_changed'] as $_funcRef) {
361 if ($_funcRef) {
362 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
363 }
364 }
365 $newPass = $_params['newPassword'];
366 }
367
368 // Save new password and clear DB-hash
369 /** @var QueryBuilder $queryBuilder */
370 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('fe_users');
371 $queryBuilder->update('fe_users')
372 ->set('password', $newPass)
373 ->set('felogin_forgotHash', '')
374 ->set('tstamp', $GLOBALS['EXEC_TIME'])
375 ->where($queryBuilder->expr()->eq('uid', (int)$user['uid']))
376 ->execute();
377
378 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText(
379 'change_password_done_message',
380 $this->conf['changePasswordDoneMessage_stdWrap.']
381 );
382 $done = true;
383 $subpartArray['###CHANGEPASSWORD_FORM###'] = '';
384 $markerArray['###BACKLINK_LOGIN###'] = $this->getPageLink(
385 $this->pi_getLL('ll_forgot_header_backToLogin', '', true),
386 array($this->prefixId . '[redirectReferrer]' => 'off')
387 );
388 }
389 }
390 if (!$done) {
391 // Change password form
392 $markerArray['###ACTION_URI###'] = $this->getPageLink('', array(
393 $this->prefixId . '[user]' => $user['uid'],
394 $this->prefixId . '[forgothash]' => $piHash
395 ), true);
396 $markerArray['###LEGEND###'] = $this->pi_getLL('change_password', '', true);
397 $markerArray['###NEWPASSWORD1_LABEL###'] = $this->pi_getLL('newpassword_label1', '', true);
398 $markerArray['###NEWPASSWORD2_LABEL###'] = $this->pi_getLL('newpassword_label2', '', true);
399 $markerArray['###NEWPASSWORD1###'] = $this->prefixId . '[password1]';
400 $markerArray['###NEWPASSWORD2###'] = $this->prefixId . '[password2]';
401 $markerArray['###STORAGE_PID###'] = $this->spid;
402 $markerArray['###SEND_PASSWORD###'] = $this->pi_getLL('change_password', '', true);
403 $markerArray['###FORGOTHASH###'] = $piHash;
404 }
405 }
406 }
407 return $this->cObj->substituteMarkerArrayCached($subpart, $markerArray, $subpartArray, $linkpartArray);
408 }
409
410 /**
411 * Generates a hashed link and send it with email
412 *
413 * @param array $user Contains user data
414 * @return string Empty string with success, error message with no success
415 */
416 protected function generateAndSendHash($user)
417 {
418 $hours = (int)$this->conf['forgotLinkHashValidTime'] > 0 ? (int)$this->conf['forgotLinkHashValidTime'] : 24;
419 $validEnd = time() + 3600 * $hours;
420 $validEndString = date($this->conf['dateFormat'], $validEnd);
421 $hash = md5(GeneralUtility::makeInstance(Random::class)->generateRandomBytes(64));
422 $randHash = $validEnd . '|' . $hash;
423 $randHashDB = $validEnd . '|' . md5($hash);
424
425 // Write hash to DB
426 /** @var QueryBuilder $queryBuilder */
427 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('fe_users');
428 $queryBuilder->update('fe_users')
429 ->set('felogin_forgotHash', (string)$randHashDB)
430 ->where($queryBuilder->expr()->eq('uid', (int)$user['uid']))
431 ->execute();
432
433 // Send hashlink to user
434 $this->conf['linkPrefix'] = -1;
435 $isAbsRefPrefix = !empty($this->frontendController->absRefPrefix);
436 $isBaseURL = !empty($this->frontendController->baseUrl);
437 $isFeloginBaseURL = !empty($this->conf['feloginBaseURL']);
438 $link = $this->pi_getPageLink($this->frontendController->id, '', array(
439 rawurlencode($this->prefixId . '[user]') => $user['uid'],
440 rawurlencode($this->prefixId . '[forgothash]') => $randHash
441 ));
442 // Prefix link if necessary
443 if ($isFeloginBaseURL) {
444 // First priority, use specific base URL
445 // "absRefPrefix" must be removed first, otherwise URL will be prepended twice
446 if ($isAbsRefPrefix) {
447 $link = substr($link, strlen($this->frontendController->absRefPrefix));
448 }
449 $link = $this->conf['feloginBaseURL'] . $link;
450 } elseif ($isAbsRefPrefix) {
451 // Second priority
452 // absRefPrefix must not necessarily contain a hostname and URL scheme, so add it if needed
453 $link = GeneralUtility::locationHeaderUrl($link);
454 } elseif ($isBaseURL) {
455 // Third priority
456 // Add the global base URL to the link
457 $link = $this->frontendController->baseUrlWrap($link);
458 } else {
459 // No prefix is set, return the error
460 return $this->pi_getLL('ll_change_password_nolinkprefix_message');
461 }
462 $msg = sprintf($this->pi_getLL('ll_forgot_validate_reset_password'), $user['username'], $link, $validEndString);
463 // Add hook for extra processing of mail message
464 if (
465 isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['forgotPasswordMail'])
466 && is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['forgotPasswordMail'])
467 ) {
468 $params = array(
469 'message' => &$msg,
470 'user' => &$user
471 );
472 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['forgotPasswordMail'] as $reference) {
473 if ($reference) {
474 GeneralUtility::callUserFunction($reference, $params, $this);
475 }
476 }
477 }
478 if ($user['email']) {
479 $this->cObj->sendNotifyEmail($msg, $user['email'], '', $this->conf['email_from'], $this->conf['email_fromName'], $this->conf['replyTo']);
480 }
481
482 return '';
483 }
484
485 /**
486 * Shows logout form
487 *
488 * @return string The content.
489 */
490 protected function showLogout()
491 {
492 $subpart = $this->cObj->getSubpart($this->template, '###TEMPLATE_LOGOUT###');
493 $subpartArray = ($linkpartArray = array());
494 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('status_header', $this->conf['logoutHeader_stdWrap.']);
495 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('status_message', $this->conf['logoutMessage_stdWrap.']);
496 $this->cObj->stdWrap($this->flexFormValue('message', 's_status'), $this->conf['logoutMessage_stdWrap.']);
497 $markerArray['###LEGEND###'] = $this->pi_getLL('logout', '', true);
498 $markerArray['###ACTION_URI###'] = $this->getPageLink('', array(), true);
499 $markerArray['###LOGOUT_LABEL###'] = $this->pi_getLL('logout', '', true);
500 $markerArray['###NAME###'] = htmlspecialchars($this->frontendController->fe_user->user['name']);
501 $markerArray['###STORAGE_PID###'] = $this->spid;
502 $markerArray['###USERNAME###'] = htmlspecialchars($this->frontendController->fe_user->user['username']);
503 $markerArray['###USERNAME_LABEL###'] = $this->pi_getLL('username', '', true);
504 $markerArray['###NOREDIRECT###'] = $this->noRedirect ? '1' : '0';
505 $markerArray['###PREFIXID###'] = $this->prefixId;
506 $markerArray = array_merge($markerArray, $this->getUserFieldMarkers());
507 if ($this->redirectUrl) {
508 // Use redirectUrl for action tag because of possible access restricted pages
509 $markerArray['###ACTION_URI###'] = htmlspecialchars($this->redirectUrl);
510 $this->redirectUrl = '';
511 }
512 return $this->cObj->substituteMarkerArrayCached($subpart, $markerArray, $subpartArray, $linkpartArray);
513 }
514
515 /**
516 * Shows login form
517 *
518 * @return string Content
519 */
520 protected function showLogin()
521 {
522 $subpart = $this->cObj->getSubpart($this->template, '###TEMPLATE_LOGIN###');
523 $subpartArray = ($linkpartArray = ($markerArray = array()));
524 $gpRedirectUrl = '';
525 $markerArray['###LEGEND###'] = $this->pi_getLL('oLabel_header_welcome', '', true);
526 if ($this->logintype === 'login') {
527 if ($this->userIsLoggedIn) {
528 // login success
529 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('success_header', $this->conf['successHeader_stdWrap.']);
530 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('success_message', $this->conf['successMessage_stdWrap.']);
531 $markerArray = array_merge($markerArray, $this->getUserFieldMarkers());
532 $subpartArray['###LOGIN_FORM###'] = '';
533 // Hook for general actions after after login has been confirmed (by Thomas Danzl <thomas@danzl.org>)
534 if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['login_confirmed']) {
535 $_params = array();
536 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['login_confirmed'] as $_funcRef) {
537 if ($_funcRef) {
538 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
539 }
540 }
541 }
542 // show logout form directly
543 if ($this->conf['showLogoutFormAfterLogin']) {
544 $this->redirectUrl = '';
545 return $this->showLogout();
546 }
547 } else {
548 // Hook for general actions on login error
549 if (
550 isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['login_error'])
551 && is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['login_error'])
552 ) {
553 $params = array();
554 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['login_error'] as $funcRef) {
555 if ($funcRef) {
556 GeneralUtility::callUserFunction($funcRef, $params, $this);
557 }
558 }
559 }
560 // login error
561 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('error_header', $this->conf['errorHeader_stdWrap.']);
562 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('error_message', $this->conf['errorMessage_stdWrap.']);
563 $gpRedirectUrl = GeneralUtility::_GP('redirect_url');
564 }
565 } else {
566 if ($this->logintype === 'logout') {
567 // login form after logout
568 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('logout_header', $this->conf['logoutHeader_stdWrap.']);
569 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('logout_message', $this->conf['logoutMessage_stdWrap.']);
570 } else {
571 // login form
572 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('welcome_header', $this->conf['welcomeHeader_stdWrap.']);
573 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('welcome_message', $this->conf['welcomeMessage_stdWrap.']);
574 }
575 }
576
577 // This hook allows to call User JS functions.
578 // The methods should also set the required JS functions to get included
579 $onSubmit = '';
580 $extraHidden = '';
581 $onSubmitAr = array();
582 $extraHiddenAr = array();
583 // Check for referer redirect method. if present, save referer in form field
584 if (GeneralUtility::inList($this->conf['redirectMode'], 'referer') || GeneralUtility::inList($this->conf['redirectMode'], 'refererDomains')) {
585 $referer = $this->referer ? $this->referer : GeneralUtility::getIndpEnv('HTTP_REFERER');
586 if ($referer) {
587 $extraHiddenAr[] = '<input type="hidden" name="referer" value="' . htmlspecialchars($referer) . '" />';
588 if ($this->piVars['redirectReferrer'] === 'off') {
589 $extraHiddenAr[] = '<input type="hidden" name="' . $this->prefixId . '[redirectReferrer]" value="off" />';
590 }
591 }
592 }
593 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['loginFormOnSubmitFuncs'])) {
594 $_params = array();
595 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['loginFormOnSubmitFuncs'] as $funcRef) {
596 list($onSub, $hid) = GeneralUtility::callUserFunction($funcRef, $_params, $this);
597 $onSubmitAr[] = $onSub;
598 $extraHiddenAr[] = $hid;
599 }
600 }
601 if (!empty($onSubmitAr)) {
602 $onSubmit = implode('; ', $onSubmitAr) . '; return true;';
603 }
604 if (!empty($extraHiddenAr)) {
605 $extraHidden = implode(LF, $extraHiddenAr);
606 }
607 if (!$gpRedirectUrl && $this->redirectUrl) {
608 $gpRedirectUrl = $this->redirectUrl;
609 }
610 // Login form
611 $markerArray['###ACTION_URI###'] = $this->getPageLink('', array(), true);
612 // Used by kb_md5fepw extension...
613 $markerArray['###EXTRA_HIDDEN###'] = $extraHidden;
614 $markerArray['###LEGEND###'] = $this->pi_getLL('login', '', true);
615 $markerArray['###LOGIN_LABEL###'] = $this->pi_getLL('login', '', true);
616 // Used by kb_md5fepw extension...
617 $markerArray['###ON_SUBMIT###'] = $onSubmit;
618 $markerArray['###PASSWORD_LABEL###'] = $this->pi_getLL('password', '', true);
619 $markerArray['###STORAGE_PID###'] = $this->spid;
620 $markerArray['###USERNAME_LABEL###'] = $this->pi_getLL('username', '', true);
621 $markerArray['###REDIRECT_URL###'] = htmlspecialchars($gpRedirectUrl);
622 $markerArray['###NOREDIRECT###'] = $this->noRedirect ? '1' : '0';
623 $markerArray['###PREFIXID###'] = $this->prefixId;
624 $markerArray = array_merge($markerArray, $this->getUserFieldMarkers());
625 if ($this->conf['showForgotPasswordLink']) {
626 $linkpartArray['###FORGOT_PASSWORD_LINK###'] = explode('|', $this->getPageLink('|', array($this->prefixId . '[forgot]' => 1)));
627 $markerArray['###FORGOT_PASSWORD###'] = $this->pi_getLL('ll_forgot_header', '', true);
628 } else {
629 $subpartArray['###FORGOTP_VALID###'] = '';
630 }
631 // The permanent login checkbox should only be shown if permalogin is not deactivated (-1),
632 // not forced to be always active (2) and lifetime is greater than 0
633 $permalogin = (int)$GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'];
634 if (
635 $this->conf['showPermaLogin']
636 && ($permalogin === 0 || $permalogin === 1)
637 && $GLOBALS['TYPO3_CONF_VARS']['FE']['lifetime'] > 0
638 ) {
639 $markerArray['###PERMALOGIN###'] = $this->pi_getLL('permalogin', '', true);
640 if ($permalogin === 1) {
641 $markerArray['###PERMALOGIN_HIDDENFIELD_ATTRIBUTES###'] = 'disabled="disabled"';
642 $markerArray['###PERMALOGIN_CHECKBOX_ATTRIBUTES###'] = 'checked="checked"';
643 } else {
644 $markerArray['###PERMALOGIN_HIDDENFIELD_ATTRIBUTES###'] = '';
645 $markerArray['###PERMALOGIN_CHECKBOX_ATTRIBUTES###'] = '';
646 }
647 } else {
648 $subpartArray['###PERMALOGIN_VALID###'] = '';
649 }
650 return $this->cObj->substituteMarkerArrayCached($subpart, $markerArray, $subpartArray, $linkpartArray);
651 }
652
653 /**
654 * Process redirect methods. The function searches for a redirect url using all configured methods.
655 *
656 * @return array Redirect URLs
657 */
658 protected function processRedirect()
659 {
660 $redirect_url = array();
661 if ($this->conf['redirectMode']) {
662 $redirectMethods = GeneralUtility::trimExplode(',', $this->conf['redirectMode'], true);
663 foreach ($redirectMethods as $redirMethod) {
664 if ($this->frontendController->loginUser && $this->logintype === 'login') {
665 // Logintype is needed because the login-page wouldn't be accessible anymore after a login (would always redirect)
666 switch ($redirMethod) {
667 case 'groupLogin':
668 // taken from dkd_redirect_at_login written by Ingmar Schlecht; database-field changed
669 $groupData = $this->frontendController->fe_user->groupData;
670 if (!empty($groupData['uid'])) {
671
672 // take the first group with a redirect page
673 $userGroupTable = $this->frontendController->fe_user->usergroup_table;
674 /** @var QueryBuilder $queryBuilder */
675 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($userGroupTable);
676 $row = $queryBuilder
677 ->select('felogin_redirectPid')
678 ->from($userGroupTable)
679 ->where(
680 $queryBuilder->expr()->andX(
681 $queryBuilder->expr()->neq('felogin_redirectPid', $queryBuilder->quote('')),
682 $queryBuilder->expr()->in('uid', implode(',', $groupData['uid']))
683 )
684 )
685 ->execute()
686 ->fetch();
687
688 if ($row) {
689 $redirect_url[] = $this->pi_getPageLink($row['felogin_redirectPid']);
690 }
691 }
692 break;
693 case 'userLogin':
694
695 $userTable = $this->frontendController->fe_user->user_table;
696 /** @var QueryBuilder $queryBuilder */
697 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($userTable);
698 $row = $queryBuilder
699 ->select('felogin_redirectPid')
700 ->from($userTable)
701 ->where(
702 $queryBuilder->expr()->andX(
703 $queryBuilder->expr()->neq('felogin_redirectPid', $queryBuilder->quote('')),
704 $queryBuilder->expr()->eq(
705 $this->frontendController->fe_user->userid_column,
706 (int)$this->frontendController->fe_user->user['uid']
707 )
708 )
709 )
710 ->execute()
711 ->fetch();
712
713 if ($row) {
714 $redirect_url[] = $this->pi_getPageLink($row['felogin_redirectPid']);
715 }
716
717 break;
718 case 'login':
719 if ($this->conf['redirectPageLogin']) {
720 $redirect_url[] = $this->pi_getPageLink((int)$this->conf['redirectPageLogin']);
721 }
722 break;
723 case 'getpost':
724 $redirect_url[] = $this->redirectUrl;
725 break;
726 case 'referer':
727 // Avoid redirect when logging in after changing password
728 if ($this->piVars['redirectReferrer'] !== 'off') {
729 // Avoid forced logout, when trying to login immediately after a logout
730 $redirect_url[] = preg_replace('/[&?]logintype=[a-z]+/', '', $this->referer);
731 }
732 break;
733 case 'refererDomains':
734 // Auto redirect.
735 // Feature to redirect to the page where the user came from (HTTP_REFERER).
736 // Allowed domains to redirect to, can be configured with plugin.tx_felogin_pi1.domains
737 // Thanks to plan2.net / Martin Kutschker for implementing this feature.
738 // also avoid redirect when logging in after changing password
739 if ($this->conf['domains'] && $this->piVars['redirectReferrer'] !== 'off') {
740 $url = $this->referer;
741 // Is referring url allowed to redirect?
742 $match = array();
743 if (preg_match('#^http://([[:alnum:]._-]+)/#', $url, $match)) {
744 $redirect_domain = $match[1];
745 $found = false;
746 foreach (GeneralUtility::trimExplode(',', $this->conf['domains'], true) as $d) {
747 if (preg_match('/(?:^|\\.)' . $d . '$/', $redirect_domain)) {
748 $found = true;
749 break;
750 }
751 }
752 if (!$found) {
753 $url = '';
754 }
755 }
756 // Avoid forced logout, when trying to login immediately after a logout
757 if ($url) {
758 $redirect_url[] = preg_replace('/[&?]logintype=[a-z]+/', '', $url);
759 }
760 }
761 break;
762 }
763 } elseif ($this->logintype === 'login') {
764 // after login-error
765 switch ($redirMethod) {
766 case 'loginError':
767 if ($this->conf['redirectPageLoginError']) {
768 $redirect_url[] = $this->pi_getPageLink((int)$this->conf['redirectPageLoginError']);
769 }
770 break;
771 }
772 } elseif ($this->logintype == '' && $redirMethod == 'login' && $this->conf['redirectPageLogin']) {
773 // If login and page not accessible
774 $this->cObj->typoLink('', array(
775 'parameter' => $this->conf['redirectPageLogin'],
776 'linkAccessRestrictedPages' => true
777 ));
778 $redirect_url[] = $this->cObj->lastTypoLinkUrl;
779 } elseif ($this->logintype == '' && $redirMethod == 'logout' && $this->conf['redirectPageLogout'] && $this->frontendController->loginUser) {
780 // If logout and page not accessible
781 $redirect_url[] = $this->pi_getPageLink((int)$this->conf['redirectPageLogout']);
782 } elseif ($this->logintype === 'logout') {
783 // after logout
784 // Hook for general actions after after logout has been confirmed
785 if ($this->logintype === 'logout' && $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['logout_confirmed']) {
786 $_params = array();
787 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['logout_confirmed'] as $_funcRef) {
788 if ($_funcRef) {
789 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
790 }
791 }
792 }
793 switch ($redirMethod) {
794 case 'logout':
795 if ($this->conf['redirectPageLogout']) {
796 $redirect_url[] = $this->pi_getPageLink((int)$this->conf['redirectPageLogout']);
797 }
798 break;
799 }
800 } else {
801 // not logged in
802 // Placeholder for maybe future options
803 switch ($redirMethod) {
804 case 'getpost':
805 // Preserve the get/post value
806 $redirect_url[] = $this->redirectUrl;
807 break;
808 }
809 }
810 }
811 }
812 // Remove empty values
813 if (!empty($redirect_url)) {
814 return GeneralUtility::trimExplode(',', implode(',', $redirect_url), true);
815 }
816 return array();
817 }
818
819 /**
820 * Reads flexform configuration and merge it with $this->conf
821 *
822 * @return void
823 */
824 protected function mergeflexFormValuesIntoConf()
825 {
826 $flex = array();
827 if ($this->flexFormValue('showForgotPassword', 'sDEF')) {
828 $flex['showForgotPasswordLink'] = $this->flexFormValue('showForgotPassword', 'sDEF');
829 }
830 if ($this->flexFormValue('showPermaLogin', 'sDEF')) {
831 $flex['showPermaLogin'] = $this->flexFormValue('showPermaLogin', 'sDEF');
832 }
833 if ($this->flexFormValue('showLogoutFormAfterLogin', 'sDEF')) {
834 $flex['showLogoutFormAfterLogin'] = $this->flexFormValue('showLogoutFormAfterLogin', 'sDEF');
835 }
836 if ($this->flexFormValue('pages', 'sDEF')) {
837 $flex['pages'] = $this->flexFormValue('pages', 'sDEF');
838 }
839 if ($this->flexFormValue('recursive', 'sDEF')) {
840 $flex['recursive'] = $this->flexFormValue('recursive', 'sDEF');
841 }
842 if ($this->flexFormValue('templateFile', 'sDEF')) {
843 $flex['templateFile'] = $this->uploadDir . $this->flexFormValue('templateFile', 'sDEF');
844 }
845 if ($this->flexFormValue('redirectMode', 's_redirect')) {
846 $flex['redirectMode'] = $this->flexFormValue('redirectMode', 's_redirect');
847 }
848 if ($this->flexFormValue('redirectFirstMethod', 's_redirect')) {
849 $flex['redirectFirstMethod'] = $this->flexFormValue('redirectFirstMethod', 's_redirect');
850 }
851 if ($this->flexFormValue('redirectDisable', 's_redirect')) {
852 $flex['redirectDisable'] = $this->flexFormValue('redirectDisable', 's_redirect');
853 }
854 if ($this->flexFormValue('redirectPageLogin', 's_redirect')) {
855 $flex['redirectPageLogin'] = $this->flexFormValue('redirectPageLogin', 's_redirect');
856 }
857 if ($this->flexFormValue('redirectPageLoginError', 's_redirect')) {
858 $flex['redirectPageLoginError'] = $this->flexFormValue('redirectPageLoginError', 's_redirect');
859 }
860 if ($this->flexFormValue('redirectPageLogout', 's_redirect')) {
861 $flex['redirectPageLogout'] = $this->flexFormValue('redirectPageLogout', 's_redirect');
862 }
863 $pid = $flex['pages'] ? $this->pi_getPidList($flex['pages'], $flex['recursive']) : 0;
864 if ($pid > 0) {
865 $flex['storagePid'] = $pid;
866 }
867 $this->conf = array_merge($this->conf, $flex);
868 }
869
870 /**
871 * Loads a variable from the flexform
872 *
873 * @param string $var Name of variable
874 * @param string $sheet Name of sheet
875 * @return string Value of var
876 */
877 protected function flexFormValue($var, $sheet)
878 {
879 return $this->pi_getFFvalue($this->cObj->data['pi_flexform'], $var, $sheet);
880 }
881
882 /**
883 * Generate link with typolink function
884 *
885 * @param string $label Linktext
886 * @param array $piVars Link vars
887 * @param bool $returnUrl TRUE: returns only url FALSE (default) returns the link)
888 * @return string Link or url
889 */
890 protected function getPageLink($label, $piVars, $returnUrl = false)
891 {
892 $additionalParams = '';
893 if (!empty($piVars)) {
894 foreach ($piVars as $key => $val) {
895 $additionalParams .= '&' . $key . '=' . $val;
896 }
897 }
898 // Should GETvars be preserved?
899 if ($this->conf['preserveGETvars']) {
900 $additionalParams .= $this->getPreserveGetVars();
901 }
902 $this->conf['linkConfig.']['parameter'] = $this->frontendController->id;
903 if ($additionalParams) {
904 $this->conf['linkConfig.']['additionalParams'] = $additionalParams;
905 }
906 if ($returnUrl) {
907 return htmlspecialchars($this->cObj->typoLink_URL($this->conf['linkConfig.']));
908 } else {
909 return $this->cObj->typoLink($label, $this->conf['linkConfig.']);
910 }
911 }
912
913 /**
914 * Add additional parameters for links according to TS setting preserveGETvars.
915 * Possible values are "all" or a comma separated list of allowed GET-vars.
916 * Supports multi-dimensional GET-vars.
917 * Some hardcoded values are dropped.
918 *
919 * @return string additionalParams-string
920 */
921 protected function getPreserveGetVars()
922 {
923 $getVars = GeneralUtility::_GET();
924 unset(
925 $getVars['id'],
926 $getVars['no_cache'],
927 $getVars['logintype'],
928 $getVars['redirect_url'],
929 $getVars['cHash'],
930 $getVars[$this->prefixId]
931 );
932 if ($this->conf['preserveGETvars'] === 'all') {
933 $preserveQueryParts = $getVars;
934 } else {
935 $preserveQueryParts = GeneralUtility::trimExplode(',', $this->conf['preserveGETvars']);
936 $preserveQueryParts = GeneralUtility::explodeUrl2Array(implode('=1&', $preserveQueryParts) . '=1', true);
937 $preserveQueryParts = \TYPO3\CMS\Core\Utility\ArrayUtility::intersectRecursive($getVars, $preserveQueryParts);
938 }
939 $parameters = GeneralUtility::implodeArrayForUrl('', $preserveQueryParts);
940 return $parameters;
941 }
942
943 /**
944 * Is used by forgot password - function with md5 option.
945 * @param int $len Length of new password
946 * @return string New password
947 */
948 protected function generatePassword($len)
949 {
950 $pass = '';
951 while ($len--) {
952 $char = rand(0, 35);
953 if ($char < 10) {
954 $pass .= '' . $char;
955 } else {
956 $pass .= chr($char - 10 + 97);
957 }
958 }
959 return $pass;
960 }
961
962 /**
963 * Returns the header / message value from flexform if present, else from locallang.xlf
964 *
965 * @param string $label label name
966 * @param array $stdWrapArray TS stdWrap array
967 * @return string label text
968 */
969 protected function getDisplayText($label, $stdWrapArray = array())
970 {
971 $text = $this->flexFormValue($label, 's_messages') ? $this->cObj->stdWrap($this->flexFormValue($label, 's_messages'), $stdWrapArray) : $this->cObj->stdWrap($this->pi_getLL('ll_' . $label), $stdWrapArray);
972 $replace = $this->getUserFieldMarkers();
973 return strtr($text, $replace);
974 }
975
976 /**
977 * Returns Array of markers filled with user fields
978 *
979 * @return array Marker array
980 */
981 protected function getUserFieldMarkers()
982 {
983 $marker = array();
984 // replace markers with fe_user data
985 if ($this->frontendController->fe_user->user) {
986 // All fields of fe_user will be replaced, scheme is ###FEUSER_FIELDNAME###
987 foreach ($this->frontendController->fe_user->user as $field => $value) {
988 $marker['###FEUSER_' . GeneralUtility::strtoupper($field) . '###'] = $this->cObj->stdWrap($value, $this->conf['userfields.'][$field . '.']);
989 }
990 // Add ###USER### for compatibility
991 $marker['###USER###'] = $marker['###FEUSER_USERNAME###'];
992 }
993 return $marker;
994 }
995
996 /**
997 * Returns a valid and XSS cleaned url for redirect, checked against configuration "allowedRedirectHosts"
998 *
999 * @param string $url
1000 * @return string cleaned referer or empty string if not valid
1001 */
1002 protected function validateRedirectUrl($url)
1003 {
1004 $url = strval($url);
1005 if ($url === '') {
1006 return '';
1007 }
1008 // Validate the URL:
1009 if ($this->isRelativeUrl($url) || $this->isInCurrentDomain($url) || $this->isInLocalDomain($url)) {
1010 return $url;
1011 }
1012 // URL is not allowed
1013 GeneralUtility::sysLog(sprintf($this->pi_getLL('noValidRedirectUrl'), $url), 'felogin', GeneralUtility::SYSLOG_SEVERITY_WARNING);
1014 return '';
1015 }
1016
1017 /**
1018 * Determines whether the URL is on the current host and belongs to the
1019 * current TYPO3 installation. The scheme part is ignored in the comparison.
1020 *
1021 * @param string $url URL to be checked
1022 * @return bool Whether the URL belongs to the current TYPO3 installation
1023 */
1024 protected function isInCurrentDomain($url)
1025 {
1026 $urlWithoutSchema = preg_replace('#^https?://#', '', $url);
1027 $siteUrlWithoutSchema = preg_replace('#^https?://#', '', GeneralUtility::getIndpEnv('TYPO3_SITE_URL'));
1028 return StringUtility::beginsWith($urlWithoutSchema . '/', GeneralUtility::getIndpEnv('HTTP_HOST') . '/')
1029 && StringUtility::beginsWith($urlWithoutSchema, $siteUrlWithoutSchema);
1030 }
1031
1032 /**
1033 * Determines whether the URL matches a domain
1034 * in the sys_domain database table.
1035 *
1036 * @param string $url Absolute URL which needs to be checked
1037 * @return bool Whether the URL is considered to be local
1038 */
1039 protected function isInLocalDomain($url)
1040 {
1041 $result = false;
1042 if (GeneralUtility::isValidUrl($url)) {
1043 $parsedUrl = parse_url($url);
1044 if ($parsedUrl['scheme'] === 'http' || $parsedUrl['scheme'] === 'https') {
1045 $host = $parsedUrl['host'];
1046 // Removes the last path segment and slash sequences like /// (if given):
1047 $path = preg_replace('#/+[^/]*$#', '', $parsedUrl['path']);
1048
1049 /** @var QueryBuilder $queryBuilder */
1050 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_domain');
1051 $localDomains = $queryBuilder->select('domainName')
1052 ->from('sys_domain')
1053 ->execute()
1054 ->fetchAll();
1055
1056 if (is_array($localDomains)) {
1057 foreach ($localDomains as $localDomain) {
1058 // strip trailing slashes (if given)
1059 $domainName = rtrim($localDomain['domainName'], '/');
1060 if (GeneralUtility::isFirstPartOfStr($host . $path . '/', $domainName . '/')) {
1061 $result = true;
1062 break;
1063 }
1064 }
1065 }
1066 }
1067 }
1068 return $result;
1069 }
1070
1071 /**
1072 * Determines whether the URL is relative to the
1073 * current TYPO3 installation.
1074 *
1075 * @param string $url URL which needs to be checked
1076 * @return bool Whether the URL is considered to be relative
1077 */
1078 protected function isRelativeUrl($url)
1079 {
1080 $url = GeneralUtility::sanitizeLocalUrl($url);
1081 if (!empty($url)) {
1082 $parsedUrl = @parse_url($url);
1083 if ($parsedUrl !== false && !isset($parsedUrl['scheme']) && !isset($parsedUrl['host'])) {
1084 // If the relative URL starts with a slash, we need to check if it's within the current site path
1085 return $parsedUrl['path'][0] !== '/' || GeneralUtility::isFirstPartOfStr($parsedUrl['path'], GeneralUtility::getIndpEnv('TYPO3_SITE_PATH'));
1086 }
1087 }
1088 return false;
1089 }
1090 }