#!/usr/bin/perl

## change-email.pl
## email update script for the WeBWorK project

####################################################################
# Copyright @ 1995-1998 University of Rochester
# All Rights Reserved
####################################################################


require 5.001;
use strict;
use lib '/ww/webwork/development/'; # mainWeBWorKDirectory;

use Global;
use Auth;
use CGI qw(:standard);
use Net::SMTP;

my $scriptDirectory   = getWebworkScriptDirectory();

my $User    = param('user')    || &error_form('No user', 'No user name specified.');
my $Key     = param('key')     || &error_form('No key', 'No session key specified.');
my $Course  = param('course')  || &error_form('No course', 'No course specified.');

&Global::getCourseEnvironment($Course);

my $Passwd_file = &getCoursePasswordFile($Course);
&Global::error("", "Can't read $Passwd_file") unless (-r $Passwd_file);

my $Key_file    = &getCourseKeyFile($Course);
&Global::error("", "Can't read $Key_file") unless (-r $Key_file);

## make sure user's already been authenticated
&verify_key($User, $Key, $Key_file, $Course);

## exit if practice user
if ($User =~ /^$Global::practiceUser/) {
	wwerror('Operation not allowed', "practice users are not allowed to change email addresses.\nPlease go back and select: Begin Problem Set.");
}

require "${scriptDirectory}$Global::HTMLglue_pl";
require "${scriptDirectory}$Global::classlist_DBglue_pl";
require "${scriptDirectory}$Global::FILE_pl";


my $databaseDirectory = $Global::databaseDirectory;

## If this is the firstTime the script is called, print a blank form else
## change the email address.  This allows empty email addresses

my $firstTime = param('firstTime');
my $newEmailAdd ='';
my $oldEmailAdd ='';
$newEmailAdd = param('newEmailAdd') if defined param('newEmailAdd');
$oldEmailAdd = param('oldEmailAdd') if defined param('oldEmailAdd');

#my $classlistFile           = getCourseClasslistFile($Course);
$newEmailAdd =~ s/\s//g; ##remove spaces
wwerror('Illegal email address', 'Your email address has not been changed.') unless
 ($newEmailAdd =~ /^[\w\.\@]*$/ );

# if this is the first call print the form
if ($firstTime eq 'firstTime') {
	&change_em_form;
}

# otherwise we should change the email address {
elsif ($firstTime eq 'cemadd') {
	&change_em_add ($User,$oldEmailAdd ,$newEmailAdd);
	success_form  ($newEmailAdd);
}

else {
	wwerror($0,'The script did not receive the proper input data.','','');
}

## end of main script

sub change_em_form {
	my $course = shift;
	$oldEmailAdd = &findEmailAdd($User);
	param('firstTime','cemadd');  ##change hidden parameter

	print &htmlTOP('Change Email Address Page', $Global::background_plain_url),
	  hr,
	  h1('Change Email Address Page'),
	  start_form('POST', url),
	  "Please enter (or edit) the email address for your ", b($Course),
	  " account, ", b($User), ".<BR>",
	  "Be careful.  If you enter an incorrect email address, you may miss receiving important information.",

	  p,
	  textfield('newEmailAdd', "$oldEmailAdd", 40), " Email Address", br,
	  p,
	  submit('Set your new email address'),
	  hidden('user'),
	  hidden('key'),
	  hidden('course'),
	  hidden('firstTime'),
	  hidden('oldEmailAdd',"$oldEmailAdd"),
	  end_form, end_html;
}


sub success_form {
	 my ($newEmailAdd) = @_;
	 print &htmlTOP('Email Address Changed', $Global::background_okay_url),
	  hr,
	  h1('Email Address Changed'),
	  "Your new email address for ", b($Course), " has been changed to <BR> $newEmailAdd",
	  p,
	  "Email messages confirming this change will be sent both to your new and old email address
	  (if they are not blank).  If you don't receive the confirming message at your new email address,
	  it means there may be a problem with the new address you entered.",
	  p,
	  start_form('POST', "${Global::cgiWebworkURL}login.pl"),
	  p,"\n",
	  hidden('course'), "\n", hidden('user'), "\n", hidden('key'),
	  submit('Continue'),
	  end_form, end_html;
}


sub findEmailAdd {
	my ($User) = @_;
	attachCLRecord($User);
	my $email_address	= CL_getStudentEmailAddress($User);

	return  $email_address;
}

sub change_em_add {
	my ($User,$oldEmailAdd ,$newEmailAdd) = @_;

	attachCLRecord($User);
	my $lastName		= CL_getStudentLastName($User);
	my $firstName		= CL_getStudentFirstName($User);

	CL_putStudentEmailAddress($newEmailAdd,$User);
	saveCLRecord($User);

	## send confirming email messages to the old and new addresses
	if ($oldEmailAdd =~ /\S/) {
		my $msg = emailMsg($oldEmailAdd, $lastName, $firstName, $newEmailAdd, $oldEmailAdd);

		my $smtp = Net::SMTP->new($Global::smtpServer, Timeout=>20);
		$smtp->mail($Global::webmaster);
		if ($smtp->recipient($oldEmailAdd)) {
			$smtp->data($msg);
		} else {die "$oldEmailAdd";}

		$smtp->quit;

#        open (MAIL,"|$Global::SENDMAIL");
#        print MAIL "$msg";
#        close (MAIL);
	}
	if ($newEmailAdd =~ /\S/) {
		my $msg = emailMsg($newEmailAdd, $lastName, $firstName, $newEmailAdd, $oldEmailAdd);

		my $smtp = Net::SMTP->new($Global::smtpServer, Timeout=>20);
		$smtp->mail($Global::webmaster);
		$smtp->recipient($newEmailAdd);
		$smtp->data($msg);
		$smtp->quit;


#        open (MAIL,"|$Global::SENDMAIL");
#        print MAIL "$msg";
#        close (MAIL);
	}
}

sub emailMsg {
	my ($emailAdd, $lastName, $firstName, $newEmailAdd, $oldEmailAdd) = @_;
	my $msg ='';
	my $fromAdd = $Global::feedbackAddress;
    $fromAdd = $Global::feedbackAddress;
	$msg = "To: $emailAdd
From: $fromAdd
Subject: Email address changed

Dear $firstName $lastName,

	Your email address for $Course has been changed from:
$oldEmailAdd
to
$newEmailAdd

	You should receive two email messages confirming this change.
One is being sent to your old email address and the other to your
new email address.

	If either one of these email addresses is blank or invalid,
obviously you will not receive the message sent to that address.\n";

$msg;
}
