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