#!/usr/bin/perl -Tw -I. -I/usr/local/positive/Perl 

#
# This software is copyright (c) 2001-2002 Positive Networks, Inc.  All rights reserved.
# 
# This software is the proprietary and confidential property of Positive Networks, Inc.
# Possession, transmission, publication, or use of this software is prohibited except by prior written consent.
#  

# reg.pl - handles the user registration proces

#
# VPN-4153
#    04.03.2012 - LM
#
# NOTE: As a general practice, WebTop passwords will be executed twice - once on the POP and sent to the 
#       PMs message queue for execution locally. 
#
#       All other DML will be executed on the PM only.
#
        
        
use strict;
use Pos::Webtop::Web::ModuleLoader;
use Pos::Webtop::Web::OEMLoader;
use Pos::Webtop::Toolbox;
use Digest::MD5;
use Pos::MessageQueue::Put::MQI;

my $mqi = MQI->new();
my $mqiHostName  = $mqi->getHostName();
my $mqiQueueName = $mqi->getQueueNameByType( type=> "queueRunSql" );
my $mqiSQL;

my $tb = Pos::Webtop::Toolbox->new();
my $client = $tb->getClient();
my $cgi = $tb->getCgi();
my $oem = $tb->getOem;
my $authdb = $tb->getPolicyDb();

my $nostep = $cgi->param('nostep');
my $mode = $cgi->param('mode');
my $auth = $cgi->param('auth');
my $username = $cgi->param('username');
my $endPassword = $cgi->param('password');
my $oemId = $cgi->param('oemId');
my $isMobile = $client->isMobileWebtop();

$oemId = "" if (not defined($oemId));
$nostep = 0 if (not defined($nostep));
$mode   = "" if (not defined($mode));
$auth	  = "" if (not defined($auth));

my $sh = $client->getSessionHash();
my $si = $client->getSessionId();

$client->checkSession(ignoreAuxAuth=> 1);
my $userId = $client->getUserId();

$client->repersistValues(values=>['startUrl']);

my @userAuthTypes = $authdb->query(sql =>  "
	select a.auth_type_id, b.auth_type_name
	from user_auth_types a
	inner join auth_types b on a.auth_type_id = b.auth_type_id
	where a.user_id = $userId");
my ($authTypeId, $authTypeName) = @{ $userAuthTypes[0] };

my $userInfoPreferences = $cgi->param('userInfoPreferences');
my $passwdPreferences = $cgi->param('passwdPreferences');

$userInfoPreferences = 0 unless defined($userInfoPreferences);
$passwdPreferences = 0 unless defined($passwdPreferences);
	
my $cancelAction;

if ($userInfoPreferences or $passwdPreferences)
{
	$cancelAction = 'document.refreshForm.submit();';
}
else
{
	$cancelAction = "document.location.href=\"" . $oem->getSetting(setting=>'webtopUrl') . "\";";
}

if ($cgi->param('primaryEmail')) 
{
	my $db = $tb->getPolicyDb();
	my $workEmail = $cgi->param('workEmail');
	my $homeEmail = $cgi->param('homeEmail');
	my $primaryEmail = $cgi->param('primaryEmail');
	my $workPhone = $cgi->param('workPhone');
	my $homePhone = $cgi->param('homePhone');
	my $firstName = $cgi->param('fname');
	my $middleName = $cgi->param('mname');
	my $lastName = $cgi->param('lname');
	my $recieveServiceHome = $cgi->param('recieveServiceHome');
	my $recieveServiceWork = $cgi->param('recieveServiceWork');
	my $errorValue;
	my $errorTypeValue;
        my $sql;

	# First set the primary e-mail

	if ($primaryEmail eq 'home' and $homeEmail)
	{
		$primaryEmail = 2;
	}
	else
	{
		$primaryEmail = 1;
	}

	# Now start going down the list of settable things

	if (!$firstName)
	{
		$errorTypeValue .= '1';

		if ($errorValue)
		{
			$errorValue = 'Multiple invalid fields';
		}
		else
		{
			$errorValue = 'First name is required';
		}
	}

	if(!$lastName)
	{
		$errorTypeValue .= '2';

		if ($errorValue)
		{
			$errorValue = 'Multiple invalid fields';
		}
		else
		{
			$errorValue = 'Last name is required';
		}
	}

	if ($middleName and $middleName !~ /[A-Za-z]/)
	{
		$errorTypeValue .='9';

		if ($errorValue)
		{
			$errorValue = 'Multiple invalid fields';
		}
		else
		{
			$errorValue = 'Middle Initial must only be a Letter [A-Z]';
		}
	}

	if (not length($workEmail))
	{
		$errorTypeValue .= '3';

		if ($errorValue)
		{
			$errorValue = 'Multiple invalid fields';
		}
		else
		{
			$errorValue = 'Work email address is required';
		}
		
	}
	elsif(length($workEmail) and $workEmail !~ /.+\@.+\..+/) 
	{
		$errorTypeValue .= '3';

		if ($errorValue)
		{
			$errorValue = 'Multiple invalid fields';
		}
		else
		{
			$errorValue = 'Please enter a valid Work email address';
		}
	}

        #
        # 201111207 - LM: Modified per Gemini ticket VPN-2672 
        #
	#if ($cgi->param('primaryEmail') eq 'home' and not $homeEmail) 
	if (not length($homeEmail))
	{
		$errorTypeValue .= '4';

		if ($errorValue)
		{
			$errorValue = 'Multiple Invalid Fields';
		}
		else
		{
                        #
                        # 201111207 - LM: Modified per Gemini ticket VPN-2672 
                        #
			#$errorValue = 'Alternate email selected as primary, it is now a required field.';
			$errorValue = 'Alternate email is required.';
		}
		
	}
        #
        # 201111207 - LM: Modified per Gemini ticket VPN-2672 
        #
	elsif ($homeEmail and $homeEmail !~ /.+\@.+\..+/)
	{
		$errorTypeValue .= '4';

		if ($errorValue)
		{
			$errorValue = 'Multiple Invalid Fields';
		}
		else
		{
			$errorValue = 'Please enter a valid Alternate Email address';
		}
	}
	elsif ($homeEmail eq $workEmail)
	{
		$errorTypeValue .= '4';

		if ($errorValue)
		{
			$errorValue = 'Multiple Invalid Fields';
		}
		else
		{
			$errorValue = 'Please enter an Alternate Email which differs from Work';
		}
	}
        # end 

	if(not ( defined $workPhone and length $workPhone ) )
	{
		$errorTypeValue .= '5';

		if($errorValue)
		{
			$errorValue = 'Multiple Invalid Fields';
		}
		else
		{
			$errorValue = 'Work Phone is required';
		}

		$workPhone = "";
	}
	else
	{
		$workPhone = substr($workPhone,0,30);
	}

	if( defined $homePhone and length $homePhone )
	{
		$homePhone = substr($homePhone,0,30);
	}
	else
	{
		$homePhone = ""
	}

	if ($errorTypeValue)
	{
		verifyUserInfo(authType=> $authTypeId, errorType=>$errorTypeValue, errorValue=>$errorValue, tb=>$tb, userId=> $userId, auth=>$auth, username=>$username, userInfoPrefs=> $userInfoPreferences);
		exit;
	}
	else
	{
		$sql = "UPDATE users SET primary_user_email_id = '" . $db->escape(dirty=>$primaryEmail) . "', first_name='" . $db->escape(dirty=>$firstName) . "', last_name='" . $db->escape(dirty=>$lastName) . "', middle_name='" . $db->escape(dirty=>$middleName) . "', modified_date = " . $db->getCurrentDateString() . " WHERE user_id = '$userId';";

		#$db->do(sql=>$sql);
                #
                # VPN-4153
                #    04.03.2012 - LM
                #

                $mqiSQL = $sql;
 
                #
                # VPN-4153
                #    04.03.2012 - LM
                #
		#$db->do(sql=>"	
		#					DELETE FROM user_email_addresses 
		#					WHERE user_id = '$userId'
		#					AND user_email_id in ('1','2')
		#				");
		#$db->do(sql=>$sql);
                $sql = "DELETE FROM user_email_addresses WHERE user_id = '$userId' AND user_email_id in ('1','2');";
                $mqiSQL .= $sql;

		if ($workEmail)
		{
                        #
                        # VPN-4153
                        #    04.03.2012 - LM
                        # 
			#$db->do(sql=>"	
			#					INSERT INTO user_email_addresses(user_id, user_email_id, email_address, email_type_id)
			#					VALUES('$userId', '1', '" . $db->escape(dirty=>$workEmail) . "', '1')
			#				");
                        #$db->do(sql=>$sql);

			$sql = "INSERT INTO user_email_addresses(user_id, user_email_id, email_address, email_type_id) VALUES('$userId', '1', '" . $db->escape(dirty=>$workEmail) . "', '1');";

                        $mqiSQL .= $sql;
		}
		if ($homeEmail)
		{
                        #
                        # VPN-4153
                        #    04.03.2012 - LM
                        #
			#$db->do(sql=>"
			#					INSERT INTO user_email_addresses(user_id, user_email_id, email_address, email_type_id)
			#					VALUES( '$userId', '2', '" . $db->escape(dirty=>$homeEmail) . "', '2')
			#				");
                        #$db->do(sql=>$sql);

			$sql = "INSERT INTO user_email_addresses(user_id, user_email_id, email_address, email_type_id) VALUES( '$userId', '2', '" . $db->escape(dirty=>$homeEmail) . "', '2');";
                        $mqiSQL .= $sql;
		}

                #
                # VPN-4153
                #    04.03.2012 - LM
                #

		#$db->do(sql=>"
		#					DELETE FROM user_phone_numbers 
		#					WHERE user_id = '$userId'
		#					AND user_phone_number_id in ('1','2')
		#				");
                #$db->do(sql=>$sql);

		$sql = "DELETE FROM user_phone_numbers WHERE user_id = '$userId' AND user_phone_number_id in ('1','2');";
                $mqiSQL .= $sql;

		if ($workPhone)
		{
                        #
                        # VPN-4153
                        #    04.03.2012 - LM
                        #
			#$db->do(sql=>"
			#					INSERT INTO user_phone_numbers(phone_number, user_id, user_phone_number_id, phone_number_type_id)
			#					VALUES( '" . $db->escape(dirty=>$workPhone) . "', '$userId', '1', '1')
			#				");
                        #$db->do(sql=>$sql);

			$sql = "INSERT INTO user_phone_numbers(phone_number, user_id, user_phone_number_id, phone_number_type_id) VALUES( '" . $db->escape(dirty=>$workPhone) . "', '$userId', '1', '1');";

                        $mqiSQL .= $sql;
		}
		if ($homePhone)
		{
                        #
                        # VPN-4153
                        #    04.03.2012 - LM
                        #
			#$db->do(sql=>"
			#					INSERT into user_phone_numbers(phone_number, user_id, user_phone_number_id, phone_number_type_id)
			#					VALUES( '" . $db->escape(dirty=>$homePhone) . "', '$userId', '2', '2')
			#				");
                        #$db->do( sql=> $sql );

		        $sql = "INSERT into user_phone_numbers(phone_number, user_id, user_phone_number_id, phone_number_type_id) VALUES( '" . $db->escape(dirty=>$homePhone) . "', '$userId', '2', '2');";
                        $mqiSQL .= $sql;
		}

                $mqi->insertMessageQueue( hostname=>$mqiHostName, queuename=>$mqiQueueName, value=>$mqiSQL );
		$db->commit();
	}

	if ( $userInfoPreferences )
	{
		my $refreshModule = $client->getPersistedValue( name => "refreshModule" );
		
		print "content-type: text/html\n\n

				<html>
				<body>
					<form method='post' action='main.pl?pvwsh=$sh&pvwsi=$si' name='refreshform'>
						<input type='hidden' name='module' value=\"" . HTML::Entities::encode($refreshModule) . "\"/>

				";

		print $client->getFormInputs();

		print "
					</form>

				<script language='javascript1.2' type='text/javascript'>

				document.refreshform.submit();

				</script>

				</body>
				</html>
		";
		exit;
																																																					
	}	
	else
	{
		if( $client->canUserChangePassword(db=>$db, userId=> $userId) && ($client->isPasswordExpired() || $client->requiredToChangePassword()) )
		{
			setUserPassword(tb=>$tb, mode=> $mode, username=> $username, userId=> $userId, auth=> $auth, passwdPrefs=> $passwdPreferences);
		}
		else
		{
			setUserVerify(tb=>$tb, mode=> $mode, authType=> $authTypeId, username=> $username, auth => $auth, password=> $endPassword );
		}
	}
}
elsif (defined($cgi->param('initialPassword'))) 
{
	my $username = $cgi->param('username');
	my $initialPassword = $cgi->param('initialPassword');
	my $confirmPassword = $cgi->param('confirmPassword');
	my $oldPassword = $cgi->param('oldPassword');
	my $validity = validatePassword(userId=> $userId, auth => $auth, password=>$initialPassword, tb=>$tb);
	my $sql;
	
	if ($initialPassword ne $confirmPassword)
	{
		setUserPassword(tb=>$tb, , errorType=>'2', error=>"Passwords did not match.", validity=>$validity, mode=> $mode, username=> $username, userId=> $userId, auth=> $auth, passwdPrefs=> $passwdPreferences );
	}
	elsif($validity)
	{
		setUserPassword(tb=>$tb, , errorType=>'3', error=>"Password does not meet Complexity Standards", validity=>$validity, mode=> $mode, username=> $username, userId=> $userId, auth=> $auth, passwdPrefs=> $passwdPreferences);
	}
	else
	{
		my $db = $tb->getPolicyDb();

		$authTypeName = "Standard" unless (defined($authTypeName));

		if ($authTypeName eq 'NTLM' || $authTypeName eq 'PhoneFactor - NTLM')
		{
			my $ntlmExec = "/usr/local/positive/Binary/ChangeNtlmPassword";
			my $cmd;
			my $rv;
			
			my $fromPw = $oldPassword;
			my $toPw = $confirmPassword;
			$fromPw =~ s/(\W)/\\$1/g;
			$toPw =~ s/(\W)/\\$1/g;

			my $oldPath = $ENV{'PATH'};
			my $oldLd   = $ENV{'LD_LIBRARY_PATH'};

			$ENV{'PATH'} = '/usr/local/bin:/usr/bin:/bin';
			$ENV{'LD_LIBRARY_PATH'} = "/usr/local/positive/Library";

			"$ntlmExec $userId $fromPw $toPw|" =~ /^(.*)$/;

			#warn "running: $1\n";

			open(RAD, $1);
			
			# Last line of output is the result.
			#
			while (<RAD>)
			{
				$rv = $_;
			}

			close(RAD);
			chomp($rv);
			$rv =~ s/(\d+)/$1/g;

			$ENV{'PATH'} = $oldPath;
			$ENV{'LD_LIBRARY_PATH'} = $oldLd;

			# If the return value was not zero, then something failed...
			if ($rv != 0)
			{
				setUserPassword(tb=>$tb,
					errorType=>'10', 
					error=>"Your password could not be changed ($rv)", 
					validity=>$validity, 
					mode => $mode, 
					username => $username, 
					userId => $userId, 
					passwdPrefs=> $passwdPreferences,
					auth => $auth);
				return;
			}
		
                        #
                        # VPN-4153
                        #    04.03.2012 - LM
                        #	
			#$db->do( sql => " 
			#				update 
			#					users
			#				set 
			#					last_password_reset = " . $db->getCurrentTimeStampString() . ",
			#					ext_password_expired = '0'
			#				where 
			#					user_id = $userId
			#			");

			$sql = "update users set last_password_reset = " . $db->getCurrentTimeStampString() . ", ext_password_expired = '0' where user_id = $userId;";
                        $db->do( sql=> $sql );
			$db->commit();

                        $mqi->insertMessageQueue( hostname=>$mqiHostName, queuename=>$mqiQueueName, value=>$sql );
		}
		else
		{
			# do the password input
			my $md5pw = Digest::MD5::md5_hex($confirmPassword);
                        #
                        # VPN-4153
                        #    04.03.2012 - LM
                        #
			#$db->do( sql => " 
			#				update 
			#					users
			#				set 
			#					password = '$md5pw',
			#					last_password_reset = " . $db->getCurrentTimeStampString() . ",
			#					ext_password_expired = '0'
			#				where 
			#					user_id = $userId
			#			");
                      
			$sql = "update users set password = '$md5pw', last_password_reset = " . $db->getCurrentTimeStampString() . ", ext_password_expired = '0' where user_id = $userId";
                        $db->do( sql=> $sql );
			$db->commit();

                        $mqi->insertMessageQueue( hostname=>$mqiHostName, queuename=>$mqiQueueName, value=>$sql );
		}

		# If we were called from the login page, refresh back to the
		# login page using the user's new credentials, or refresh
		# to the correct download page
		
		if ($auth eq 'expired' || ($passwdPreferences && $mode eq 'netcon'))
		{
			if ($passwdPreferences && $mode eq 'netcon')
			{	
				#$db->do(sql=> " update users set register_complete = 1 where user_id = $userId ");

                                #
                                # VPN-4153
                                #    04.03.2012 - LM
                                #
				$sql = "update users set register_complete = 1 where user_id = $userId ";
                                $mqi->insertMessageQueue( hostname=>$mqiHostName, queuename=>$mqiQueueName, value=>$sql );
			}

			print "Content-type: text/html\n\n

					<html>
					<body>
						<form method='POST' action='login.pl' name='refreshform'>
							<input type='hidden' name='un' value=\"" . HTML::Entities::encode($username) . "\"/>
							<input type='hidden' name='pw' value=\"" . HTML::Entities::encode($confirmPassword) . "\"/>
							<input type='hidden' name='pwreset' value='1'/>
							" . (length($mode) ? "<input type='hidden' name='mode' value=\"" . HTML::Entities::encode($mode) . "\"/>" : "") . "
							" . (length($oemId) ? "<input type='hidden' name='oemId' value=\"" . HTML::Entities::encode($oemId) . "\"/>" : "") . "
						</form>
				";
			
			#print $client->getFormInputs();
					
			print "
					<script type='text/javascript'>


						document.refreshform.submit();

					</script>

					</body>
					</html>
			";
			exit;
		}
		
		if ( $passwdPreferences )
		{
			my $refreshModule = $client->getPersistedValue( name => "refreshModule" );

			print "Content-type: text/html\n\n

					<html>
					<body>
						<form method='POST' action='main.pl?" . $client->getSessionParams() . "' name='refreshform'>
							<input type='hidden' name='module' value=\"" . HTML::Entities::encode($refreshModule) . "\"/>

					";

			print $client->getFormInputs();

			print "
						</form>

					<script type='text/javascript'>

						document.refreshform.submit();

					</script>

					</body>
					</html>
			";
			exit;																																																	
		}
		else
		{
			setUserVerify(authType=> $authTypeId, tb=>$tb, username=> $username, auth=> $auth, password=>$confirmPassword, mode=> $mode);
		}
	}
}
elsif( $cgi->param('secretQuestion') )
{
	my $username = $cgi->param('username');
	my $mode = $cgi->param('mode');
	my $question = $cgi->param('question');
	my $initialAnswer = $cgi->param('initialAnswer');
	my $confirmAnswer = $cgi->param('confirmAnswer');
    my $userPrefsUpdate = $cgi->param('userPrefsUpdate');
    my $questionUserPrefsUpdate = $cgi->param('questionUserPrefsUpdate');
        my $sql;

    if (defined($userPrefsUpdate))
    {
        setUserVerify(authType=> $authTypeId, tb=>$tb, username=> $username, auth=> $auth, password=>$endPassword, mode=> $mode);
        exit;
    }
	elsif (not defined($question) || !length($question))
	{
		setUserVerify(authType=> $authTypeId, tb=>$tb, , errorType=>'1', error=>"Please supply a Secret Question.", username=> $username, auth=> $auth, mode=> $mode, password=>$endPassword );
		exit;
	}
	elsif (lc($initialAnswer) ne lc($confirmAnswer))
	{
		setUserVerify(authType=> $authTypeId, tb=>$tb, , errorType=>'1', error=>"Answers to Secret Question did not match.", username=> $username, auth=> $auth, mode=> $mode, password=>$endPassword);
		exit;
	}
	elsif(!$initialAnswer or !$confirmAnswer)
	{
		setUserVerify(authType=> $authTypeId, tb=>$tb, , errorType=>'1', error=>"Please supply an intial and confirm answer to your Secret Question.", username=> $username, auth=> $auth, mode=> $mode, password=>$endPassword);
		exit;
	}
	
	my $db = $tb->getPolicyDb();

        #
        # VPN-4153
        #    04.03.2012 - LM
        #
	$sql = "UPDATE users SET verify_user_question = '" . $db->escape(dirty=>$question) ."', verify_user_answer = '" . $db->escape(dirty=>$initialAnswer) . "', register_complete = 1 WHERE user_id = '$userId';";

	#$db->do(sql=>$sql);
	#$db->commit();

        $mqi->insertMessageQueue( hostname=>$mqiHostName, queuename=>$mqiQueueName, value=>$sql );

	#$db->do(sql=> " update user_enrollment_metrics set registration_date=" . $db->getCurrentDateString() . " where user_id = '$userId'" );
	#$db->do(sql=>$sql);
	#$db->commit();

    if(not defined($questionUserPrefsUpdate))
    {
        $sql =  "update user_enrollment_metrics set registration_date=" . $db->getCurrentDateString() . " where user_id = '$userId';" ;
        $mqi->insertMessageQueue( hostname=>$mqiHostName, queuename=>$mqiQueueName, value=>$sql );
    }

	my $refreshUrl = $client->getPersistedValue( name => "startUrl" );

	$refreshUrl = URI::Escape::uri_unescape($refreshUrl, "\\W");

	if($auth eq 'register')
	{
		$refreshUrl = 'login.pl?logout=1';
	}
	elsif (defined($mode) && length($mode))
	{
		$refreshUrl = "vpndownload.pl";
	}
    elsif (defined($questionUserPrefsUpdate))
    {
        $refreshUrl = "main.pl?module=UserPrefs";
    }
	else
	{
		$refreshUrl = "main.pl?displayFrameset=1";
	}

	my ($url, $p) = split /\?/, $refreshUrl;
	my @parms     = split /&/, $p;
	
	print "Content-type: text/html\n\n
		<html><body>
			<form method='POST' action=\"" . (defined($url) ? "$url" : "login.pl") . "\" name='refreshForm'>
				" . (defined($oemId) ? "<input type='hidden' name='oemId' value=\"" . HTML::Entities::encode($oemId) . "\">" : "<input type='hidden' name='oemId' value=\"1\">" ) . "
				" . (defined($mode) ? "<input type='hidden' name='mode' value=\"" . HTML::Entities::encode($mode) . "\">" : "" ) . "
				" . (defined($username) ? "<input type='hidden' name='un' value=\"" . HTML::Entities::encode($username) . "\">" : "" ) . "
				" . (defined($endPassword) ? "<input type='hidden' name='pw' value=\"" . HTML::Entities::encode($endPassword) . "\">" : "" ) . "
			";
			
			foreach (@parms)
			{
				my ($name, $val) = split /=/, $_;
				
				print
					"<input type='hidden' name=\"" . HTML::Entities::encode($name) . "\" value=\"" . HTML::Entities::encode($val) . "\">\n";
			}

			print 
				"
			</form>

			<script language='javascript'>
				document.refreshForm.submit();
			</script>
		</head></html>
	";
	exit;
}
else
{
	if ( $cgi->param('verifyUserInfoBack') )
	{
		verifyUserInfo(authType=> $authTypeId, tb=>$tb , userId=> $userId , auth=> $auth, username=>$username, userInfoPrefs=> $userInfoPreferences, mode=> $mode);
	}
	elsif ( $cgi->param('initialPasswordBack') || $passwdPreferences || $auth eq 'expired' )
	{
		setUserPassword(tb=>$tb, authType=> $authTypeId, username=> $username, userId=> $userId, auth=> $auth, passwdPrefs=> $passwdPreferences, mode=> $mode);
	}
	else
	{
		verifyUserInfo(authType=> $authTypeId, tb=>$tb, userId=> $userId, auth=> $auth, username=>$username, userInfoPrefs=> $userInfoPreferences, mode=> $mode);
	}
}

sub getUserInfo 
{
	my ($tb, $userId) = @{{@_}}{qw/tb userId/};
	my $db = $tb->getPolicyDb();
	my $client = $tb->getClient();
	$userId = $client->getUserId() unless defined($userId);
	
	my $sql = "	SELECT a.last_name, a.first_name, a.middle_name, a.primary_user_email_id,
						(
							SELECT u.email_address
							FROM user_email_addresses u
							WHERE email_type_id ='1'
							AND u.user_id = '$userId'
						) as Primary_Email,
						(
							SELECT u.email_address
							FROM user_email_addresses u
							WHERE email_type_id ='2'
							AND u.user_id = '$userId'
						) as Secondary_Email,
						(
							SELECT p.phone_number
							FROM user_phone_numbers p
							WHERE p.phone_number_type_id = '1'
							AND p.user_id = '$userId'
						) as Primary_Phone,
						(
							SELECT p.phone_number from user_phone_numbers p
  							WHERE p.phone_number_type_id = '2'
							AND p.user_id = '$userId'
						) as Secondary_Phone
					FROM users a
					WHERE user_id = '$userId'
				";

	my @userInfo = $db->query(sql=>$sql);
	return @userInfo;
}

sub verifyUserInfo 
{
	my ($tb, $errorType, $errorValue, $authType, $userId, $auth, $username, $userInfoPreferences, $mode) = @{{@_}}{qw/tb errorType errorValue authType userId auth username userInfoPrefs mode/};

	my $db = $tb->getPolicyDb();
	my $client = $tb->getClient();
	my $cgi = $tb->getCgi();
	my @customerInfo = getUserInfo(tb => $tb, userId=> $userId);
	my ($lname, $fname, $mname, $primaryEmail, $workEmail, $homeEmail, $workPhone, $homePhone) = @{$customerInfo[0]};
	
	$workEmail = $cgi->param('workEmail') unless not defined($cgi->param('workEmail'));
	$homeEmail = $cgi->param('homeEmail') unless not defined($cgi->param('homeEmail'));
	$primaryEmail = $cgi->param('primaryEmail') unless not defined($cgi->param('primaryEmail'));
	$workPhone = $cgi->param('workPhone') unless not defined($cgi->param('workPhone'));
	$homePhone = $cgi->param('homePhone') unless not defined($cgi->param('homePhone'));;
	$fname = $cgi->param('fname') unless not defined($cgi->param('fname'));
	$mname = $cgi->param('mname') unless not defined($cgi->param('mname'));
	$lname = $cgi->param('lname') unless not defined($cgi->param('lname'));
	
	my $minit = substr($mname, 0, 1);
	
	my $error = undef;

	if (defined($errorType))
	{
		$error = $errorValue;
	}


	$oem->printHtmlHeader(title => "Registration");
	my $companyLogoSettings = $tb->getCompanyLogoSettings();
	$oem->printBodyHeader(companyText=> $companyLogoSettings->{'companyText'}, companyImage=> $companyLogoSettings->{'companyImage'}, removeSupportImages => $companyLogoSettings->{'removeSupportImages'}, isMobile => $isMobile);

	my $numSteps;
	$numSteps = 2 if $authType == 3;
	$numSteps = 3 if $authType == 2;

	print "
		<form method='POST' action='main.pl?" . $client->getSessionParams() . "' name='refreshForm'>
			
			";

			my $refreshModule = $client->getPersistedValue( name => "refreshModule" );
	print "
			<input type='hidden' name='module' value=\"" . HTML::Entities::encode($refreshModule) . "\"/>

			";

				print $client->getFormInputs();

	print "
		</form>
			<div style='text-align: left' class='BOXTD1'><span style='font-size: 18px;'><b>Please verify your user information" . 
			((!$nostep) ? ": <font size='2'>(Step 1 of $numSteps)</font> " : "") . "</b></span></div>
			<br><br>
			<form method='POST' action='reg.pl'>
				" . ((defined($auth))?"<input type='hidden' name='auth' value=\"" . HTML::Entities::encode($auth) . "\"/>":"") . "
				" . ((defined($userInfoPreferences))?"<input type='hidden' name='userInfoPreferences' value=\"" . HTML::Entities::encode($userInfoPreferences) . "\">" : "" ) . "
				" . ((defined($nostep))?"<input type='hidden' name='nostep' value=\"" . HTML::Entities::encode($nostep) . "\"/>":"") . "
				" . ((defined($cgi->param('mode')))?"<input type='hidden' name='mode' value=\"" . HTML::Entities::encode($cgi->param('mode')) . "\"/>":"") . "
				" . ((defined($cgi->param('password')))?"<input type='hidden' name='password' value=\"" . HTML::Entities::encode($cgi->param('password')) . "\"/>":"") . "
				" . ((defined($username))?"<input type='hidden' name='username' value=\"" . HTML::Entities::encode($username) . "\"/>":"") . "
				" . ((defined($cgi->param('oemId')))?"<input type='hidden' name='oemId' value=\"" . HTML::Entities::encode($cgi->param('oemId')) . "\"/>":"") . "
				<center>
				<table align='center' border='0' cellspacing='0' cellpadding='2' width='500'>
					<tr>
						<td align='center' class='BOXTD1'>
							<i class='DEF'>
							Please note that all fields marked with an asterisk (<font color='red'>*</font>) are required fields
							</i>
						</td>
					</tr>	
				</table>
				<table border='0' cellspacing='1' cellpadding='0' bgcolor='#000000' width='500'>
				<tr><td>
				<table border='0' cellspacing='0' cellpadding='2' width='100%'>
					<tr>
						<td class='title' align='left' width='20%'>&nbsp;Name:</td>
						<td class='title' align='center' width='80%'>
						</td>
					</tr>
				</table>
				<table border='0' cellspacing='0' cellpadding='2' width='500'>
					<tr>
						<td bgcolor='#FFFFFF' class='bgfill' align='left'>
							<b>&nbsp;" . ( $errorType =~ /1/ ? "<font color=red>First:" : "First:<font color=red>" ) . "*</b></font>
							<input type='text' name='fname' value=\"" . HTML::Entities::encode($fname) . "\" maxlength='49' id='firstName'>
						</td>
						<td align='left' bgcolor='#FFFFFF' class='BOXTD1'>
							<b>" . ( $errorType =~ /9/ ? "<font color='red'>MI:</font>" : "MI:" ) . "</b>
							<input type='text' size='1' name='mname' value=\"" . HTML::Entities::encode($minit) . "\" maxlength='1'>
						</td>
						<td align='left' bgcolor='#FFFFFF' class='BOXTD1'>
							<b>" . ( $errorType =~ /2/ ? "<font color='red'>Last:" : "Last:<font color='red'>" ) . "*</b></font>
							<input type='text' name='lname' value=\"" . HTML::Entities::encode($lname) . "\" maxlength='49'>
						</td>
				</tr>
			</table>
			<table border='0' cellspacing='0' cellpadding='2' width='500'>
				<tr>
					<td class='title' align='left' width='30%'>&nbsp;Email and Phone:</td>
					<td class='title' align='center' width='70%' colspan='2'>
					</td>
				</tr>
			</table>
			<table border='0' cellspacing='0' cellpadding='2' width='500'>
				<tr>
					<td bgcolor='#FFFFFF' class='bgfill'></td>
					<td bgcolor='#FFFFFF' class='bgfill'></td>
					<td bgcolor='#FFFFFF' class='BOXTD1' align='left'> 
						Primary:
					</td>
				</tr>
				<tr>
					<td bgcolor='#FFFFFF' class='bgfill' align='left' width='110'>
						<b>&nbsp;" . ( $errorType =~ /3/ ? "<font color=red>Work email:" : "Work email:<font color=red>" ) . "*</b></font>
					</td>
					<td bgcolor='#FFFFFF' class='bgfill'>
						<input type ='text' name='workEmail' size='50' value=\"" . HTML::Entities::encode($workEmail) . "\" maxlength='254'>
					</td>
					<td bgcolor='#FFFFFF' class='bgfill' align='center'>
						<input type ='radio' " . ( $primaryEmail ne '2' || $primaryEmail eq 'work' ? "checked" : "" ) . " name='primaryEmail' value='work'>
					</td>
				</tr>
				<tr>
					<td bgcolor='#FFFFFF' class='bgfill' align='left' width='110'>
                                                <!-- 20111207 - LM: Changed per Gemini ticket VPN-2672 -->
						<!-- &nbsp;<b>" . ( $errorType =~ /4/ ? "<font color=red>Alternate email:</font>" : "Alternate email:" ) . "</b></font>-->
						<b>&nbsp;" . ( $errorType =~ /4/ ? "<font color=red>Alternate<br>&nbsp;email:" : "Alternate<br>&nbsp;email:<font color=red>" ) . "*</b></font>
					</td>
					<td bgcolor='#FFFFFF' class='bgfill'>
						<input type ='text' name='homeEmail' size='50' value=\"" . HTML::Entities::encode($homeEmail) . "\" maxlength='254'>
					</td>
					<td bgcolor='#FFFFFF' class='bgfill' align='center'>
						<input type ='radio' " . ( $primaryEmail eq '2' || $primaryEmail eq 'home' ? "checked" : "" ) . " name='primaryEmail' value='home'>
					</td>
				</tr>
			</table>
			<table border='0' cellspacing='0' cellpadding='2' width='500'>
				<tr>
					<td bgcolor='#FFFFFF' class='bgfill' align='left' width='100'>
						&nbsp;<b>" . ( $errorType =~ /5/ ? "<font color='red'>Work phone:" : "Work phone:<font color='red'>" ) . "*</b></font>
					</td>
					<td bgcolor='#FFFFFF' class='bgfill'>
						<input type='text' size='20' maxlength='30' name='workPhone' value=\"" . HTML::Entities::encode($workPhone) . "\">
					</td>
					<td bgcolor='#FFFFFF' class='BOXTD1'>
						<b>" . ( $errorType =~ /6/ ? "<font color=red>Alternate phone:</font>" : "Alternate phone:" ) . "</b>
					</td>
					<td bgcolor='#FFFFFF' class='bgfill'>
						<input type='text' size='20' maxlength='30' name='homePhone' value=\"" . HTML::Entities::encode($homePhone) . "\">
					</td>
				</tr>
				<tr>
					<td bgcolor='#FFFFFF' class='bgfill' colspan='4'>
                                        NOTE: It may take up to 15 seconds for your changes to be reflected.   
                                        </td>
                                </tr>  
				<tr>
					<td bgcolor='#FFFFFF' class='bgfill' align='center' colspan='4'>
			";
			
	if ($userInfoPreferences) { $client->repersistValues( values => [ "refreshModule" ] ) };
	
	print $client->getFormInputs();

	
	print "
					</td>
				</tr>
			</table>
			</td></tr>
			</table><br/>

		";

	
	if (defined($error))
	{
		print "
					<font color='red'><b>&nbsp;Error: $error </b></font>
				";
	}

	print "
			<table align='center' border='0' cellspacing='10' style='height: 32px'>
				<tr>
					<td><input type=submit value='Continue'></td>
					<td><input type=button value='Cancel' onClick='$cancelAction'></td>
				</tr>
			</table>
		</form>
		</center>

		<script language='JavaScript1.3' TYPE='text/javascript'>
			document.getElementById('firstName').focus();
		</script>
		";


	$oem->printBodyFooter();
	$oem->printHtmlFooter();

}

sub setUserPassword
{
	my ($tb, $errorType, $error, $validity, $mode, $username, $userId, $auth, $passwdPreferences) = @{{@_}}{qw/tb errorType error validity mode username userId auth passwdPrefs/};
	my $client = $tb->getClient();
	my $cgi = $tb->getCgi();
	my $db = $tb->getPolicyDb();

	my $workEmail = $cgi->param('workEmail');
	my $homeEmail = $cgi->param('homeEmail');
	my $primaryEmail = $cgi->param('primaryEmail');
	my $workPhone = $cgi->param('workPhone');
	my $homePhone = $cgi->param('homePhone');
	my $firstName = $cgi->param('fname');
	my $middleName = $cgi->param('mname');
	my $lastName = $cgi->param('lname');
	my $recieveServiceHome = $cgi->param('recieveServiceHome');
	my $recieveServiceWork = $cgi->param('recieveServiceWork');

	my $errorValue;
	my $errorTypeValue;

	my $requireOldPassword = $cgi->param('reqoldpass');
	my $nostep = $cgi->param('nostep');
	
	$validity = "" unless defined($validity);
	$errorType = 0 unless defined($errorType);
	
	$requireOldPassword = 1 if ($auth eq 'expired' || ( $authTypeName eq 'NTLM' || $authTypeName eq 'PhoneFactor - NTLM' ) );

	my ($eightChars, $numReq, $upperLowerReq, $nonAlphaNumeric, $passMustDiffer) = @{ getPasswordComplexity(tb => $tb, userId=> $userId) };

	# Pop up the password setting page

	my $oemId = $tb->getOemId;
	my $title = "Registration";

	if ( $auth eq 'expired' )
	{
		$title = "Password Expired";
	}

	if ( $auth eq 'expired' )
	{
		$title = "Password Expired";
	}

	$oem->printHtmlHeader( title => $title);
	my $companyLogoSettings = $tb->getCompanyLogoSettings();
	$oem->printBodyHeader(companyText=> $companyLogoSettings->{'companyText'}, companyImage=> $companyLogoSettings->{'companyImage'}, removeSupportImages => $companyLogoSettings->{'removeSupportImages'}, isMobile => $isMobile);

	my $oemStep2Text;
	my $oemStep2Info;

	if ( $oemId == 20 )
	{
		$oemStep2Text = 'Create your new EarthLink VPN password';
		$oemStep2Info = '<b>You\'ll use this password to sign on to the EarthLink VPN service.</b>
								<br><i>Note: This will be your password for both VPNLink and WebLink access.';
	}
	else
	{
		$oemStep2Text = 'Choose your Sign On password';
		$oemStep2Info = 'You\'ll use this password to sign on to the ' . $oem->getSetting(setting => 'rebrandName') . ' service.';
	}

	# If we're in auth mode, set the title and info to convey that the user's password has expired
	if ($auth eq 'expired')
	{
		$oemStep2Text = 'Your password has expired';
		$oemStep2Info = 'Please specify a new password.';

		if ($errorType eq '10')
		{
			$oemStep2Info = "<font color='red'>$error</font><br/<br/>$oemStep2Info";
		}
	}
	print "
		
		<form method='POST' action='main.pl?" . $client->getSessionParams() . "' name='refreshForm'>
			
			";

			my $refreshModule = $client->getPersistedValue( name => "refreshModule" );
	print "
			<input type='hidden' name='module' value=\"" . HTML::Entities::encode($refreshModule) . "\"/>

			";

				print $client->getFormInputs();

	print "
		</form>
		";
								
   print "
	      <div style='text-align: left' class='BOXTD1'><span style='font-size: 18px;'><B>$oemStep2Text" .
			      ((!$nostep) ? ": <font size='2'>(Step 2 of 3)</font> " : "") . "</b></span></div>
			";

											
	print "
			<form autocomplete='off' method=POST action='reg.pl'>
			" . ((length($mode))?"<input type='hidden' name='mode' value=\"" . HTML::Entities::encode($mode) . "\"/>":"") . "
			" . ((length($username))?"<input type='hidden' name='username' value=\"" . HTML::Entities::encode($username) . "\"/>":"") . "
			" . ((defined($nostep))?"<input type='hidden' name='nostep' value=\"" . HTML::Entities::encode($nostep) . "\"/>":"") . "
			" . ((defined($requireOldPassword))?"<input type='hidden' name='reqoldpass' value=\"" . HTML::Entities::encode($requireOldPassword) . "\"/>":"") . "
			" . ((length($cgi->param('password')))?"<input type='hidden' name='password' value=\"" . HTML::Entities::encode($cgi->param('password')) . "\"/>":"") . "
			" . ((defined($auth))?"<input type='hidden' name='auth' value=\"" . HTML::Entities::encode($auth) . "\"/>":"") . "
			" . ((defined($passwdPreferences))?"<input type='hidden' name='passwdPreferences' value=\"" . HTML::Entities::encode($passwdPreferences) . "\">" : "" ) . "
				" . ((defined($cgi->param('oemId')))?"<input type='hidden' name='oemId' value=\"" . HTML::Entities::encode($cgi->param('oemId')) . "\"/>":"") . "
		";

	
	if ($passwdPreferences) { $client->repersistValues( values => [ "refreshModule" ] ) };
	print $client->getFormInputs();
	print "
				<table align='center' border='0' cellpadding='5' cellspacing='0'>
					<tr>
						<td colspan='2' class='BOXTD1' align='center'><br/>$oemStep2Info<br><br></td>
					</tr>
					<tr>
						<td>

							<table cellspacing=1 cellpadding=4 bgcolor='#000000'>
								<tr>
									<td colspan=2 class='title'>
										" . ( defined($passwdPreferences) ? "Change Password" : "Create a password" ) . "	
									</td>
								</tr>
			";

			if ($requireOldPassword)
			{
				print "
								<tr>
									<td bgcolor='#FFFFFF' width='50' class='BOXTD1' align='right'><b>Old password:</b></td>
									<td bgcolor='#FFFFFF' width ='150'><input type='password' name='oldPassword' size=\"" . ($isMobile ? "10" : "20") . "\" maxlength='79' id='oldPassword'></td>
								</tr>
				";
			}

	print "

								<tr>
									<td bgcolor='#FFFFFF' width='50' class='BOXTD1' align='right'><b>" . (($requireOldPassword) ? "New password:" : "Password:") . "</b></td>
									<td bgcolor='#FFFFFF' width ='150'><input type ='password' name='initialPassword' size=\"" . ($isMobile ? "10" : "20") . "\" maxlength='79' id='initialPassword'></td>
								</tr>
								<tr>
									<td bgcolor='#FFFFFF' width='50' class='BOXTD1'><nobr><b>Confirm" . (($requireOldPassword) ? " new " : "" ) . "password:</b></nobr></td>
									<td bgcolor='#FFFFFF'> <input type ='password' name='confirmPassword' size=\"" . ($isMobile ? "10" : "20") . "\" maxlength='79'><br> </td>
								</tr>
							</table> " . ($isMobile ? "<br>" : "
						</td>
						<td>") . "
							<table border='0' cellspacing=\"1\" cellpadding=\"3\" bgcolor=\"#000000\" width=\"100%\">
								<tr>
									<td class='NOTE'>Password Complexity Guidelines:</td>
								</tr>
								<tr>
									<td align='left' bgcolor='#FFFFFF'><ul>
	";

	my @info = @{ getPasswordComplexity(tb=>$tb, userId=> $userId) };

	if ($requireOldPassword)
	{
		if ($validity =~ /oldPassword/)
		{
			print "
				<li class='notes'><font color ='red'><b>Old password correct</b></font></li>";
		}
		else
		{
			print "
				<li class='notes'>Old password correct</li>";
		}

	}

	if ($info[0]->[0])
	{
		if ($validity =~ /lessthan/)
		{
			print "
										<li class='notes'><font color ='red'><b>At least 8 characters</b></font></li>";
		}
		else
		{
			print " 
										<li class='notes'>At least 8 characters</li>";
		}
	}

	if ($info[0]->[1])
	{
		if ($validity =~ /digit/)
		{
			print " 
										<li class='notes'><font color = 'red'><b>At least 1 number</b></font> </li>";
		}
		else
		{
			print " 
										<li class='notes'>At least 1 number </li>";
		}
	}

	if ($info[0]->[2])
	{
		if ($validity =~ /alpha/)
		{
			print " 
										<li class='notes'><font color = 'red'><b>Upper and lower case</b></font> </li>";
		}
		else
		{
			print " 
										<li class='notes'>Upper and lower case</li>";
		}
	}

	if ($info[0]->[3])
	{
		if ($validity =~ /nonalpha/)
		{
			print " 
										<li class='notes'><font color = 'red'><b>At least 1 non-alpha numeric character</b></font></li>";
		}
		else
		{
			print " 
										<li class='notes'>At least 1 non-alpha numeric character</li>";
		}
	}

	if ($info[0]->[4])
	{
		if ($validity =~ /equal/)
		{
			print " 
										<li class='notes'><font color = 'red'><b>Password must differ from old password</b></font></li>";
		}
		else
		{
			print "
										<li class='notes'>Password must differ from old password</li>";
		}
	}

	print "
										<li class='notes'>Case sensitive</li>";

	if ($errorType == '2')
	{
		print " 
										<li class='notes'><font color='red'><b>Passwords must match</b></font></li>";
	}
	else
	{
		print " 
										<li class='notes'>Passwords must match</li>";
 	}

	if ($validity =~ /onechar/ and !$info[0]->[0])
	{
		print "
										<li class='notes'><font color='red'><b>Password must be at least one character</b></font></li>";
	}
	elsif(!$info[0]->[0])
	{
		print "
										<li class='notes'>Password must be at least one character</li>";
	}

	print "
									</ul>
								</td>
							</tr>
						</table>
					</td>
					</tr>
				</table>
				<center>
				<table border='0' cellspacing='10' style='height: 32px'>
					<tr>
						" . (($requireOldPassword) || $passwdPreferences ? "" : "<td><input type=button value='Back' onClick='document.verifyUserInfoBack.submit();'></td>") . "
						<td><input type=submit value='Continue'></td>
						<td><input type=button value='Cancel' onClick='$cancelAction'></td>
					</tr>
				</table>
				</form>
			<form method='POST' name='verifyUserInfoBack' action='reg.pl?" . $client->getSessionParams() . "'>
				<input type='hidden' name='verifyUserInfoBack' value='1'>
				" . ((length($mode))?"<input type='hidden' name='mode' value=\"" . HTML::Entities::encode($mode) . "\"/>":"") . "
				" . ((length($username))?"<input type='hidden' name='username' value=\"" . HTML::Entities::encode($username) . "\"/>":"") . "
				" . ((defined($nostep))?"<input type='hidden' name='nostep' value=\"" . HTML::Entities::encode($nostep) . "\"/>":"") . "
				" . ((defined($requireOldPassword))?"<input type='hidden' name='reqoldpass' value=\"" . HTML::Entities::encode($requireOldPassword) . "\"/>":"") . "
				" . ((length($cgi->param('password')))?"<input type='hidden' name='password' value=\"" . HTML::Entities::encode($cgi->param('password')) . "\"/>":"") . "
				" . ((defined($auth))?"<input type='hidden' name='auth' value=\"" . HTML::Entities::encode($auth) . "\"/>":"") . "
				" . ((defined($passwdPreferences))?"<input type='hidden' name='passwdPreferences' value=\"" . HTML::Entities::encode($passwdPreferences) . "\">" : "" ) . "
					" . ((defined($cgi->param('oemId')))?"<input type='hidden' name='oemId' value=\"" . HTML::Entities::encode($cgi->param('oemId')) . "\"/>":"") . "
		";
	print $client->getFormInputs();
	print "
			</form>

		<script language='JavaScript1.3' TYPE='text/javascript'>
			" . (($requireOldPassword) ? "
			document.getElementById('oldPassword').focus();
			":"
			document.getElementById('initialPassword').focus();
			") . "
		</script>
	";


	$oem->printBodyFooter();
	$oem->printHtmlFooter();

}

sub setUserVerify 
{
	my ($tb, $errorType, $error, $authType, $auth, $username, $password, $mode) = @{{@_}}{qw/tb errorType error authType auth username password mode/};
	my $client = $tb->getClient();

	$oem->printHtmlHeader(title => "Registration");
	my $companyLogoSettings = $tb->getCompanyLogoSettings();
	$oem->printBodyHeader(companyText=> $companyLogoSettings->{'companyText'}, companyImage=> $companyLogoSettings->{'companyImage'}, removeSupportImages => $companyLogoSettings->{'removeSupportImages'}, isMobile => $isMobile);
	
	my $question = $cgi->param('question');

	$question = 'What was your high school mascot?' unless defined($question);

	my $numSteps = 3;
	$numSteps = 2 if $authType == 3;

	print "
	<form autocomplete='off' method='POST' action='reg.pl'>
	<input type='hidden' name='secretQuestion' value='1'>
	" . ((defined($username))?"<input type='hidden' name='username' value=\"" . HTML::Entities::encode($username) . "\"/>":"") . "
	" . ((defined($password))?"<input type='hidden' name='password' value=\"" . HTML::Entities::encode($password) . "\"/>":"") . "
	" . ((defined($auth))?"<input type='hidden' name='auth' value=\"" . HTML::Entities::encode($auth) . "\"/>":"") . "
	" . ((defined($mode))?"<input type='hidden' name='mode' value=\"" . HTML::Entities::encode($mode) . "\"/>":"") . "
	" . ((defined($nostep))?"<input type='hidden' name='nostep' value=\"" . HTML::Entities::encode($nostep) . "\"/>":"") . "
	" . ((defined($cgi->param('oemId')))?"<input type='hidden' name='oemId' value=\"" . HTML::Entities::encode($cgi->param('oemId')) . "\"/>":"") . "
	" . ((defined($cgi->param('userPrefsUpdate')))?"<input type='hidden' name='questionUserPrefsUpdate' value=\"" . HTML::Entities::encode($cgi->param('userPrefsUpdate')) . "\"/>":"") . "
		<table cellspacing='0' cellpadding='0' border='0' width='100%' style='height: 400px'>
			<tr valign='top' style='height: 350px'>
				<td width='100%'>
					<table border='0' width='100%'>
						<tr>
							<td class='BOXTD1' align='left' width='100%' colspan='3'><span style='font-size: 18px;'><b>
							Secret question and answer " . ((!$nostep) ? ": <font size='2'>(Step $numSteps of $numSteps)</font> " : "") . "</b></span>
							</td>
						</tr>
						<tr>
							<td align='center' style='height: 75px;' align='center'>
								<table border=0 cellpadding=4 cellspacing=2>
									<tr>
										<td colspan='2'>
											<table align='center' valign='middle' border='0' cellspacing='0' cellpadding='0'>
												<tr>
													<td width='100%' class='BOXTD1'>
														<b>
														Choose a question only you know the answer to
														and that has nothing to do with your password.<br> This helps us
														verify your identity if you forget your password or need
														other administrative assistance.
														</b>
													</td>
												</tr>
											</table>
										</td>
									</tr>
									<tr>
										<td valign='top'>
											<table cellpadding='1' cellspacing='1' bgcolor='#000000'><!-- style='height: 85px' -->
												<tr>
													<td class='title' width='100%' colspan='2'>
														<b><font size='2'>Create a secret question and answer:</font></b>
													</td>
												</tr>
												<tr>
													<td align='right' class='BOXTD1'>
														<b>Question:</b>
													</td>
													<td bgcolor='#FFFFFF' height='32'>
														<input type='text' size='50' name='question' value=\"" . HTML::Entities::encode($question) . "\" maxlength='255' style='margin: 5px;'>
													</td>
												</tr>
												<tr>
													<td align='right' class='BOXTD1'>
														<b>Answer:</b>
													</td>
													<td bgcolor='#FFFFFF'>
														<input type='text' name='initialAnswer' maxlength='254' id='initialAnswer' style='margin: 5px;'>
													</td>
												</tr>
												<tr>
													<td align='right' class='BOXTD1'>
														<nobr><b>Confirm Answer:</b></nobr>
													</td>
													<td bgcolor='#FFFFFF'>
														<input type='text' name='confirmAnswer' maxlength='254' style='margin: 5px;'>
													</td>
												</tr>
											</table>
											<center>
											";
				if ($errorType == '1')
				{
					print "
											<center>
											<font color='red' size=2><b>Error: $error</b></font>
											</center>
							";
				}
	
	print "	
											<table border='0' cellspacing='10' style='height: 32px'>
												<tr>
													<td><input type=button value='Back' onClick='document.initialPasswordBack.submit()'></td>
													<td><input type=submit value='Finish'></td>
													<td><input type=button value='Cancel' onClick=\"javascript:document.location.href='" . $oem->getSetting(setting=>'webtopUrl') . "';\"></td>
												</tr>
												<script language='JavaScript1.2' TYPE='text/javascript'>
													document.getElementById('initialAnswer').focus();
												</script>
											</table>
											</center>
			";		
	print $client->getFormInputs();
	
				print "
										</td>
										<td>
											<table border='0' cellspacing='1' cellpadding='3' bgcolor='#000000' width='80%'>
												<tr>
													<td class='note'>Security Tip:</td>
												</tr>
												<tr>
													<td bgcolor='#FFFFFF' width='100%' class='BOXTD1'>
														<p align='left' style='margin-right: -3; margin-top: 0; margin-bottom: 0; font-size: 8pt; font-weight: bold;'>
														Ensure your question is:
														</p>
														<ul style='margin-top: 1px; margin-bottom: 1px;'>
															<li class='notes'>something only you will know</li>
															<li class='notes'>not related to your password</li>
															<li class='notes'>unlikely to change over time</li>
															<li class='notes'>difficult for others to guess</li>
														</ul>
													</td>
												</tr>
												<tr>
													<td class='note' width='100%'>Examples:</td>
												</tr>
												<tr>
													<td bgcolor='#FFFFFF' width='100%'>
														<ul style='margin-top: 1px; margin-bottom: 1px'>
															<li class='notes'>What was your high school mascot?</li>
															<li class='notes'>What was your favorite pet's name?</li>
															<li class='notes'>What is your favorite movie?</li>
															<li class='notes'>What was your favorite teacher's name?</li>
															<li class='notes'>What is your favorite sports team?</li>
															<li class='notes'>What is your favorite meal?</li>
															<li class='notes'>What is your favorite ice cream flavor?</li>
															<li class='notes'>What is the first and last name of your first boyfriend or girlfriend?</li>
															<li class='notes'>Which phone number do you remember most from your childhood?</li>
															<li class='notes'>What was your favorite place to visit as a child?</li>
															<li class='notes'>Who is your favorite actor, musician, or artist?</li>
														</ul>
													</td>
												</tr>
											</table>
										</td>
									</tr>
								</table>
							<td>
						</tr>
					</table>
				</td>
			</tr>
			<tr>
				<td align='center'>
				</td>
			</tr>
		</table>
	</form>
			<form method='POST' name='initialPasswordBack' action='reg.pl?" . $client->getSessionParams() . "'>
				<input type='hidden' name='initialPasswordBack' value='1'>
					" . ((length($username))?"<input type='hidden' name='username' value=\"" . HTML::Entities::encode($username) . "\"/>":"") . "
					" . ((length($password))?"<input type='hidden' name='password' value=\"" . HTML::Entities::encode($password) . "\"/>":"") . "
					" . ((defined($auth))?"<input type='hidden' name='auth' value=\"" . HTML::Entities::encode($auth) . "\"/>":"") . "
					" . ((defined($mode))?"<input type='hidden' name='mode' value=\"" . HTML::Entities::encode($mode) . "\"/>":"") . "
					" . ((defined($nostep))?"<input type='hidden' name='nostep' value=\"" . HTML::Entities::encode($nostep) . "\"/>":"") . "
					" . ((defined($cgi->param('oemId')))?"<input type='hidden' name='oemId' value=\"" . HTML::Entities::encode($cgi->param('oemId')) . "\"/>":"") . "
		";
	print $client->getFormInputs();
	print "
			</form>
	<br/>
";

	$oem->printBodyFooter();
	$oem->printHtmlFooter();

}

sub validatePassword 
{
	my ($tb, $userId, $auth, $password) = @{{@_}}{qw/tb userId auth password/};
	my $client = $tb->getClient();
	my $cgi = $tb->getCgi();
	my $db = $tb->getPolicyDb();

	my $pc = getPasswordComplexity(tb => $tb, userId => $userId);
	my $eightChars = $pc->[0];

	my $hexedPass = Digest::MD5::md5_hex($password);

	my ($oldPassword) = $db->query(sql=>"
			SELECT password 
			FROM users 
			WHERE user_id = $userId
		");

	my $error = 0;

	# If we need to validate the old password, do so now
	# This needs to be investigated for security issues.  A malicious user could
	# not supply reqoldpass.
	my $requireOldPassword = $cgi->param('reqoldpass');

	if ($requireOldPassword or $auth eq 'expired')
	{

		if ($authTypeName ne 'NTLM')
		{
			my $oldPass = $cgi->param('oldPassword');
			my $oldPassHash = Digest::MD5::md5_hex($oldPass);
	
			if (uc($oldPassHash) ne uc($oldPassword))
			{
				$error .= 'oldPassword';
			}
		}
	}

	if($eightChars->[0])
	{
		if ( length($password) < 8) 
		{
			$error .= 'lessthan';
		}
	}

	if($eightChars->[1])
	{
		if ($password !~ /\d/)
		{
			$error .= 'digit';
		}
	}

	if($eightChars->[2])
	{
		if ($password !~ /[A-Z]/ or $password !~ /[a-z]/)
		{
			$error .= 'alpha';
		}
	}

	if($eightChars->[3])
	{
		if ($password !~ /\W/)
		{
			$error .= 'nonalpha';
		}
	}

	if($eightChars->[4])
	{
		if (uc($hexedPass) eq uc($oldPassword))
		{
			$error .= 'equal';
		}
	}

	if (!length $password)
	{
		$error .= 'onechar';
	}

	return $error;
}

sub getPasswordComplexity 
{
	my ($tb,$userId) = @{{@_}}{qw/tb userId/};
	my $db = $tb->getPolicyDb();
	my $client = $tb->getClient();

	my $sql = "
					SELECT eight_characters, one_number, upper_lower_case, non_alpha_numeric, password_must_differ
					FROM user_auth_requirements
					WHERE user_id = $userId
				";

	my @passwordComplexity = $db->query(sql=>$sql);
	return \@passwordComplexity;
}
