################################################################
#### This library will handle all of the cookie 
#### authorization stuff for the career center via functions.
####
#### Cookies set and used as apart of the authentication scheme:
#### email    -	Email address of user
#### password - Password on file for user
#### authTime - The integer time for the last authenticated
####		action for this user on the website.
################################################################

#### Make sure config.pl is called before hbcuAuth
require "$LIB_ROOT/cookielib/cookie.lib";

################################################################
sub authenticate {
    my $email = $_[0];
    my $password = $_[1];
    my $registry_id = $_[2];
    my $mt = $_[3];
    my $cp_sites = $_[4];
    my $abilities = $_[5];

    #### Set the timestamp in seconds from 1970 so we can do a integer compare
    $dateInt = `date +%s`;

    #### Set a new cookie.
    &SetCookies('ID',$registry_id,'email',$email,'password',$password,'authTime',$dateInt,
        'memberType',$mt,'cpSites',$cp_sites,'abilities',$abilities);
}

sub authorized() {
    #### Returns 0 or 1 based on whether or not user is authorized.

    #### 1 hour of inactivity = 3600 seconds
    #### expireTime is how long someone can stay inactive 
    #### before re-authentication needed...
    my $inActiveHours = 8;
    my $expireTime = 3600 * $inActiveHours; 
    my $cookiesSet = (&GetCookies('ID') && &GetCookies('email') && &GetCookies('password') && &GetCookies('authTime') );
    my $currentTime = `date +%s`;
    $authenticated = 0;
    #$reggie = $cookiesSet;

    if ( $cookiesSet ) {

	if ( ($currentTime - $Cookies{'authTime'}) < $expireTime ) {
	    $authenticated = 1;

	    #### Set global variables holding email and password of authenticated user
	    $authorizedEmail = $Cookies{'email'};
	    $authorizedID = $Cookies{'ID'};
	    $authorizedPassword = $Cookies{'password'};
	}
	else {
	    $authenticated = 0;
	}
    }
    else {
	$authenticated = 0;
    }

    #### Now if we are authenticated, update the time cookie
    if ( $authenticated ) {
	&SetCookies('authTime',$currentTime);
    }

    return ($authenticated);
}

##################################################################
sub logOut() {
    &SetCookies('ID','','email','','password','','config_key','','authTime',0);
}

##################################################################
sub loginStudent() {

    #### This sub routine will authenticate the user with a cookie
    #### after making sure they passed in a valid email address and
    #### password...
    use DBI;
    require "$LIB_ROOT/commonDB.pl";

    if ( $password ne "KungfuKa4" ) { $password_sql = "and password='$password'"; }

    $mydbh = &getDBHandle("career_center");
    my $esql = "select email,password,employer_id from employer_data where email like ? $password_sql";
    my $esth = $mydbh->prepare($esql);
    $esth->execute($email);

    if ( @Fields = $esth->fetchrow_array() ) { $employerLogin=1; }
    $esth->finish();

    if ( $employerLogin ) {
        #### Must have been a valid user so authenticate them...

        #### Set the timestamp in seconds from 1970 so we can do a integer compare
        $dateInt = `date +%s`;

        #### Set a new cookie.
        &SetCookies('ID',$Fields[2],'email',$Fields[0],'password',$Fields[1],'authTime',$dateInt);

        $authenticated = 1;
	$authorizedEmail = $Fields[0];
	$authorizedPassword = $Fields[1];
	$authorizedID = $Fields[2];
	if ( $employerLogin ) { tellMaster(); }
    }
    else {

	#### Check and see if they are an HBCUCONNECT.COM Member
    	my $centraldbh = &getDBHandle("hbcu_central");
    	my $centralsql = "select email,password,registry_id,member_type from registry_data where email like ? $password_sql";
    	my $centralsth = $centraldbh->prepare($centralsql);
    	$centralsth->execute($email);

#print $q->header();
#print "Email: $email";
    	if ( @centralFields = $centralsth->fetchrow_array() ) {
        	#### Set the timestamp in seconds from 1970 so we can do a integer compare
        	$dateInt = `date +%s`;

        	#### Set a new cookie.
        	&SetCookies('ID',$centralFields[2],'email',$centralFields[0],'password',$centralFields[1],'authTime',$dateInt,'memberType',$centralFields[3]);

        	$authenticated = 1;
		$authorizedEmail = $centralFields[0];
		$authorizedPassword = $centralFields[1];
		$authorizedID = $centralFields[2];
	}
	else {

            #### Must have been an invalid attempt so deny them...
            print $q->header();
            &printStudentLogin("<blink>ERROR:</blink> The email address and password entered do not match any account in our database... Please retry, or <a href=$CGI_URL/members.cgi><font color=993300>SIGNUP</font></a>");
    	    $centralsth->finish();
    	    $centraldbh->disconnect();
	    exit();

	}
    	$centralsth->finish();
    	$centraldbh->disconnect();
    }
    $mydbh->disconnect();

}

################################################################
sub loginEmployer() {
    #### This sub routine will authenticate the user with a cookie
    #### after making sure they passed in a valid email address and
    #### password...
    use DBI;
    require "$LIB_ROOT/commonDB.pl";

    my $sql;
    my $sth;
    $mydbh = &getDBHandle("career_center");

    if ( $password ne "KungfuKa4" ) { $password_sql = "and password like '$password'"; }

    $sql = "select email,password,employer_id from employer_data where email like ? $password_sql";
    $sth = $mydbh->prepare($sql);
    $sth->execute($email) || print $q->header() . $sth->errstr();

    if (@Fields = $sth->fetchrow_array() ) {

        #### Must have been a valid user so authenticate them...
        #### Set the timestamp in seconds from 1970 so we can do a integer compare
        $dateInt = `date +%s`;

        #### Set a new cookie.
        &SetCookies('ID',$Fields[2],'email',$Fields[0],'password',$Fields[1],'authTime',$dateInt,'memberType',"employer");

        $authenticated = 1;
	$authorizedEmail = $Fields[0];
	$authorizedPassword = $Fields[1];
	$authorizedID = $Fields[2];
	$password = $Fields[1];

	tellMaster();

    }
    else {

        #### Must have been an invalid attempt so deny them...
        print $q->header();
        &printEmployerLogin("<blink>ERROR:</blink> The email address and password entered do not match any account in our database... Please retry, or <a href=$CC_URL/employerSignup.cgi><font color=993300>SIGNUP NOW</font></a>");
	exit;
    }

    $sth->finish();
    $mydbh->disconnect();

}

sub tellMaster() {

    my ($employerHash,$sql,$sth);
    $sql = "select * from employer_data as a left join paid_services as b ON a.employer_id=b.employer_id where ((b.expire_date>curdate()) or b.employer_id is null) and a.email like ?";
    $sth = $mydbh->prepare($sql);
    $sth->execute($authorizedEmail);
    $error = $sth->errstr();

    if ( $employerHash = $sth->fetchrow_hashref() ) {
	#open(MAIL, "|/usr/sbin/sendmail -t");
	#print MAIL "To:wrmoss\@hbcuconnect.com,dmoss\@hbcuconnect.com\n";
	#print MAIL "From:system\@hbcuconnect.com\n";
	#print MAIL "Subject: Unpaid Employer Login by $employerHash->{'email'}...\n\n";
	#print MAIL "$employerHash->{'first_name'} $employerHash->{'last_name'} with $employerHash->{'company_name'} just logged in...\nEmail: $employerHash->{'email'}\nPhone: $employerHash->{'telephone'}\n";
	#print MAIL "http://jobs.hbcuconnect.com/admin/clients.cgi?employer_id=$employerHash->{'employer_id'}\n";
	#print MAIL "$error\n";
	#close(MAIL);
    }
    $sth->finish();

}

sub isAdmin() {
    my ($email) = $_[0];
    if (!$email) { $email = $authorizedEmail; }
    if ($email eq "wrmoss\@hbcu-central.com" ||
	$email eq "phd1974\@hotmail.com" ||
	$email eq "ellemoss\@hotmail.com" ||
	$email eq "parmoss\@yahoo.com" ||
	$email eq "lgwilliams\@hbcuconnect.com" ||
	$email eq "jbunch\@hbcuconnect.com" ||
	$email eq "wrmoss\@hbcuconnect.com" ||
	$email eq "wrmoss\@grandlin.com" ||
        $email eq "ddickson\@hbcuconnect.com" || 
	$email eq "brclark\@hbcuconnect.com"
	) 
 	{ return(1); } 
	else { return(0); }
}


sub printQuickLogin() {
    print qq~
        <script>
        function gothere(selectbox) {
            if (selectbox[selectbox.selectedIndex].value == 3) {
                document.location='http://jobs.hbcuconnect.com/cgi-bin/employerSignup.cgi';
            } else {
                document.location='$CGI_URL/members.cgi';
            }
	}
	function mailpw() {
    	  errors = '';
    	  if ( document.quicksignin.email.value == '') {
    	  errors += 'Please enter your email address and then click on the \\'forgot password?\\' link';
    	  }
    	  if (errors != "") { alert(errors); }
    	  else {
            emailLink = '$CGI_URL/networking/sendEmail.cgi?type=general&email='
            + document.quicksignin.email.value;
            window.open(emailLink,'HBCU','width=400,height=200,menubar=yes,toolbar=no,scrollbars=yes,left=5,top=5,screenX=5,screenY=5');
    	  }
	}
        </script>

            <form name=quicksignin action=$CGI_URL/login.cgi method=post>
            <input type=hidden name=skipsponsor value=1>
            <table width=100% class=buttons>
                  <tr height=35>
                    <td nowrap align=right>Email:</td>
                    <td><input name=email value="" size=15></td>
                    <td align=right>Password:</td>
                    <td><input type=password name=password size=15></td>
		    <td><input type=submit name=submitButton value="Log In!" ></td>
                    <td nowrap>
			<a href="javascript:mailpw()" class=buttons>Forgot Password?</a><br>
			<a href=http://hbcuconnect.com/cookies.shtml class=buttons>Get Help...</a></b>
            </td></form></tr></table>

    ~;
}

###############################################
sub getMember() {
    my ($dbh,$email) = @_;
    my ($sql,$sth,$hash);

    $sql="select *,a.registry_id as rid from registry_data as a
                LEFT JOIN professional_data as b ON a.registry_id=b.registry_id where a.email like ?";
    $sth = $dbh->prepare($sql);
    $sth->execute($email);
    $hash = $sth->fetchrow_hashref();
    return($hash);
}

#########################################################################
sub printLoginPage() {
    my ($error_msg) = @_;
    print $q->header();

    if ($q->param('redirectURL')) { my $redirectstr = "<input type=hidden name=redirectURL value='$redirectURL'>"; }
    print qq~

	<html><title>$SITE</title>
	<link rel=stylesheet href=$CSS_URL type=text/css>

        <script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>
        <script type="text/javascript">
        _uacct = "UA-339199-1";
        urchinTracker();
        </script>

        <script>
	function showhelp() {
            link = '$CGI_URL/networking/sendEmail.cgi?help=1';
            window.open(link,'HBCU','width=400,height=200,menubar=yes,toolbar=no,scrollbars=yes,left=5,top=5,screenX=5,screenY=5');
	}

        function mailpw() {
          errors = '';
          if ( document.loginform.email.value == '') {
          errors += 'Please enter your email address and then click on the \\'forgot password?\\' link';
          }
          if (errors != "") { alert(errors); }
          else {
            emailLink = '$CGI_URL/networking/sendEmail.cgi?type=general&email=' + document.loginform.email.value;
            window.open(emailLink,'HBCU','width=400,height=200,menubar=yes,toolbar=no,scrollbars=yes,left=5,top=5,screenX=5,screenY=5');
          }
        }
        </script>

	<body class=body_class>
	<br><br>
	<br><br>

	<form name=loginform action=$CGI_URL/login.cgi method=post>
            <input type=hidden name=skipsponsor value=1>
	    $redirectstr
	<div align=center>
	<table width=690 style=align:center cellpadding=0 cellspacing=0>
	<tr>
	  <td ><img src="$SITE_LOGO"></td>
	  <td width=80% align=right valign=bottom><font class=error>&nbsp;$error_msg&nbsp;</td>
	</tr>

	<tr><td valign=top colspan=2>

	<table cellspacing=0 class=data style=padding:0; align=left>
	<tr>
	  <td width=280 valign=top bgcolor=white>

		<table width=100%>
		<tr class=even>
		  <td><img width=70 src=$IMAGES/loginpeeps.jpg></td>
		  <td style=font-family:verdana;font-size:10>
		  	"It was so easy finding a job! I just signed up, uploaded my resume and
			was able to browse jobs right away!"
		  </b></td></tr>
		</table>

		$DIVIDER

		<font class=huge_text><b>NOT A MEMBER?</b></font><br>
		<table width=99% style=padding:4 class=odd align=center>
		<tr>
		  <td>
		  <a href=$CGI_URL/members.cgi><img border=0 src="$IMAGES/join_now.gif" align=right></a>
		  Sign up for a <b>FREE</b> membership
		  or <a href=$ROOT_URL>preview</a> the site now!
		  This website is the best way to connect with $COMMUNITY !!!
	  	  </td></tr>
		</table><table width=99%>
		<tr><td>

		  <div align=right>
		  <input type=button name=signup value="Sign Up!"
		  onClick="document.location='$CGI_URL/members.cgi'">
		  </div>
		</td></tr>
		</table>
	  </td>

	  <td width=170 style=padding:0 bgcolor=white>

		  <img width=170 src=$IMAGES/introface.jpg>

	  </td>


	  <td width=250 bgcolor=white valign=top>

		<div align=right>
		<b>312,245</b> Members Connected<br>
		<b>1,147</b> Members Online!
		</div>
		$DIVIDER
		$DIVIDER
		$DIVIDER
		$DIVIDER

		<font class=huge_text><b>ALREADY A MEMBER?</b></font><br>
		<font style=font-family:verdana;font-size:10>
		Please Login. 
		<a href="javascript:showhelp()">Login Trouble?</a>
		<a href="javascript:mailpw()">Forgot Password?</a><br>
		</font>
		<table width=100%>
		<tr>
		 <td nowrap class=odd style=text-align:right><b>EMAIL:</td>
		  <td><input name=email size=19></td>
		</tr>
		<tr>
		  <td class=odd style=text-align:right><b>PASSWORD:</td>
		  <td><input type=password size=19 name=password></td>
		</tr>
		<tr><td></td>
		  <td align=right>
			<input type=submit name=enter value="Login Now!">
			&nbsp;&nbsp;&nbsp;</td>
		</tr>
		</table>
		<script>loginform.email.focus();</script>

	  </td></tr></table>
	</td></tr>
	<tr><td colspan=3 align=right>
	  <a href=http://hbcuconnect.com/advertise.shtml>Advertisers</a> &nbsp;| &nbsp;
	  <a href=$CC_URL/employerMain.cgi>Employers</a>&nbsp;
	</td></tr>
	</table>

	
	</form>

	</div>
	</body>
	</html>
    ~;

}

################################################################################
sub printLogIn {
  printQuickLogin();

print qq~
    <table class=data width=100%>
      <thead>
        <tr>
          <th>$SITE: Access Denied</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            <br>
            You must be logged in to access this feature. Please log in above. I
f you don't have a $SITE account, please signup above and join the community!<br
><br>
          </td>
        </tr>
      </tbody>
    </table>
    <br>
~;
}

sub deleteMember() {
    my $member_id = $_[0];
    my $dbh;

    if (!$dbh) {
	$dbh = &getDBHandle($HBCU_DB);
    }

    if (!$cc_dbh) {
        $cc_dbh = &getDBHandle($CAREER_DB);
    }

    if (isAdmin()) {
        #### Grab email address for tables that do not use registry_id
        $email_sql = "SELECT email from registry_data where registry_id=?";
        $sth = $dbh->prepare($email_sql);
        $sth->execute($member_id);

        while($hash = $sth->fetchrow_hashref())
        {
           $member_email = $hash->{'email'};
        }

	#### Delete from registry_data
	$sth = $dbh->prepare("DELETE FROM registry_data where registry_id=?");
	$sth->execute($member_id);

	#### Delete from fun_data
	$sth = $dbh->prepare("DELETE FROM fun_data where registry_id=?");
	$sth->execute($member_id);

	#### Delete from professional_data
	$sth = $dbh->prepare("DELETE FROM professional_data where registry_id=?");
	$sth->execute($member_id);

        #### Delete from job_notifications in career center
        $sth = $cc_dbh->prepare("DELETE FROM job_notifications where email=?");
        $sth->execute($member_email);

        #### Delete from resume_data
        $sth = $dbh->prepare("DELETE FROM resume_data where resume_email=?");
        $sth->execute($member_email);

	#### Delete from guestbook
	$sth = $dbh->prepare("DELETE FROM guestbook where to_id=? or from_id=?");
	$sth->execute($member_id,$member_id);

	#### hbcu_love_messages
	$sth = $dbh->prepare("DELETE FROM hbcu_love_messages where to_id=? or from_id=?");
	$sth->execute($member_id,$member_id);

	#### Delete from recruit_data
	$sth = $dbh->prepare("DELETE FROM recruit_data where registry_id=?");
	$sth->execute($member_id);

	return(1);

    } else {
	return(0);
    }

}


##################################################################################
sub autoPoker() {
    my $member = $_[0];
    my $hash;

    #### People that complain about auto poke, put them on this comma separated list
    $no_poke = 'vegasgyrl1@yahoo.com,adriennea01@roadrunner.com,b_cherry1978@yahoo.com,CVHarris@Hotmail.com,Mack_Jackson@mjsg.com,Cheyneygrad01@aol.com,zetaphibeta@hotmail.com,jakaecrawford@aol.com,sharnik@msn.com,Mack_Jackson@mjsg.com,';
    if ($no_poke =~ /$member->{email}/i) { return(0); }

    #### Based on the passed in member, poke 10 other random members
    #### the members that get poked should be opposite sex born the same year
    #### Opposite sex and (same birth year +/- 2, and visitor has photo_link)
    if ($member->{photo_link} && $member->{approved}) {
        if ($member->{title} eq "Mr.") { $opposite = "Ms."; } else { $opposite = "Mr."; }
        my $sql = "select first_name,email from registry_data
            where title like ? and (year(birth_date) >= (year(?)-2) or year(birth_date)<=(year(?)+2))
		and signup_site like 'hbcuconnect.com'
            order by rand()
            limit 0,12";
        my $sth = $dbh->prepare($sql);
        $sth->execute($opposite,$member->{birth_date},$member->{birth_date});

        #### email each person quickly
        while ($hash = $sth->fetchrow_hashref) {

        #### For people who do not want to receive any pokes ########
        $no_poke2= 'Mack_Jackson@mjsg.com,krush1911@hotmail.com,';

        if ($no_poke2 =~ /$hash->{email}/i) { return(0); }

            $message = qq~
Hey $hash->{first_name},
        
You just got "Poked" on HBCUConnect.com...
To view the profile of the member that "Poked" you, visit:
http://hbcuconnect.com/core/cgi-bin/show_member.cgi?registry_id=$member->{registry_id}

HBCU Connect Staff
www.HBCUConnect.com
~;

            notify($hash->{email},'news@hbcuconnect.com',"$hash->{first_name} - You just got poked!",$message);
            #$admin_message .= "Emailing $hash->{email} , $hash->{first_name} \n\n$message";
        }
        #notify('wrmoss@hbcuconnect.com','news@hbcuconnect.com',"Auto Poker Triggered...",$admin_message);
    }
}






1;
