#!/usr/bin/perl
#
# $Id: regsas.pl,v 1.21 2006/11/28 21:07:48 psims Exp $
#
# Source File: regsas.pl

# Set variables local to this code file.

# HBI Shorten validation key to less characters.
%Long_Val_Client = () ; 
# Inital value, no clients use the long validation string. 
# This is a global that could be modified in sitecfg.pl
my $Short_Val_off = 1 ; # Start with the second digit of the computed value.
my $Short_Val_len = 3 ; # Use three characters.

# Get config
require 'sitecfg.pl';
require 'testlib.pl';

&app_initialize;

&setbrowsertype();
if ($FORM{'newsas'} ne "") {
	$SESSION{'clid'} = $FORM{'clid'};
	$SESSION{'lang'} = $FORM{'lang'};
	&get_client_configuration();
	&LanguageSupportInit();
	if ($FORM{'dbop'} eq 'save') {
		&get_client_profile($SESSION{'clid'});
		if (&adduidreq($SESSION{'clid'},$FORM{'uidreq'},$FORM{'pwdreq'})) {
			$FORM{'uid'}=$FORM{'uidreq'};
			$CANDIDATE{'uid'}=$FORM{'uidreq'};
			$FORM{'clid'}=$SESSION{'clid'};
			&get_candidate_profile($SESSION{'clid'}, $FORM{'uid'}, $opts);
			&send_the_mail("$CLIENT{'clid'}.emlsend", "testmanager.com Personal Validation Key", $FORM{'eml'}) unless $CLIENT{'emlval'} ne "Y"; 
			$FORM{'uac'}='sas';
			&init_session;
			&LanguageSupportInit();
			my $opts = { restrict_to_availability_window => 1 };
			&get_candidate_profile($SESSION{'clid'}, $SESSION{'uid'}, $opts);
			&log_entry($SESSION{'clid'}, $SESSION{'uid'}, "1");
			$FORM{'notice'} = $SYSTEM{'message'};
			$CANDIDATE{'badid'}="";
		} else {
			&get_candidate_profile($SESSION{'clid'}, $FORM{'uid'});
			if ($FORM{'allowin'} ne "Y") {
				$CANDIDATE{'firstlogin'}="";
				$CANDIDATE{'new'}="Y";
				$errmess = $xlatphrase[758];
				$CANDIDATE{'badid'}="$xlatphrase[758]";
                        }
		}

		#$CANDIDATE{'sal'}="";
		#$CANDIDATE{'nmf'}=$FORM{'nmf'};
		#$CANDIDATE{'nmm'}=$FORM{'nmm'};
		#$CANDIDATE{'nml'}=$FORM{'nml'};
		#$CANDIDATE{'adr'}=$FORM{'adr'};
		#$CANDIDATE{'cty'}=$FORM{'cty'};
		#$CANDIDATE{'ste'}=$FORM{'ste'};
		#$CANDIDATE{'pst'}=$FORM{'pst'};
		#$CANDIDATE{'ctry'}=$FORM{'ctry'};
		#$CANDIDATE{'eml'}=$FORM{'eml'};
		#$CANDIDATE{'cnd1'}=$FORM{'cnd1'};
		#$CANDIDATE{'cnd2'}=$FORM{'cnd2'};
		#$CANDIDATE{'cnd3'}=$FORM{'cnd3'};
		#$CANDIDATE{'cnd4'}=$FORM{'cnd4'};
		#$CANDIDATE{'uid'}=$FORM{'uid'};
		if ($CANDIDATE{'badid'} eq "$xlatphrase[758]") {
			if ($errmess2 ne '') { #This is the fast way to patch error messages
				$FORM{'badid'} = $errmess2;
			} else {
				$FORM{'badid'} = $errmess unless $errmess eq '';
			}
			print "Content-Type: text/html\n\n";
			&show_template("regsas");
		} else {
			$vars{'home'}  = "client";
			$vars{'lang'} = "$FORM{'lang'}";
			$vars{'uid'} = "$CANDIDATE{'uid'}";
			$vars{'pwd'} = "$CANDIDATE{'pwd'}";
			$vars{'clid'} = "$SESSION{'clid'}";
			$vars{'cnd'} = "Login";
			$vars{'newsas'} = "";
			$vars{'dbop'} = "$FORM{'dbop'}";

			&redirect("login", \%vars);
		}
	}
} else {
	if (&get_session($FORM{'tid'})) {
		&LanguageSupportInit();
		if ($FORM{'lang'} eq "") { $FORM{'lang'} = $SESSION{'lang'}; }
		if ($FORM{'dbop'} eq 'logout') {
			$indextemplate = ($SESSION{'clid'} eq 'std') ? "shome" : "cindex";
			if ($SESSION{'clid'} ne 'std') {&get_client_profile($SESSION{'clid'});}
			print "Content-Type: text/html\n\n";
			&show_template("$indextemplate");
		} elsif ($FORM{'dbop'} eq 'save') {
			&get_client_profile($SESSION{'clid'});
			&get_candidate_profile( $SESSION{'clid'}, $SESSION{'uid'});
                	foreach (keys %CANDIDATE) {
                       		if (!( defined($FORM{$_}) )) {
                               			$FORM{$_} = $CANDIDATE{$_};
                        	}
				if ($CLIENT{'savechange'} eq "N") {
                               		$FORM{$_} = $CANDIDATE{$_} unless $_ eq 'pwd';
				}
                        	if ($_ eq 'pwd') { #Do this type of check for filters based on seperate buttons
                               		if ($FORM{'oldpwdval'} ne $CANDIDATE{'pwd'} && $FORM{'oldpwdval'} ne '') {
                                        	$errmess = "$xlatphrase[888]";
						$direction = "password";
                                        	$FORM{$_} = $CANDIDATE{$_};
                                	} else {
                                        	$errmess = "$xlatphrase[879]" unless $FORM{'oldpwdval'} eq '';
                                	}
                        	}
				if ($FORM{'eml'} ne $CANDIDATE{'eml'}) { #Do this type of check on every subsequent filter based revision
					$FORM{'validated'} = 'N';
					$continue_eml_tests = 1;
					&send_the_mail("$CLIENT{'clid'}.emlsend", "testmanager.com Personal Validation Key", $FORM{'eml'}) unless $CLIENT{'emlval'} ne "Y"; 
					$CANDIDATE{'badid'}="$xlatphrase[872]" unless $CLIENT{'emlval'}  ne "Y";
					&get_client_profile($SESSION{'clid'});
					if ( ($CLIENT{'emlacl'} eq "Y") && ($continue_eml_tests == 1) ){
						my @tempacl = &popEmlAcl($CLIENT{'clid'});
						if ($CLIENT{'emlacllst'} eq "B") {
							foreach (@tempacl) {
								if ($FORM{'eml'} =~ /$_/g) {
									$FORM{'eml'} = $CANDIDATE{'eml'};
									$continue_eml_tests = 0;
									$errmess = $xlatphrase[903];
								}
							}
						}
						if ($CLIENT{'emlacllst'} eq "W") {
							foreach (@tempacl) {
								$tempemlacltest .= $_;
							}
							$tmpemladr = $FORM{'eml'};
							$tmpemladr =~ s/@/ /g;
							$tmpemladr =~ /\w+\.\w+$/g;
							$tmpemladr = $&;
							if ( !($tempemlacltest =~ /$tmpemladr/) ) {
								$FORM{'eml'} = $CANDIDATE{'eml'};
								$continue_eml_tests = 0;
								$errmess = $xlatphrase[903];
							}
						}
					}
					if ( ($CLIENT{'emlstrict'} eq "Y") && ($continue_eml_tests == 1) ) {
						my $clid = $SESSION{'clid'};
						my @cndcols = &get_data("cnd.$SESSION{'clid'}");
						my @duplicates = grep(/$FORM{'eml'}/, @cndcols);
						foreach (@duplicates) {
							$errmess = $xlatphrase[904];
							$continue_eml_tests = 0;
							$FORM{'eml'} = $CANDIDATE{'eml'};
						}
					}
				}
			}
			&put_candidate_profile($SESSION{'clid'}, $SESSION{'uid'});
			&get_candidate_profile( $SESSION{'clid'}, $SESSION{'uid'});
        	        if ($CANDIDATE{'badid'} eq "$xlatphrase[758]" || $CANDIDATE{'badid'} eq "$xlatphrase[872]") {
                                $vars{'home'}  = "client";
                                $vars{'lang'} = "$FORM{'lang'}";
                                $vars{'uid'} = "$CANDIDATE{'uid'}";
                                $vars{'pwd'} = "$CANDIDATE{'pwd'}";
                                $vars{'clid'} = "$SESSION{'clid'}";
                                $vars{'cnd'} = "Login";
				$vars{'badid'} = "$xlatphrase[758]" unless $CANDIDATE{'badid'} ne "$xlatphrase[758]";
				$vars{'badid'} = "$xlatphrase[872]" unless $CANDIDATE{'badid'} ne "$xlatphrase[872]";
			&redirect("login", \%vars);
               	 	} else {
               	       		$vars{'home'}  = "client";
               	       		$vars{'lang'} = "$FORM{'lang'}";
               	      		$vars{'uid'} = "$CANDIDATE{'uid'}";
               	   		$vars{'pwd'} = "$CANDIDATE{'pwd'}";
               	       		$vars{'clid'} = "$SESSION{'clid'}";
                       		$vars{'cnd'} = "Login";
				$vars{'badid'} = $errmess unless $errmess eq '';
				$vars{'direction'} = $direction unless $direction eq '';
				&redirect("login", \%vars);
                	}
			#print "Content-Type: text/html\n\n";
			#&show_template("regsas");
		 } elsif ($FORM{'dbop'} eq 'resend') {
			&resend_exit_emails($SESSION{'clid'}, $SESSION{'uid'}, $FORM{'tstid'});
			$vars{'tid'} = "$SESSION{'tid'}";
			$vars{'lang'} = "$SESSION{'lang'}";
			&redirect("regsas", \%vars);
		} else {
			&get_client_profile($SESSION{'clid'});

			my $opts = { restrict_to_availability_window => 1 };
			&get_candidate_profile( $SESSION{'clid'}, $SESSION{'uid'}, $opts);
			my $realkey = &makecndhash($CANDIDATE{'createdate'}, $CANDIDATE{'uid'});
			$realkey =~ s/-//g;
			# HBI Shorten validation key to less characters.
			unless ($Long_Val_Client{$SESSION{'clid'}} ) {
				$realkey = substr($realkey, $Short_Val_off, $Short_Val_len) ;
			}
			$FORM{'validationcode'} =~ s/-//g;
			if ($CLIENT{'emlval'} eq "Y") { #If the client doesnt want selfreg eml validation, ignore this and go straight to regsas.
				if ($CANDIDATE{'selfreg'} eq "Y" && $CANDIDATE{'validated'} eq "N") {
					if ($FORM{'resendkey'} eq "Y") {
						$SESSION{'message'} = "<%=PHRASE.868%>";
						&send_the_mail("$CLIENT{'clid'}.emlresend", "testmanager.com Personal Validation Key", $CANDIDATE{'eml'});
						print "Content-Type: text/html\n\n";
						&show_template("validatesreg");
					} elsif ($FORM{'validationcode'} eq $realkey) {
						$FORM{'validated'} = "Y";
						$FORM{'uid'} = $CANDIDATE{'uid'}; #This is because regsas is terribly broken when it treats form variables
						&put_candidate_profile($SESSION{'clid'}, $SESSION{'uid'});
						#&show_template("regsas");
						$vars{'home'}  = "client";
						$vars{'lang'} = "$FORM{'lang'}";
						$vars{'uid'} = "$CANDIDATE{'uid'}";
						$vars{'pwd'} = "$CANDIDATE{'pwd'}";
						$vars{'clid'} = "$SESSION{'clid'}";
						$vars{'cnd'} = "Login";
			
						&redirect("login", \%vars);
					} else {
						if ($FORM{'validationcode'} ne '') {
							$SESSION{'message'} = "<%=PHRASE.867%>";
						} else {
							$SESSION{'message'} = "<br>";
						}
						print "Content-Type: text/html\n\n";
						&show_template("validatesreg");
					}
				} elsif ($CANDIDATE{'selfreg'} eq "Y" && $CANDIDATE{'validated'} eq "Y") {
					print "Content-Type: text/html\n\n";
					$FORM{'allowin'} = "Y";
					&show_template("regsas");
				} else { #Dont punish old sreggers without a $CANDIDATE{'validated'} value, which is all of them to this point
					$FORM{'allowin'} = "Y";
					print "Content-Type: text/html\n\n";
					&show_template("regsas");
				}
			} else {
				print "Content-Type: text/html\n\n";
				if ($errmess ne '') {
					$FORM{'badid'} = $errmess;
				}
				&show_template("regsas");
			}
		}
	}
}
#
# Verify that the requested id is not already
# used in admin.dat or cnd.{client}
# if not used add it to the cnd.{client} file
#
sub adduidreq {
	my ($clid,$urq,$urpw) = @_;
	my @crecs = &get_data("admin.dat");
	my $rec;
	my $i;
	my $fldkey;
	my $fldval;
	my $trash;
	my @flds;
	my $retOK=1;
	my @found = grep( /$urq&/ ,@crecs);
	if ($#found != -1) {
		#
		# verify that the first field is the requested urq
		# just in case grep picked it up somewhere else in the record
		#
		foreach $rec (@found) {
			@flds=split(/&/, $rec);
			if ($flds[0] eq $urq) {
				$retOK=0;
				$last;
			}
		}
	}
	my $cndeml = $FORM{'eml'};
	if ($CLIENT{'emlacl'} eq "Y") {
		my @tempacl = &popEmlAcl($SESSION{'clid'});
		if ($CLIENT{'emlacllst'} eq "B") {
			foreach (@tempacl) {
				if ($cndeml =~ /$_/g) {
					$retOK = 0;
					$errmess2 = $xlatphrase[903];
				}
			}
		}
		if ($CLIENT{'emlacllst'} eq "W") {
			foreach (@tempacl) {
				$tempemltest .= $_;
			}
			$tmpemladr = $cndeml;
			$tmpemladr =~ s/@/ /g;
			$tmpemladr =~ /\w+\.\w+$/g;
			$tmpemladr = $&;	#the domain.ltd part of user@domain.ltd
			if ( !($tempemltest =~/$tmpemladr/) ) {
				$retOK = 0;
				$errmess2 = $xlatphrase[903];
			}
		}
		
	}
	if ($CLIENT{'emlstrict'} eq "Y") {
		my @cndcols = &get_data("cnd.$clid");
		my @duplicates = grep(/$cndeml/, @cndcols);
		foreach (@duplicates) {
			$retOK=0;
			$errmess2 = $xlatphrase[904];
		}
	}
	if ($retOK == 1) {
		@crecs = &get_data("cnd.$clid");
		my $rhdr = shift @crecs;
		@found = grep( /$urq&/ ,@crecs);
		if ($#found != -1) {
			#
			# verify that the first field is the requested uid
			# just in case grep picked it up somewhere else in the record
			#
			foreach $rec (@found) {
				@flds=split(/&/, $rec);
				if ($flds[0] eq $urq) {
					$retOK=0;
					$last;
				}
			}
		}
		if ($retOK == 1) {
			#
			# add the requested uid
			#
			$rec=$rhdr;
			chop($rec);
			@flds=split(/&/,$rec);
			$rec = join('&',$urq,$urpw);
			$FORM{'selfreg'} = "Y";
			for $i (2 .. $#flds) {
				$fldkey=$flds[$i];
				$FORM{$fldkey} =~ tr/+/ /;
				$fldval=$FORM{$fldkey};
				$rec = join('&', $rec, $fldval);
			}
			push @crecs,"$rec\n";
			my @csorted = sort @crecs;
			@crecs=();
			unshift @csorted,$rhdr;
			$retOK=0;


			#This adds createdate and validated to the new candidate stack
			my $shift_hack = shift(@csorted);
			$shift_hack =~ (s/authtests/createdate/);
			$shift_hack =~ (s/grpid/createdby/);
			$_ = $shift_hack;
			if ( !(/validated/)) {
				chomp $shift_hack;
				$shift_hack .= '&validated'."\n";
			}
			if ( !(/registrar/)) {
				chomp $shift_hack;
				$shift_hack .= '&registrar'."\n";
			}
			### DED 3/26/07 These fields not yet supported
			#if ( !(/cnd3/)) {
				#chomp $shift_hack;
				#$shift_hack .= '&cnd3'."\n";
			#}
			#if ( !(/cnd4/)) {
				#chomp $shift_hack;
				#$shift_hack .= '&cnd4'."\n";
			#}
			unshift (@csorted, $shift_hack);

			my @labels = split('&', @csorted[0]);
			my @fields;
			foreach (@csorted) {
				if (/^$urq&/) {
					@fields = split('&', $_);
				}
			}
			my %turbohash = (); #merge them into a hash
				foreach (0..$#labels) { 		
					$turbohash{$labels[$_]} = $fields[$_];
				}
				$turbohash{'createdate'} = time();
				$turbohash{'createdby'} = $FORM{'uidreq'};
				$turbohash{'validated'} = 'N';
			#Now we have to put them all together in the same order as the key row
			my $client_string; #will hold the temp. line for cnd.clientid
			foreach (0..$#labels) {
				chomp($labels[$_]); #chomp it because $labels[-1] is actually $labels[-1]\n
				$client_string .= "&$turbohash{$labels[$_]}";
			}
			$client_string =~ s/^&//; 
			$client_string =~ s/\n//g;
			$client_string =~ s/\+/ /g;
			$client_string .= "\n"; #insert the \n after the chomp
			foreach my $rotator (1..$#csorted) { 		#scary part where we insert it back into the array
				if ($csorted[$rotator] =~ /^$urq&/) {
					$csorted[$rotator] = $client_string;
				}
			}
					

			my $tmpfile = join($pathsep, $dataroot, "cnd.$clid");
			my $existed=&file_exists($tmpfile);
			if ( open (TMPFILE, ">$tmpfile") ) {
				for $i (0 .. $#csorted) {
					print TMPFILE "$csorted[$i]";
				}
				close TMPFILE;
				if ($existed==0) {
					$chmodok = chmod 0666, $_[0];
				}
				$retOK=1;
			}
			@csorted=();
		}
	}
	#
	# clean up
	#
	@flds=();
	@found=();
	@crecs=();
	return $retOK;
}



sub send_the_mail {	#This is a special function to send the validation key email. Shouldn't ever be needed outside this file.
	my $mmfrom = $CLIENT{'email_from'};
        my $eml_txt = join( $pathsep, $dataroot,  $_[0]);
        my $mmsubj = $_[1];
        my $mmto = $_[2];
        my $hash_createdate = &get_a_key("cnd.$SESSION{'clid'}", $CANDIDATE{'uid'}, "createdate");
        my $mmbody = '';
        if ( open(EMLBODY, "<$eml_txt") ) {
        	foreach (<EMLBODY>) {
                	$mmbody .= $_;
        		close(EMLBODY);
        	}
	} else {
		$mmbody = "Thank you for registering at $ENV{'HTTP_HOST'}. Your personal Registration Code is <%=NOP_valkey%>. You will only have to enter it once.\n"
	}
	#insert customized regex here
	my $valkey = &makecndhash($hash_createdate, $CANDIDATE{'uid'});
	#print STDERR "valkey = $valkey, hash_createdate = $hash_createdate, uid = $CANDIDATE{'uid'}\n";	#uncomment this to see all necessary validation key info
	# HBI Shorten validation key to less characters.
	unless ($Long_Val_Client{$SESSION{'clid'}} ) {
		$valkey =~ s/-//g;
		$valkey = substr($valkey, $Short_Val_off, $Short_Val_len) ;
	}
        $mmbody =~ s/\<%=NOP_valkey%\>/$valkey/g;
	$mmbody = &xlatline($mmbody, '', 0);
	&send_mail($mmfrom, $mmto, $mmsubj, $mmbody);
}