/**
	 * @param null|int  $id
	 * @param UserTable $user
	 */
	private function saveInviteEdit( $id, $user )
	{
		global $_CB_framework, $_CB_database, $_PLUGINS;

		$inviteLimit						=	(int) $this->params->get( 'invite_limit', null );
		$cbModerator						=	Application::User( (int) $user->get( 'id' ) )->isGlobalModerator();

		$row								=	new cbinvitesInviteTable();

		$row->load( (int) $id );

		$canAccess							=	false;
		$inviteCount						=	0;

		if ( ! $row->get( 'id' ) ) {
			if ( $cbModerator ) {
				$canAccess					=	true;
			} elseif ( $user->get( 'id' ) && Application::MyUser()->canViewAccessLevel( $this->params->get( 'invite_create_access', 2 ) ) ) {
				if ( $inviteLimit ) {
					$query					=	'SELECT COUNT(*)'
											.	"\n FROM " . $_CB_database->NameQuote( '#__comprofiler_plugin_invites' )
											.	"\n WHERE " . $_CB_database->NameQuote( 'user_id' ) . " = " . (int) $user->get( 'id' )
											.	"\n AND ( " . $_CB_database->NameQuote( 'user' ) . " IS NULL OR " . $_CB_database->NameQuote( 'user' ) . " = " . $_CB_database->Quote( '' ) . " )";
					$_CB_database->setQuery( $query );
					$inviteCount			=	(int) $_CB_database->loadResult();

					if ( $inviteCount < $inviteLimit ) {
						$canAccess			=	true;
					}
				} else {
					$canAccess				=	true;
				}
			}
		} elseif ( $cbModerator || ( $row->get( 'user_id' ) == $user->get( 'id' ) ) ) {
			$canAccess						=	true;
		}

		$profileUrl							=	$_CB_framework->userProfileUrl( $row->get( 'user_id', $user->get( 'id' ) ), false, 'cbinvitesTab' );

		if ( $canAccess && ( ! $row->isAccepted() ) ) {
			$toArray						=	explode( ',', $this->input( 'post/to', null, GetterInterface::STRING ) );

			if ( ( ! $this->params->get( 'invite_multiple', 1 ) ) && ( ! $cbModerator ) && ( count( $toArray ) > 1 ) ) {
				$this->showInviteEdit( $row->get( 'id' ), $user, CBTxt::T( 'Comma seperated lists are not supported! Please use a single To address.' ) ); return;
			}

			$sent							=	false;

			if ( ! empty( $toArray ) ) {
				foreach ( $toArray as $k => $to ) {
					if ( $k != 0 ) {
						$row->set( 'id', null );
						$row->set( 'code', null );
					}

					$orgTo					=	$row->get( 'to' );

					$row->set( 'to', $to );
					$row->set( 'subject', $this->input( 'post/subject', $row->get( 'subject' ), GetterInterface::STRING ) );

					if ( $this->params->get( 'invite_editor', 2 ) >= 2 ) {
						$row->set( 'body', $this->input( 'post/body', $row->get( 'body' ), GetterInterface::HTML ) );
					} else {
						$row->set( 'body', $this->input( 'post/body', $row->get( 'body' ), GetterInterface::STRING ) );
					}

					$row->set( 'user_id', (int) $this->input( 'post/user_id', $row->get( 'user_id', $user->get( 'id' ) ), GetterInterface::INT ) );

					if ( $cbModerator ) {
						$row->set( 'user', (int) $this->input( 'post/user', $row->get( 'user' ), GetterInterface::INT ) );
					}

					if ( ! $row->get( 'code' ) ) {
						$row->set( 'code', md5( uniqid() ) );
					}

					$new					=	( $row->get( 'id' ) ? false : true );

					if ( $new && $inviteLimit ) {
						$inviteCount++;

						if ( $inviteCount > $inviteLimit ) {
							cbRedirect( $profileUrl, CBTxt::T( 'Invite limit reached!' ), 'error' );
						}
					}

					if ( ! $row->get( 'user' ) ) {
						$toUser				=	new UserTable();

						$toUser->loadByEmail( $row->get( 'to' ) );
					} else {
						$toUser				=	CBuser::getUserDataInstance( (int) $row->get( 'user' ) );
					}

					if ( ! $row->get( 'to' ) ) {
						$row->setError( CBTxt::T( 'To address not specified.' ) );
					} elseif ( ! cbIsValidEmail( $row->get( 'to' ) ) ) {
						$row->setError( CBTxt::T( 'INVITE_TO_ADDRESS_INVALID', 'To address not valid: [to_address]', array( '[to_address]' => $row->get( 'to' ) ) ) );
					} elseif ( $toUser->id == $row->get( 'user_id' ) ) {
						$row->setError( CBTxt::T( 'You can not invite your self.' ) );
					} elseif ( $toUser->id && ( $row->get( 'to' ) != $orgTo ) ) {
						$row->setError( CBTxt::T( 'To address is already a user.' ) );
					} elseif ( ( ! $this->params->get( 'invite_duplicate', 0 ) ) && ( ! $cbModerator ) && $row->isDuplicate() ) {
						$row->setError( CBTxt::T( 'To address is already invited.' ) );
					} elseif ( $this->params->get( 'invite_captcha', 0 ) && ( ! $row->get( 'id' ) ) && ( $k == 0 ) && ( ! $cbModerator ) ) {
						$_PLUGINS->loadPluginGroup( 'user' );

						$_PLUGINS->trigger( 'onCheckCaptchaHtmlElements', array() );

						if ( $_PLUGINS->is_errors() ) {
							$row->setError( CBTxt::T( $_PLUGINS->getErrorMSG() ) );
						}
					}

					$_PLUGINS->trigger( 'invites_onBeforeInvite', array( &$row, $user ) );

					if ( $row->getError() || ( ! $row->store() ) ) {
						$this->showInviteEdit( $row->get( 'id' ), $user, CBTxt::T( 'INVITE_FAILED_SAVE_ERROR', 'Invite failed to save! Error: [error]', array( '[error]' => $row->getError() ) ) ); return;
					}

					if ( ( $new || ( ! $row->isSent() ) ) && ( ! $toUser->id ) ) {
						if ( ! $row->send() ) {
							$this->showInviteEdit( $row->get( 'id' ), $user, CBTxt::T( 'INVITE_FAILED_SEND_ERROR', 'Invite failed to send! Error: [error]', array( '[error]' => $row->getError() ) ) ); return;
						} else {
							$sent			=	true;
						}
					}

					$_PLUGINS->trigger( 'invites_onAfterInvite', array( $row, $sent, $user ) );
				}

				cbRedirect( $profileUrl, ( $sent ? CBTxt::T( 'Invite sent successfully!' ) : CBTxt::T( 'Invite saved successfully!' ) ) );
			} else {
				$this->showInviteEdit( $row->get( 'id' ), $user, CBTxt::T( 'To address not specified.' ) ); return;
			}
		} else {
			cbRedirect( $profileUrl, CBTxt::T( 'Not authorized.' ), 'error' );
		}
	}
Esempio n. 2
0
 /**
  * Logins on host CMS using any allowed authentication methods
  *
  * @param  string          $username        The username
  * @param  string|boolean  $password        Well, The password OR strictly boolean false for login without password
  * @param  boolean         $rememberMe      If login should be remembered in a cookie to be sent back to user's browser
  * @param  boolean         $message         If an alert message should be prepared on successful login
  * @param  string          $return          IN & OUT: IN: return URL NOT SEFED for normal login completition (unless an event says different), OUT: redirection url (no htmlspecialchars) NOT SEFED
  * @param  array           $messagesToUser  OUT: messages to display to user (html)
  * @param  array           $alertMessages   OUT: messages to alert to user (text)
  * @param  int             $loginType       0: username, 1: email, 2: username or email, 3: username, email or CMS authentication
  * @param  string          $secretKey       secretKey used for two step authentication
  * @return string                           Error message if error
  */
 public function login($username, $password, $rememberMe, $message, &$return, &$messagesToUser, &$alertMessages, $loginType = 0, $secretKey = null)
 {
     global $_CB_framework, $ueConfig, $_PLUGINS;
     $returnURL = null;
     $loggedIn = false;
     if (!$username || !$password && $password !== false) {
         $resultError = CBTxt::T('LOGIN_INCOMPLETE', 'Please complete the username and password fields.');
     } else {
         $_PLUGINS->loadPluginGroup('user');
         $_PLUGINS->trigger('onBeforeLogin', array(&$username, &$password, &$secretKey));
         $resultError = null;
         $showSysMessage = true;
         $stopLogin = false;
         $firstLogin = false;
         $row = new UserTable();
         if ($_PLUGINS->is_errors()) {
             $resultError = $_PLUGINS->getErrorMSG();
         } else {
             $foundUser = false;
             // Try login by CB authentication trigger:
             $_PLUGINS->trigger('onLoginAuthentication', array(&$username, &$password, &$row, $loginType, &$foundUser, &$stopLogin, &$resultError, &$messagesToUser, &$alertMessages, &$return, &$secretKey));
             if (!$foundUser) {
                 if ($loginType != 2) {
                     // login by username:
                     $foundUser = $row->loadByUsername($username) && ($password === false || $row->verifyPassword($password));
                 }
                 if (!$foundUser && $loginType >= 1) {
                     // login by email:
                     $foundUser = $row->loadByEmail($username) && ($password === false || $row->verifyPassword($password));
                     if ($foundUser) {
                         $username = $row->username;
                     }
                 }
                 if (!$foundUser && $loginType > 2) {
                     // If no result, try login by CMS authentication:
                     if ($_CB_framework->login($username, $password, $rememberMe, null, $secretKey)) {
                         $foundUser = $row->load((int) $_CB_framework->myId());
                         // core user might not have username set, so we use id (bug #3303 fix)
                         $this->cbSplitSingleName($row);
                         $row->confirmed = 1;
                         $row->approved = 1;
                         $row->store();
                         // synchronizes with comprofiler table
                         $loggedIn = true;
                     }
                 }
             }
             if ($foundUser) {
                 $returnPluginsOverrides = null;
                 $pluginResults = $_PLUGINS->trigger('onDuringLogin', array(&$row, 1, &$returnPluginsOverrides));
                 if ($returnPluginsOverrides) {
                     $return = $returnPluginsOverrides;
                 }
                 if (is_array($pluginResults) && count($pluginResults)) {
                     foreach ($pluginResults as $res) {
                         if (is_array($res)) {
                             if (isset($res['messagesToUser'])) {
                                 $messagesToUser[] = $res['messagesToUser'];
                             }
                             if (isset($res['alertMessage'])) {
                                 $alertMessages[] = $res['alertMessage'];
                             }
                             if (isset($res['showSysMessage'])) {
                                 $showSysMessage = $showSysMessage && $res['showSysMessage'];
                             }
                             if (isset($res['stopLogin'])) {
                                 $stopLogin = $stopLogin || $res['stopLogin'];
                             }
                         }
                     }
                 }
                 if ($_PLUGINS->is_errors()) {
                     $resultError = $_PLUGINS->getErrorMSG();
                 } elseif ($stopLogin) {
                     // login stopped: don't even check for errors...
                 } elseif ($row->approved == 2) {
                     $resultError = CBTxt::T('LOGIN_REJECTED', 'Your sign up request was rejected!');
                 } elseif ($row->confirmed != 1) {
                     if ($row->cbactivation == '') {
                         $row->store();
                         // just in case the activation code was missing
                     }
                     $cbNotification = new cbNotification();
                     $cbNotification->sendFromSystem($row->id, CBTxt::T(stripslashes($ueConfig['reg_pend_appr_sub'])), CBTxt::T(stripslashes($ueConfig['reg_pend_appr_msg'])), true, isset($ueConfig['reg_email_html']) ? (int) $ueConfig['reg_email_html'] : 0);
                     $resultError = CBTxt::T('LOGIN_NOT_CONFIRMED', 'Your sign up process is not yet complete! Please check again your email for further instructions that have just been resent. If you don\'t find the email, check your spam-box. Make sure that your email account options are not set to immediately delete spam. If that was the case, just try logging in again to receive a new instructions email.');
                 } elseif ($row->approved == 0) {
                     $resultError = CBTxt::T('LOGIN_NOT_APPROVED', 'Your account has not yet been approved!');
                 } elseif ($row->block == 1) {
                     $resultError = CBTxt::T('LOGIN_BLOCKED', 'Your login is blocked.');
                 } elseif ($row->lastvisitDate == '0000-00-00 00:00:00') {
                     $firstLogin = true;
                     if (isset($ueConfig['reg_first_visit_url']) and $ueConfig['reg_first_visit_url'] != "") {
                         $return = $ueConfig['reg_first_visit_url'];
                     } else {
                         if ($returnPluginsOverrides) {
                             $return = $returnPluginsOverrides;
                             // by default return to homepage on first login (or on page overridden by plugin).
                         }
                     }
                     $_PLUGINS->trigger('onBeforeFirstLogin', array(&$row, $username, $password, &$return, $secretKey));
                     if ($_PLUGINS->is_errors()) {
                         $resultError = $_PLUGINS->getErrorMSG("<br />");
                     }
                 }
             } else {
                 if ($loginType < 2) {
                     $resultError = CBTxt::T('LOGIN_INCORRECT_USER_NOT_FOUND LOGIN_INCORRECT', 'Incorrect username or password. Please try again.');
                 } else {
                     $resultError = CBTxt::T('UE_INCORRECT_EMAIL_OR_PASSWORD', 'Incorrect email or password. Please try again.');
                 }
             }
         }
         if ($resultError) {
             if ($showSysMessage) {
                 $alertMessages[] = $resultError;
             }
         } elseif (!$stopLogin) {
             if (!$loggedIn) {
                 $_PLUGINS->trigger('onDoLoginNow', array($username, $password, $rememberMe, &$row, &$loggedIn, &$resultError, &$messagesToUser, &$alertMessages, &$return, $secretKey));
             }
             if (!$loggedIn) {
                 $_CB_framework->login($username, $password, $rememberMe, null, $secretKey);
                 $loggedIn = true;
             }
             if ($firstLogin) {
                 $_PLUGINS->trigger('onAfterFirstLogin', array(&$row, $loggedIn));
             }
             $_PLUGINS->trigger('onAfterLogin', array(&$row, $loggedIn));
             if ($loggedIn && $message && $showSysMessage) {
                 $alertMessages[] = CBTxt::T('LOGIN_SUCCESS', 'You have successfully logged in');
             }
             if (!$loggedIn) {
                 $resultError = CBTxt::T('LOGIN_INCORRECT_USER_AUTHENTICATION_FAILED LOGIN_INCORRECT', 'Incorrect username or password. Please try again.');
             }
             // changing com_comprofiler to comprofiler is a quick-fix for SEF ON on return path...
             if ($return && !(strpos($return, 'comprofiler') && (strpos($return, 'login') || strpos($return, 'logout') || strpos($return, 'registers') || strpos(strtolower($return), 'lostpassword')))) {
                 // checks for the presence of a return url
                 // and ensures that this url is not the registration or login pages
                 $returnURL = $return;
             } elseif (!$returnURL) {
                 $returnURL = 'index.php';
             }
         }
     }
     if (!$loggedIn) {
         $_PLUGINS->trigger('onLoginFailed', array(&$resultError, &$returnURL));
     }
     $return = $returnURL;
     return $resultError;
 }
	/**
	 * Registers a new user
	 *
	 * @param UserTable           $user
	 * @param Hybrid_User_Profile $profile
	 * @return bool
	 */
	private function register( $user, $profile )
	{
		global $_CB_framework, $_PLUGINS, $ueConfig;

		if ( ! $profile->identifier ) {
			cbRedirect( $this->_returnUrl, CBTxt::T( 'PROVIDER_PROFILE_MISSING', '[provider] profile could not be found.', array( '[provider]' => $this->_providerName ) ), 'error' );
			return false;
		}

		$mode						=	$this->params->get( $this->_provider . '_mode', 1, GetterInterface::INT );
		$approve					=	$this->params->get( $this->_provider . '_approve', 0, GetterInterface::INT );
		$confirm					=	$this->params->get( $this->_provider . '_confirm', 0, GetterInterface::INT );
		$usergroup					=	$this->params->get( $this->_provider . '_usergroup', null, GetterInterface::STRING );
		$approval					=	( $approve == 2 ? $ueConfig['reg_admin_approval'] : $approve );
		$confirmation				=	( $confirm == 2 ? $ueConfig['reg_confirmation'] : $confirm );
		$usernameFormat				=	$this->params->get( $this->_provider . '_username', null, GetterInterface::STRING );
		$username					=	null;
		$dummyUser					=	new UserTable();

		if ( $usernameFormat ) {
			$extras					=	array( 'provider' => $this->_provider, 'provider_id' => $this->_providerId, 'provider_name' => $this->_providerName );

			foreach ( (array) $profile as $k => $v ) {
				if ( ( ! is_array( $v ) ) && ( ! is_object( $v ) ) ) {
					$k				=	'profile_' . $k;

					$extras[$k]		=	$v;
				}
			}

			$username				=	preg_replace( '/[<>\\\\"%();&\']+/', '', trim( cbReplaceVars( $usernameFormat, $user, true, false, $extras, false ) ) );
		} else {
			if ( isset( $profile->username ) ) {
				$username			=	preg_replace( '/[<>\\\\"%();&\']+/', '', trim( $profile->username ) );
			}

			if ( ( ! $username ) || ( $username && $dummyUser->loadByUsername( $username ) ) ) {
				$username			=	preg_replace( '/[<>\\\\"%();&\']+/', '', trim( $profile->displayName ) );
			}
		}

		if ( ( ! $username ) || ( $username && $dummyUser->loadByUsername( $username ) ) ) {
			$username				=	(string) $profile->identifier;
		}

		if ( $mode == 2 ) {
			$user->set( 'email', $profile->email );
		} else {
			if ( $dummyUser->loadByUsername( $username ) ) {
				cbRedirect( $this->_returnUrl, CBTxt::T( 'UE_USERNAME_NOT_AVAILABLE', "The username '[username]' is already in use.", array( '[username]' =>  htmlspecialchars( $username ) ) ), 'error' );
				return false;
			}

			if ( ! $this->email( $user, $profile ) ) {
				return false;
			}

			if ( $dummyUser->loadByEmail( $user->get( 'email' ) ) ) {
				cbRedirect( $this->_returnUrl, CBTxt::T( 'UE_EMAIL_NOT_AVAILABLE', "The email '[email]' is already in use.", array( '[email]' =>  htmlspecialchars( $user->get( 'email' ) ) ) ), 'error' );
				return false;
			}

			$this->avatar( $user, $profile, $mode );

			if ( ! $usergroup ) {
				$gids				=	array( (int) $_CB_framework->getCfg( 'new_usertype' ) );
			} else {
				$gids				=	cbToArrayOfInt( explode( '|*|', $usergroup ) );
			}

			$user->set( 'gids', $gids );
			$user->set( 'sendEmail', 0 );
			$user->set( 'registerDate', $_CB_framework->getUTCDate() );
			$user->set( 'password', $user->hashAndSaltPassword( $user->getRandomPassword() ) );
			$user->set( 'registeripaddr', cbGetIPlist() );

			if ( $approval == 0 ) {
				$user->set( 'approved', 1 );
			} else {
				$user->set( 'approved', 0 );
			}

			if ( $confirmation == 0 ) {
				$user->set( 'confirmed', 1 );
			} else {
				$user->set( 'confirmed', 0 );
			}

			if ( ( $user->get( 'confirmed' ) == 1 ) && ( $user->get( 'approved' ) == 1 ) ) {
				$user->set( 'block', 0 );
			} else {
				$user->set( 'block', 1 );
			}
		}

		if ( $profile->firstName || $profile->lastName ) {
			$user->set( 'name', trim( $profile->firstName . ' ' . $profile->lastName ) );
		} elseif ( $profile->displayName ) {
			$user->set( 'name', trim( $profile->displayName ) );
		} else {
			$user->set( 'name', $username );
		}

		switch ( $ueConfig['name_style'] ) {
			case 2:
				$lastName			=	strrpos( $user->get( 'name' ), ' ' );

				if ( $lastName !== false ) {
					$user->set( 'firstname', substr( $user->get( 'name' ), 0, $lastName ) );
					$user->set( 'lastname', substr( $user->get( 'name' ), ( $lastName + 1 ) ) );
				} else {
					$user->set( 'firstname', '' );
					$user->set( 'lastname', $user->get( 'name' ) );
				}
				break;
			case 3:
				$middleName			=	strpos( $user->get( 'name' ), ' ' );
				$lastName			=	strrpos( $user->get( 'name' ), ' ' );

				if ( $lastName !== false ) {
					$user->set( 'firstname', substr( $user->get( 'name' ), 0, $middleName ) );
					$user->set( 'lastname', substr( $user->get( 'name' ), ( $lastName + 1 ) ) );

					if ( $middleName !== $lastName ) {
						$user->set( 'middlename', substr( $user->get( 'name' ), ( $middleName + 1 ), ( $lastName - $middleName - 1 ) ) );
					} else {
						$user->set( 'middlename', '' );
					}
				} else {
					$user->set( 'firstname', '' );
					$user->set( 'lastname', $user->get( 'name' ) );
				}
				break;
		}

		$user->set( 'username', $username );
		$user->set( $this->_providerField, $profile->identifier );

		$this->fields( $user, $profile, $mode );

		if ( $mode == 2 ) {
			foreach ( $user as $k => $v ) {
				$_POST[$k]			=	$v;
			}

			$emailPass				=	( isset( $ueConfig['emailpass'] ) ? $ueConfig['emailpass'] : '******' );
			$regErrorMSG			=	null;

			if ( ( ( $_CB_framework->getCfg( 'allowUserRegistration' ) == '0' ) && ( ( ! isset( $ueConfig['reg_admin_allowcbregistration'] ) ) || $ueConfig['reg_admin_allowcbregistration'] != '1' ) ) ) {
				$msg				=	CBTxt::T( 'UE_NOT_AUTHORIZED', 'You are not authorized to view this page!' );
			} else {
				$msg				=	null;
			}

			$_PLUGINS->loadPluginGroup( 'user' );

			$_PLUGINS->trigger( 'onBeforeRegisterFormRequest', array( &$msg, $emailPass, &$regErrorMSG ) );

			if ( $msg ) {
				$_CB_framework->enqueueMessage( $msg, 'error' );
				return false;
			}

			$fieldsQuery			=	null;
			$results				=	$_PLUGINS->trigger( 'onBeforeRegisterForm', array( 'com_comprofiler', $emailPass, &$regErrorMSG, $fieldsQuery ) );

			if ( $_PLUGINS->is_errors() ) {
				$_CB_framework->enqueueMessage( $_PLUGINS->getErrorMSG( '<br />' ), 'error' );
				return false;
			}

			if ( implode( '', $results ) != '' ) {
				$return				=		'<div class="cb_template cb_template_' . selectTemplate( 'dir' ) . '">'
									.			'<div>' . implode( '</div><div>', $results ) . '</div>'
									.		'</div>';

				echo $return;
				return false;
			}

			$_CB_framework->enqueueMessage( CBTxt::T( 'PROVIDER_SIGN_UP_INCOMPLETE', 'Your [provider] sign up is incomplete. Please complete the following.', array( '[provider]' => $this->_providerName ) ) );

			HTML_comprofiler::registerForm( 'com_comprofiler', $emailPass, $user, $_POST, $regErrorMSG );
			return false;
		} else {
			$_PLUGINS->trigger( 'onBeforeUserRegistration', array( &$user, &$user ) );

			if ( $user->store() ) {
				if ( $user->get( 'confirmed' ) == 0 ) {
					$user->store();
				}

				$messagesToUser		=	activateUser( $user, 1, 'UserRegistration' );

				$_PLUGINS->trigger( 'onAfterUserRegistration', array( &$user, &$user, true ) );

				if ( $user->get( 'block' ) == 1 ) {
					$return			=		'<div class="cb_template cb_template_' . selectTemplate( 'dir' ) . '">'
									.			'<div>' . implode( '</div><div>', $messagesToUser ) . '</div>'
									.		'</div>';

					echo $return;
				} else {
					return true;
				}
			}

			cbRedirect( $this->_returnUrl, CBTxt::T( 'SIGN_UP_WITH_PROVIDER_FAILED', 'Sign up with [provider] failed. Error: [error]', array( '[provider]' => $this->_providerName, '[error]' => $user->getError() ) ), 'error' );
			return false;
		}
	}
Esempio n. 4
0
function sendNewPass($option)
{
    global $_CB_framework, $ueConfig, $_PLUGINS, $_POST;
    $loginType = isset($ueConfig['login_type']) ? (int) $ueConfig['login_type'] : 0;
    if ($loginType == 4) {
        cbRedirect($_CB_framework->viewUrl('done', false), CBTxt::Th('UE_NOT_AUTHORIZED', 'You are not authorized to view this page!'), 'error');
        return;
    }
    // simple spoof check security
    checkCBPostIsHTTPS();
    cbSpoofCheck('lostPassForm');
    cbRegAntiSpamCheck();
    $liveSite = $_CB_framework->getCfg('live_site');
    $usernameExists = $loginType != 2;
    // ensure no malicous sql gets past
    $checkusername = trim(cbGetParam($_POST, 'checkusername', ''));
    $confirmEmail = trim(cbGetParam($_POST, 'checkemail', ''));
    $_PLUGINS->loadPluginGroup('user');
    $_PLUGINS->trigger('onStartNewPassword', array(&$checkusername, &$confirmEmail));
    if ($_PLUGINS->is_errors()) {
        cbRedirect($_CB_framework->viewUrl('lostpassword', false), $_PLUGINS->getErrorMSG(), 'error');
        return;
    }
    $checkusername = stripslashes($checkusername);
    $confirmEmail = stripslashes($confirmEmail);
    $res = false;
    $error = null;
    if ($usernameExists && $confirmEmail != '' && !$checkusername) {
        $user = new UserTable();
        if (!$user->loadByEmail($confirmEmail)) {
            cbRedirect($_CB_framework->viewUrl('lostpassword', false), CBTxt::Th('UE_EMAIL_DOES_NOT_EXISTS_ON_SITE', "The email '[email]' does not exist on this site.", array('[email]' => htmlspecialchars($confirmEmail))), 'error');
        }
        $message = str_replace('\\n', "\n", sprintf(CBTxt::T('UE_USERNAMEREMINDER_MSG', 'Hello,\\nA username reminder has been requested for your %s account.\\n\\nYour username is: %s\\n\\nTo log in to your account, click on the link below:\\n%s\\n\\nThank you.\\n'), $_CB_framework->getCfg('sitename'), $user->username, $liveSite));
        /*
        'Hello,\n'
        .'A username reminder has been requested for your %s account.\n\n'
        .'Your username is: %s\n\n'
        .'To log in to your account, click on the link below:\n'
        .'%s\n\n'
        .'Thank you.\n'
        */
        $subject = sprintf(CBTxt::T('UE_USERNAMEREMINDER_SUB', 'Username reminder for %s'), $user->username);
        $_PLUGINS->trigger('onBeforeUsernameReminder', array($user, &$subject, &$message));
        if ($_PLUGINS->is_errors()) {
            cbRedirect($_CB_framework->viewUrl('lostpassword', false), $_PLUGINS->getErrorMSG(), 'error');
            return;
        }
        $cbNotification = new cbNotification();
        $res = $cbNotification->sendFromSystem($user->id, $subject, $message);
        $error = $cbNotification->errorMSG;
        $_PLUGINS->trigger('onAfterUsernameReminder', array($user, &$res));
        if ($res) {
            cbRedirect($_CB_framework->viewUrl('done', false), sprintf(CBTxt::Th('UE_USERNAME_REMINDER_SENT', 'Username reminder sent to your email address %s. Please check your email (and if needed your spambox too)!'), htmlspecialchars($confirmEmail)));
        } else {
            cbRedirect($_CB_framework->viewUrl('done', false), $error ? CBTxt::Th('SENDING_EMAIL_FAILED_ERROR_ERROR', 'Sending Email Failed! Error: [error]', array('[error]' => $error)) : CBTxt::Th('UE_EMAIL_SENDING_ERROR', 'Error sending email'), 'error');
        }
    } elseif ($confirmEmail != '') {
        $user = new UserTable();
        if ($usernameExists) {
            $foundUser = $user->loadByUsername($checkusername);
            if ($foundUser && cbutf8_strtolower($user->email) != cbutf8_strtolower($confirmEmail)) {
                $foundUser = false;
            }
        } else {
            $foundUser = $user->loadByEmail($confirmEmail);
        }
        if (!$foundUser) {
            cbRedirect($_CB_framework->viewUrl('lostpassword', false), CBTxt::Th('ERROR_PASS', 'Sorry, no corresponding user was found'), 'error');
        }
        $resetTime = (int) $_CB_framework->getCfg('reset_time');
        $resetCount = (int) $_CB_framework->getCfg('reset_count');
        $hoursSinceLastReset = ($_CB_framework->getUTCNow() - (int) $_CB_framework->getUTCTimestamp($user->lastResetTime)) / 3600;
        if ($hoursSinceLastReset > $resetTime) {
            $user->lastResetTime = $_CB_framework->getUTCDate();
            $user->resetCount = 1;
        } else {
            $user->resetCount = $user->resetCount + 1;
        }
        if ($resetCount && $user->resetCount > $resetCount) {
            cbRedirect($_CB_framework->viewUrl('lostpassword', false), CBTxt::Th('EXCEEDED_MAXIMUM_PASSWORD_RESETS', 'You have exceeded the maximum number of password resets allowed. Please try again in %%COUNT%% hours.|You have exceeded the maximum number of password resets allowed. Please try again in 1 hour.', array('%%COUNT%%' => $resetTime)), 'error');
        }
        $newpass = $user->getRandomPassword();
        $message = str_replace('\\n', "\n", sprintf(CBTxt::T('UE_NEWPASS_MSG', 'The user account %s has this email associated with it.\\nA web user from %s has just requested that a new password be sent.\\n\\nYour New Password is: %s\\n\\nIf you didn\'t ask for this, don\'t worry. You are seeing this message, not them. If this was an error just log in with your new password and then change your password to what you would like it to be.'), $user->username, $liveSite, $newpass));
        /*
        'The user account %s has this email associated with it.\n'
        .'A web user from %s has just requested that a new password be sent.\n\n'
        .'Your New Password is: %s\n\n'
        .'If you didn\'t ask for this, don\'t worry. You are seeing this message, not them. If this was an error just log in with your new password and then change your password to what you would like it to be.'
        */
        $subject = sprintf(CBTxt::T('UE_NEWPASS_SUB', 'New password for: %s'), $user->username);
        $_PLUGINS->trigger('onBeforeNewPassword', array($user, &$newpass, &$subject, &$message));
        if ($_PLUGINS->is_errors()) {
            cbRedirect($_CB_framework->viewUrl('lostpassword', false), $_PLUGINS->getErrorMSG(), 'error');
        }
        $_PLUGINS->trigger('onNewPassword', array($user, $newpass));
        $storeValues = array('password' => $newpass, 'lastResetTime' => $user->lastResetTime, 'resetCount' => $user->resetCount);
        if (!$user->storeDatabaseValues($storeValues)) {
            cbRedirect($_CB_framework->viewUrl('lostpassword', false), $user->getError(), 'error');
        } else {
            $cbNotification = new cbNotification();
            $res = $cbNotification->sendFromSystem($user->id, $subject, $message);
            $error = $cbNotification->errorMSG;
        }
        $_PLUGINS->trigger('onAfterPasswordReminder', array($user, $newpass, &$res));
        if ($res) {
            cbRedirect($_CB_framework->viewUrl('done', false), sprintf(CBTxt::Th('UE_NEWPASS_SENT', 'New User Password created and sent to your email address %s. Please check your email (and if needed your spambox too)!'), htmlspecialchars($confirmEmail)));
        } else {
            cbRedirect($_CB_framework->viewUrl('done', false), $error ? CBTxt::Th('PASSWORD_RESET_FAILED_ERROR_ERROR', 'Password Reset Failed! Error: [error]', array('[error]' => $error)) : CBTxt::Th('UE_NEWPASS_FAILED', 'Password Reset Failed!'), 'error');
        }
    } else {
        cbRedirect($_CB_framework->viewUrl('done', false), CBTxt::Th('UE_NEWPASS_FAILED', 'Password Reset Failed!'), 'error');
    }
}