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