[FEATURE] felogin: Introduce new label for the legend marker
[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('legend', $this->pi_getLL('reset_password', '', 1), 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 $link = $this->pi_getPageLink($GLOBALS['TSFE']->id, '', array(
365 $this->prefixId . '[user]' => $user['uid'],
366 $this->prefixId . '[forgothash]' => $randHash
367 ));
368
369 // Prefix link if necessary
370 if ($isFeloginBaseURL) {
371 // First priority, use specific base URL
372 // "absRefPrefix" must be removed first, otherwise URL will be prepended twice
373 if (!empty($GLOBALS['TSFE']->absRefPrefix)) {
374 $link = substr($link, strlen($GLOBALS['TSFE']->absRefPrefix));
375 }
376 $link = $this->conf['feloginBaseURL'] . $link;
377 } elseif ($isAbsRelPrefix) {
378 // Second priority
379 // absRefPrefix must not necessarily contain a hostname and URL scheme, so add it if needed
380 $link = t3lib_div::locationHeaderUrl($link);
381 } elseif ($isBaseURL) {
382 // Third priority
383 // Add the global base URL to the link
384 $link = $GLOBALS['TSFE']->baseUrlWrap($link);
385 } else {
386 // no prefix is set, return the error
387 return $this->pi_getLL('ll_change_password_nolinkprefix_message');
388 }
389
390 $msg = sprintf($this->pi_getLL('ll_forgot_validate_reset_password', '', 0), $user['username'], $link, $validEndString);
391
392 // no RDCT - Links for security reasons
393 $oldSetting = $GLOBALS['TSFE']->config['config']['notification_email_urlmode'];
394 $GLOBALS['TSFE']->config['config']['notification_email_urlmode'] = 0;
395 // send the email
396 $this->cObj->sendNotifyEmail($msg, $user['email'], '', $this->conf['email_from'], $this->conf['email_fromName'], $this->conf['replyTo']);
397 // restore settings
398 $GLOBALS['TSFE']->config['config']['notification_email_urlmode'] = $oldSetting;
399
400 return '';
401 }
402
403 /**
404 * Shows logout form
405 *
406 * @return string The content.
407 */
408 protected function showLogout() {
409 $subpart = $this->cObj->getSubpart($this->template, '###TEMPLATE_LOGOUT###');
410 $subpartArray = $linkpartArray = array();
411
412 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('status_header',$this->conf['logoutHeader_stdWrap.']);
413 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('status_message', $this->conf['logoutMessage_stdWrap.']);
414 $this->cObj->stdWrap($this->flexFormValue('message', 's_status'), $this->conf['logoutMessage_stdWrap.']);
415
416 $markerArray['###LEGEND###'] = $this->pi_getLL('logout', '', 1);
417 $markerArray['###ACTION_URI###'] = $this->getPageLink('',array(),TRUE);
418 $markerArray['###LOGOUT_LABEL###'] = $this->pi_getLL('logout', '', 1);
419 $markerArray['###NAME###'] = htmlspecialchars($GLOBALS['TSFE']->fe_user->user['name']);
420 $markerArray['###STORAGE_PID###'] = $this->spid;
421 $markerArray['###USERNAME###'] = htmlspecialchars($GLOBALS['TSFE']->fe_user->user['username']);
422 $markerArray['###USERNAME_LABEL###'] = $this->pi_getLL('username', '', 1);
423 $markerArray['###NOREDIRECT###'] = $this->noRedirect ? '1' : '0';
424 $markerArray['###PREFIXID###'] = $this->prefixId;
425 $markerArray = array_merge($markerArray, $this->getUserFieldMarkers());
426
427 if ($this->redirectUrl) {
428 // use redirectUrl for action tag because of possible access restricted pages
429 $markerArray['###ACTION_URI###'] = htmlspecialchars($this->redirectUrl);
430 $this->redirectUrl = '';
431 }
432 return $this->cObj->substituteMarkerArrayCached($subpart, $markerArray, $subpartArray, $linkpartArray);
433 }
434
435 /**
436 * Shows login form
437 *
438 * @return string content
439 */
440 protected function showLogin() {
441 $subpart = $this->cObj->getSubpart($this->template, '###TEMPLATE_LOGIN###');
442 $subpartArray = $linkpartArray = $markerArray = array();
443
444 $gpRedirectUrl = '';
445
446 $markerArray['###LEGEND###'] = $this->pi_getLL('oLabel_header_welcome', '', 1);
447
448 if($this->logintype === 'login') {
449 if($this->userIsLoggedIn) {
450 // login success
451 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('success_header',$this->conf['successHeader_stdWrap.']);
452 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('success_message', $this->conf['successMessage_stdWrap.']);
453 $markerArray = array_merge($markerArray, $this->getUserFieldMarkers());
454 $subpartArray['###LOGIN_FORM###'] = '';
455
456 // Hook for general actions after after login has been confirmed (by Thomas Danzl <thomas@danzl.org>)
457 if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['login_confirmed']) {
458 $_params = array();
459 foreach($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['login_confirmed'] as $_funcRef) {
460 if ($_funcRef) {
461 t3lib_div::callUserFunction($_funcRef, $_params, $this);
462 }
463 }
464 }
465 // show logout form directly
466 if ($this->conf['showLogoutFormAfterLogin']) {
467 $this->redirectUrl = '';
468 return $this->showLogout();
469 }
470 } else {
471 // login error
472 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('error_header',$this->conf['errorHeader_stdWrap.']);
473 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('error_message',$this->conf['errorMessage_stdWrap.']);
474 $gpRedirectUrl = t3lib_div::_GP('redirect_url');
475 }
476 } else {
477 if($this->logintype === 'logout') {
478 // login form after logout
479 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('logout_header', $this->conf['logoutHeader_stdWrap.']);
480 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('logout_message', $this->conf['logoutMessage_stdWrap.']);
481 } else {
482 // login form
483 $markerArray['###STATUS_HEADER###'] = $this->getDisplayText('welcome_header',$this->conf['welcomeHeader_stdWrap.']);
484 $markerArray['###STATUS_MESSAGE###'] = $this->getDisplayText('welcome_message',$this->conf['welcomeMessage_stdWrap.']);
485 }
486 }
487
488
489 // Hook (used by kb_md5fepw extension by Kraft Bernhard <kraftb@gmx.net>)
490 // This hook allows to call User JS functions.
491 // The methods should also set the required JS functions to get included
492 $onSubmit = '';
493 $extraHidden = '';
494 $onSubmitAr = array();
495 $extraHiddenAr = array();
496
497 // check for referer redirect method. if present, save referer in form field
498 if (t3lib_div::inList($this->conf['redirectMode'], 'referer') || t3lib_div::inList($this->conf['redirectMode'], 'refererDomains')) {
499 $referer = $this->referer ? $this->referer : t3lib_div::getIndpEnv('HTTP_REFERER');
500 if ($referer) {
501 $extraHiddenAr[] = '<input type="hidden" name="referer" value="' . htmlspecialchars($referer) . '" />';
502 }
503 }
504
505 if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['loginFormOnSubmitFuncs'])) {
506 $_params = array();
507 foreach($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['loginFormOnSubmitFuncs'] as $funcRef) {
508 list($onSub, $hid) = t3lib_div::callUserFunction($funcRef, $_params, $this);
509 $onSubmitAr[] = $onSub;
510 $extraHiddenAr[] = $hid;
511 }
512 }
513 if (count($onSubmitAr)) {
514 $onSubmit = implode('; ', $onSubmitAr).'; return true;';
515 }
516 if (count($extraHiddenAr)) {
517 $extraHidden = implode(LF, $extraHiddenAr);
518 }
519
520 if (!$gpRedirectUrl && $this->redirectUrl) {
521 $gpRedirectUrl = $this->redirectUrl;
522 }
523
524 // Login form
525 $markerArray['###ACTION_URI###'] = $this->getPageLink('',array(),TRUE);
526 $markerArray['###EXTRA_HIDDEN###'] = $extraHidden; // used by kb_md5fepw extension...
527 $markerArray['###LEGEND###'] = $this->pi_getLL('login', '', 1);
528 $markerArray['###LOGIN_LABEL###'] = $this->pi_getLL('login', '', 1);
529 $markerArray['###ON_SUBMIT###'] = $onSubmit; // used by kb_md5fepw extension...
530 $markerArray['###PASSWORD_LABEL###'] = $this->pi_getLL('password', '', 1);
531 $markerArray['###STORAGE_PID###'] = $this->spid;
532 $markerArray['###USERNAME_LABEL###'] = $this->pi_getLL('username', '', 1);
533 $markerArray['###REDIRECT_URL###'] = htmlspecialchars($gpRedirectUrl);
534 $markerArray['###NOREDIRECT###'] = $this->noRedirect ? '1' : '0';
535 $markerArray['###PREFIXID###'] = $this->prefixId;
536 $markerArray = array_merge($markerArray, $this->getUserFieldMarkers());
537
538 if ($this->flexFormValue('showForgotPassword','sDEF') || $this->conf['showForgotPasswordLink']) {
539 $linkpartArray['###FORGOT_PASSWORD_LINK###'] = explode('|',$this->getPageLink('|',array($this->prefixId.'[forgot]'=>1)));
540 $markerArray['###FORGOT_PASSWORD###'] = $this->pi_getLL('ll_forgot_header', '', 1);
541 } else {
542 $subpartArray['###FORGOTP_VALID###'] = '';
543 }
544
545
546 // 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
547 if ($this->conf['showPermaLogin'] && t3lib_div::inList('0,1', $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin']) && $GLOBALS['TYPO3_CONF_VARS']['FE']['lifetime'] > 0) {
548 $markerArray['###PERMALOGIN###'] = $this->pi_getLL('permalogin', '', 1);
549 if($GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 1) {
550 $markerArray['###PERMALOGIN_HIDDENFIELD_ATTRIBUTES###'] = 'disabled="disabled"';
551 $markerArray['###PERMALOGIN_CHECKBOX_ATTRIBUTES###'] = 'checked="checked"';
552 } else {
553 $markerArray['###PERMALOGIN_HIDDENFIELD_ATTRIBUTES###'] = '';
554 $markerArray['###PERMALOGIN_CHECKBOX_ATTRIBUTES###'] = '';
555 }
556 } else {
557 $subpartArray['###PERMALOGIN_VALID###'] = '';
558 }
559 return $this->cObj->substituteMarkerArrayCached($subpart, $markerArray, $subpartArray, $linkpartArray);
560 }
561
562 /**
563 * Process redirect methods. The function searches for a redirect url using all configured methods.
564 *
565 * @return string redirect url
566 */
567 protected function processRedirect() {
568 $redirect_url = array();
569 if ($this->conf['redirectMode']) {
570 $redirectMethods = t3lib_div::trimExplode(',', $this->conf['redirectMode'], TRUE);
571 foreach ($redirectMethods as $redirMethod) {
572 if ($GLOBALS['TSFE']->loginUser && $this->logintype === 'login') {
573 // logintype is needed because the login-page wouldn't be accessible anymore after a login (would always redirect)
574 switch ($redirMethod) {
575 case 'groupLogin': // taken from dkd_redirect_at_login written by Ingmar Schlecht; database-field changed
576 $groupData = $GLOBALS['TSFE']->fe_user->groupData;
577 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
578 'felogin_redirectPid',
579 $GLOBALS['TSFE']->fe_user->usergroup_table,
580 'felogin_redirectPid<>\'\' AND uid IN (' . implode(',', $groupData['uid']) . ')'
581 );
582 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res)) {
583 $redirect_url[] = $this->pi_getPageLink($row[0]); // take the first group with a redirect page
584 }
585 break;
586 case 'userLogin':
587 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
588 'felogin_redirectPid',
589 $GLOBALS['TSFE']->fe_user->user_table,
590 $GLOBALS['TSFE']->fe_user->userid_column . '=' . $GLOBALS['TSFE']->fe_user->user['uid'] . ' AND felogin_redirectPid<>\'\''
591 );
592 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res)) {
593 $redirect_url[] = $this->pi_getPageLink($row[0]);
594 }
595 break;
596 case 'login':
597 if ($this->conf['redirectPageLogin']) {
598 $redirect_url[] = $this->pi_getPageLink(intval($this->conf['redirectPageLogin']));
599 }
600 break;
601 case 'getpost':
602 $redirect_url[] = $this->redirectUrl;
603 break;
604 case 'referer':
605 // avoid forced logout, when trying to login immediatly after a logout
606 $redirect_url[] = preg_replace('/[&?]logintype=[a-z]+/', '', $this->referer);
607 break;
608 case 'refererDomains':
609 // Auto redirect.
610 // Feature to redirect to the page where the user came from (HTTP_REFERER).
611 // Allowed domains to redirect to, can be configured with plugin.tx_felogin_pi1.domains
612 // Thanks to plan2.net / Martin Kutschker for implementing this feature.
613 if ($this->conf['domains']) {
614 $url = $this->referer;
615 // is referring url allowed to redirect?
616 $match = array();
617 if (preg_match('/^http://([[:alnum:]._-]+)//', $url, $match)) {
618 $redirect_domain = $match[1];
619 $found = FALSE;
620 foreach(t3lib_div::trimExplode(',', $this->conf['domains'], TRUE) as $d) {
621 if (preg_match('/(^|\.)/'.$d.'$', $redirect_domain)) {
622 $found = TRUE;
623 break;
624 }
625 }
626 if (!$found) {
627 $url = '';
628 }
629 }
630
631 // Avoid forced logout, when trying to login immediatly after a logout
632 if ($url) {
633 $redirect_url[] = preg_replace('/[&?]logintype=[a-z]+/', '', $url);
634 }
635 }
636 break;
637 }
638 } elseif ($this->logintype === 'login') { // after login-error
639 switch ($redirMethod) {
640 case 'loginError':
641 if ($this->conf['redirectPageLoginError']) {
642 $redirect_url[] = $this->pi_getPageLink(intval($this->conf['redirectPageLoginError']));
643 }
644 break;
645 }
646 } elseif (($this->logintype == '') && ($redirMethod == 'login') && $this->conf['redirectPageLogin']) {
647 // if login and page not accessible
648 $this->cObj->typolink('', array(
649 'parameter' => $this->conf['redirectPageLogin'],
650 'linkAccessRestrictedPages' => TRUE,
651 ));
652 $redirect_url[] = $this->cObj->lastTypoLinkUrl;
653
654 } elseif (($this->logintype == '') && ($redirMethod == 'logout') && $this->conf['redirectPageLogout'] && $GLOBALS['TSFE']->loginUser) {
655 // if logout and page not accessible
656 $redirect_url[] = $this->pi_getPageLink(intval($this->conf['redirectPageLogout']));
657
658 } elseif ($this->logintype === 'logout') { // after logout
659
660 // Hook for general actions after after logout has been confirmed
661 if ($this->logintype === 'logout' && $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['logout_confirmed']) {
662 $_params = array();
663 foreach($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['felogin']['logout_confirmed'] as $_funcRef) {
664 if ($_funcRef) {
665 t3lib_div::callUserFunction($_funcRef, $_params, $this);
666 }
667 }
668 }
669
670 switch ($redirMethod) {
671 case 'logout':
672 if ($this->conf['redirectPageLogout']) {
673 $redirect_url[] = $this->pi_getPageLink(intval($this->conf['redirectPageLogout']));
674 }
675 break;
676 }
677 } else { // not logged in
678 // Placeholder for maybe future options
679 switch ($redirMethod) {
680 case 'getpost':
681 // preserve the get/post value
682 $redirect_url[] = $this->redirectUrl;
683 break;
684 }
685 }
686
687 }
688 }
689 // remove empty values
690 if (count($redirect_url)) {
691 return t3lib_div::trimExplode(',', implode(',', $redirect_url), TRUE);
692 } else {
693 return array();
694 }
695 }
696
697 /**
698 * Reads flexform configuration and merge it with $this->conf
699 *
700 * @return void
701 */
702 protected function mergeflexFormValuesIntoConf() {
703 $flex = array();
704 if ($this->flexFormValue('showForgotPassword', 'sDEF')) {
705 $flex['showForgotPassword'] = $this->flexFormValue('showForgotPassword','sDEF');
706 }
707
708 if ($this->flexFormValue('showPermaLogin', 'sDEF')) {
709 $flex['showPermaLogin'] = $this->flexFormValue('showPermaLogin', 'sDEF');
710 }
711
712 if ($this->flexFormValue('showLogoutFormAfterLogin', 'sDEF')) {
713 $flex['showLogoutFormAfterLogin'] = $this->flexFormValue('showLogoutFormAfterLogin', 'sDEF');
714 }
715
716 if ($this->flexFormValue('pages', 'sDEF')) {
717 $flex['pages'] = $this->flexFormValue('pages', 'sDEF');
718 }
719
720 if ($this->flexFormValue('recursive', 'sDEF')) {
721 $flex['recursive'] = $this->flexFormValue('recursive', 'sDEF');
722 }
723
724 if ($this->flexFormValue('templateFile', 'sDEF')) {
725 $flex['templateFile'] = $this->uploadDir . $this->flexFormValue('templateFile', 'sDEF');
726 }
727
728 if ($this->flexFormValue('redirectMode', 's_redirect')) {
729 $flex['redirectMode'] = $this->flexFormValue('redirectMode', 's_redirect');
730 }
731
732 if ($this->flexFormValue('redirectFirstMethod', 's_redirect')) {
733 $flex['redirectFirstMethod'] = $this->flexFormValue('redirectFirstMethod', 's_redirect');
734 }
735
736 if ($this->flexFormValue('redirectDisable', 's_redirect')) {
737 $flex['redirectDisable'] = $this->flexFormValue('redirectDisable', 's_redirect');
738 }
739
740 if ($this->flexFormValue('redirectPageLogin', 's_redirect')) {
741 $flex['redirectPageLogin'] = $this->flexFormValue('redirectPageLogin', 's_redirect');
742 }
743
744 if ($this->flexFormValue('redirectPageLoginError', 's_redirect')) {
745 $flex['redirectPageLoginError'] = $this->flexFormValue('redirectPageLoginError','s_redirect');
746 }
747
748 if ($this->flexFormValue('redirectPageLogout', 's_redirect')) {
749 $flex['redirectPageLogout'] = $this->flexFormValue('redirectPageLogout', 's_redirect');
750 }
751
752 $pid = $flex['pages'] ? $this->pi_getPidList($flex['pages'], $flex['recursive']) : 0;
753 if ($pid > 0) {
754 $flex['storagePid'] = $pid;
755 }
756
757 $this->conf = array_merge($this->conf, $flex);
758 }
759
760 /**
761 * Loads a variable from the flexform
762 *
763 * @param string name of variable
764 * @param string name of sheet
765 * @return string value of var
766 */
767 protected function flexFormValue($var, $sheet) {
768 return $this->pi_getFFvalue($this->cObj->data['pi_flexform'], $var,$sheet);
769 }
770
771 /**
772 * Generate link with typolink function
773 *
774 * @param string linktext
775 * @param array link vars
776 * @param boolean TRUE: returns only url FALSE (default) returns the link)
777 *
778 * @return string link or url
779 */
780 protected function getPageLink($label, $piVars,$returnUrl = FALSE) {
781 $additionalParams = '';
782
783 if (count($piVars)) {
784 foreach($piVars as $key=>$val) {
785 $additionalParams .= '&' . $key . '=' . $val;
786 }
787 }
788 // should GETvars be preserved?
789 if ($this->conf['preserveGETvars']) {
790 $additionalParams .= $this->getPreserveGetVars();
791 }
792
793 $this->conf['linkConfig.']['parameter'] = $GLOBALS['TSFE']->id;
794 if ($additionalParams) {
795 $this->conf['linkConfig.']['additionalParams'] = $additionalParams;
796 }
797
798 if ($returnUrl) {
799 return htmlspecialchars($this->cObj->typolink_url($this->conf['linkConfig.']));
800 } else {
801 return $this->cObj->typolink($label,$this->conf['linkConfig.']);
802 }
803 }
804
805 /**
806 * Is used by TS-setting preserveGETvars
807 * possible values are "all" or a commaseperated list of GET-vars
808 * they are used as additionalParams for link generation
809 *
810 * @return string additionalParams-string
811 */
812 protected function getPreserveGetVars() {
813
814 $params = '';
815 $preserveVars =! ($this->conf['preserveGETvars'] || $this->conf['preserveGETvars']=='all' ? array() : implode(',', (array)$this->conf['preserveGETvars']));
816 $getVars = t3lib_div::_GET();
817
818 foreach ($getVars as $key => $val) {
819 if (stristr($key,$this->prefixId) === FALSE) {
820 if (is_array($val)) {
821 foreach ($val as $key1 => $val1) {
822 if ($this->conf['preserveGETvars'] == 'all' || in_array($key . '[' . $key1 .']', $preserveVars)) {
823 $params .= '&' . $key . '[' . $key1 . ']=' . $val1;
824 }
825 }
826 } else {
827 if (!in_array($key, array('id','no_cache','logintype','redirect_url','cHash'))) {
828 $params .= '&' . $key . '=' . $val;
829 }
830 }
831 }
832 }
833 return $params;
834 }
835
836 /**
837 * Is used by forgot password - function with md5 option.
838 *
839 * @author Bernhard Kraft
840 *
841 * @param int length of new password
842 * @return string new password
843 */
844 protected function generatePassword($len) {
845 $pass = '';
846 while ($len--) {
847 $char = rand(0,35);
848 if ($char < 10) {
849 $pass .= '' . $char;
850 } else {
851 $pass .= chr($char - 10 + 97);
852 }
853 }
854 return $pass;
855 }
856
857 /**
858 * Returns the header / message value from flexform if present, else from locallang.xml
859 *
860 * @param string label name
861 * @param string TS stdWrap array
862 * @return string label text
863 */
864 protected function getDisplayText($label, $stdWrapArray=array()) {
865 $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);
866 $replace = $this->getUserFieldMarkers();
867 return strtr($text, $replace);
868 }
869
870 /**
871 * Returns Array of markers filled with user fields
872 *
873 * @return array marker array
874 */
875 protected function getUserFieldMarkers() {
876 $marker = array();
877 // replace markers with fe_user data
878 if ($GLOBALS['TSFE']->fe_user->user) {
879 // all fields of fe_user will be replaced, scheme is ###FEUSER_FIELDNAME###
880 foreach ($GLOBALS['TSFE']->fe_user->user as $field => $value) {
881 $marker['###FEUSER_' . t3lib_div::strtoupper($field) . '###'] = $this->cObj->stdWrap($value, $this->conf['userfields.'][$field . '.']);
882 }
883 // add ###USER### for compatibility
884 $marker['###USER###'] = $marker['###FEUSER_USERNAME###'];
885 }
886 return $marker;
887 }
888
889 /**
890 * Returns a valid and XSS cleaned url for redirect, checked against configuration "allowedRedirectHosts"
891 *
892 * @param string $url
893 * @return string cleaned referer or empty string if not valid
894 */
895 protected function validateRedirectUrl($url) {
896 $url = strval($url);
897 if ($url === '') {
898 return '';
899 }
900
901 $decodedUrl = rawurldecode($url);
902 $sanitizedUrl = t3lib_div::removeXSS($decodedUrl);
903
904 if ($decodedUrl !== $sanitizedUrl || preg_match('#["<>\\\]+#', $url)) {
905 t3lib_div::sysLog(sprintf($this->pi_getLL('xssAttackDetected'), $url), 'felogin', t3lib_div::SYSLOG_SEVERITY_WARNING);
906 return '';
907 }
908
909 // Validate the URL:
910 if ($this->isRelativeUrl($url) || $this->isInCurrentDomain($url) || $this->isInLocalDomain($url)) {
911 return $url;
912 }
913
914 // URL is not allowed
915 t3lib_div::sysLog(sprintf($this->pi_getLL('noValidRedirectUrl'), $url), 'felogin', t3lib_div::SYSLOG_SEVERITY_WARNING);
916 return '';
917 }
918
919 /**
920 * Determines whether the URL is on the current host
921 * and belongs to the current TYPO3 installation.
922 *
923 * @param string $url URL to be checked
924 * @return boolean Whether the URL belongs to the current TYPO3 installation
925 */
926 protected function isInCurrentDomain($url) {
927 return (t3lib_div::isOnCurrentHost($url) && t3lib_div::isFirstPartOfStr($url, t3lib_div::getIndpEnv('TYPO3_SITE_URL')));
928 }
929
930 /**
931 * Determines whether the URL matches a domain
932 * in the sys_domain databse table.
933 *
934 * @param string $url Absolute URL which needs to be checked
935 * @return boolean Whether the URL is considered to be local
936 */
937 protected function isInLocalDomain($url) {
938 $result = FALSE;
939
940 if (t3lib_div::isValidUrl($url)) {
941 $parsedUrl = parse_url($url);
942 if ($parsedUrl['scheme'] === 'http' || $parsedUrl['scheme'] === 'https' ) {
943 $host = $parsedUrl['host'];
944 // Removes the last path segment and slash sequences like /// (if given):
945 $path = preg_replace('#/+[^/]*$#', '', $parsedUrl['path']);
946
947 $localDomains = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
948 'domainName',
949 'sys_domain',
950 '1=1' . $this->cObj->enableFields('sys_domain')
951 );
952 if (is_array($localDomains)) {
953 foreach ($localDomains as $localDomain) {
954 // strip trailing slashes (if given)
955 $domainName = rtrim($localDomain['domainName'], '/');
956 if (t3lib_div::isFirstPartOfStr($host. $path . '/', $domainName . '/')) {
957 $result = TRUE;
958 break;
959 }
960 }
961 }
962 }
963 }
964 return $result;
965 }
966
967 /**
968 * Determines wether the URL is relative to the
969 * current TYPO3 installation.
970 *
971 * @param string $url URL which needs to be checked
972 * @return boolean Whether the URL is considered to be relative
973 */
974 protected function isRelativeUrl($url) {
975 $parsedUrl = @parse_url($url);
976 if ($parsedUrl !== FALSE && !isset($parsedUrl['scheme']) && !isset($parsedUrl['host'])) {
977 // If the relative URL starts with a slash, we need to check if it's within the current site path
978 return (!t3lib_div::isFirstPartOfStr($parsedUrl['path'], '/') || t3lib_div::isFirstPartOfStr($parsedUrl['path'], t3lib_div::getIndpEnv('TYPO3_SITE_PATH')));
979 }
980 return FALSE;
981 }
982 }
983
984
985
986 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/felogin/pi1/class.tx_felogin_pi1.php'])) {
987 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/felogin/pi1/class.tx_felogin_pi1.php']);
988 }
989
990 ?>