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