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