#!/usr/local/bin/webwork-perl

## This file is profSendMail.pl
## It provides a utility for professors to send mail to one or more students
## using individualized emails or mass emails

use lib '.'; use webworkInit; # WeBWorKInitLine

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

#begin Timing code
use Benchmark;
my $beginTime = new Benchmark;
#end Timing code

my $cgi = new CGI;
my %inputs = $cgi->Vars();

#for use in strings where $cgi->param is not interpolated correctly or at all
my $course = $cgi->param('course');
my $user = $cgi->param('user');
my $session_key = $cgi->param('key');
my $openfilename = $cgi->param('openfilename');

&Global::getCourseEnvironment($course);

my $scriptDirectory			= $Global::scriptDirectory;
my $databaseDirectory		= $Global::databaseDirectory;
my $htmlURL					= $Global::htmlURL;
my $cgiURL					= $Global::cgiWebworkURL;
my $courseScriptsDirectory	= $Global::courseScriptsDirectory;
my $templateDirectory		= getCourseTemplateDirectory;
my $emailDirectory			= getCourseEmailDirectory;
my $scoringDirectory		= getCourseScoringDirectory;
my $feedbackAddress			= $Global::feedbackAddress;
my $defaultFrom				= $Global::defaultFrom;
my $defaultReply			= $Global::defaultReply;
my $smtpSender				= $Global::smtpSender;
my $defaultClasslistFile	= getCourseClasslistFile($course);
my $default_msg				= 'default.msg';
my $old_default_msg			= 'default_old.msg';
require "${scriptDirectory}$Global::FILE_pl";

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

# log access
&Global::log_info('', query_string);

my $permissionsFile = &Global::getCoursePermissionsFile($course);
my $permissions = &get_permissions($user, $permissionsFile);
my $keyFile = &Global::getCourseKeyFile($course);


#verify session key
&verify_key($user, $session_key, "$keyFile", $course);

#verify permissions are correct
if (($permissions != $Global::instructor_permissions) and ($permissions != $Global::TA_permissions) ) {
	print "permissions = $permissions instructor_permissions = $Global::instructor_permissions\n";
	print &html_NO_PERMISSION;
	exit(0);
	}

#user macros that can be used in the email message
my $SID = '';
my $FN = '';
my $LN = '';
my $SECTION = '';
my $RECITATION = '';
my $STATUS = '';
my $EMAIL = '';
my $LOGIN = '';
my @COL = ();

my $endCol;

#hashes to hold student info
my %fn = ();
my %ln = ();
my %section = ();
my %recitation = ();
my %status = ();
my %email = ();
my %login = ();

# get format information

my $format = (defined($cgi->param('format'))) ? $cgi->param('format') : 'alph';

#get information from the classlist data base
my $availableStudents_ref;
if ((defined $format) and ($format eq 'section')) {
		$availableStudents_ref = getAllLoginNamesSortedBySectionThenByName();
}
elsif ((defined $format) and ($format eq 'recitation')) {
		$availableStudents_ref = getAllLoginNamesSortedByRecitationThenByName();
}
else {
		$availableStudents_ref = getAllLoginNamesSortedByName();
}

my @availableStudents = @$availableStudents_ref;

#my %loginName_StudentID_Hash 	= %{getLoginName_StudentID_Hash()};
my %studentID_LoginName_Hash 	= %{getStudentID_LoginName_Hash()};



#make sure message file was submitted and exists
	my $messageFileName;
	if (defined($openfilename) && -e "${emailDirectory}$openfilename") {
		if ( -R "${emailDirectory}$openfilename") {
			$messageFileName = $openfilename;
		} else {
			wwerror ('File is not readable', "The file
${emailDirectory}$openfilename
is not readable by the webserver. Check that it's permissions are set correctly.");
		}
	} else {
		$messageFileName = $default_msg;
	}


#get row and column info if submitted
	my $rows = (defined($cgi->param('rows'))) ? $cgi->param('rows') : $Global::editor_window_rows;
	my $columns = (defined($cgi->param('columns'))) ? $cgi->param('columns') : $Global::editor_window_columns;

#Deal with filled out forms and various actions resulting from different buttons
	if ( defined($cgi->param('action')) ) {
		if (defined($cgi->param('savefilename'))) {
			&user_error("For security reasons, you cannot save a message in any directory higher than the email directory.  Please specify a   file name to save under.") if ($cgi->param('savefilename') =~ /^[~.]/ || $cgi->param('savefilename') =~ /\.\./);
		}

		#if Save button was clicked
		if (( $cgi->param('action') eq 'Save') && defined($cgi->param('body')) && defined($cgi->param('savefilename'))) {

			my $temp_body = $cgi->param('body');
			$temp_body =~ s/\r\n/\n/g;
			$temp_body = "From: " . $cgi->param('from') . "\n" .
					   "Reply-To: " . $cgi->param('replyTo') . "\n" .
					   "Subject: " . $cgi->param('subject') . "\n" .
					   "Message: \n" . $temp_body;

			saveProblem($temp_body, $cgi->param('savefilename'));
			$messageFileName = $cgi->param('savefilename');

		#if Save As button was clicked
		} elsif (( $cgi->param('action') eq 'Save as') && defined($cgi->param('body')) && defined($cgi->param('savefilename'))) {

			$messageFileName = $cgi->param('savefilename');

			if ($messageFileName =~ /^[~.]/ || $messageFileName =~ /\.\./) {
				&user_error("For security reasons, you cannot specify a merge file from a directory higher than the email directory (you can't use ../blah/blah).  Please specify a different file or move the needed file to the email directory");
			}


			my $temp_body = $cgi->param('body');
			$temp_body =~ s/\r\n/\n/g;
			$temp_body = "From: " . $cgi->param('from') . "\n" .
					   "Reply-To: " . $cgi->param('replyTo') . "\n" .
					   "Subject: " . $cgi->param('subject') . "\n" .
					   "Message: \n" . $temp_body;

			saveNewProblem($temp_body, $messageFileName);

		#if Save As Default button was clicked
		} elsif (( $cgi->param('action') eq 'Save as Default') && defined($cgi->param('body'))) {

			my $temp_body;
			$temp_body = $cgi->param('body');
			$temp_body =~ s/\r\n/\n/g;

			#get default.msg and back it up in default.old.msg
			open DEFAULT, "$emailDirectory$default_msg";
				$temp_body = <DEFAULT>;
			close DEFAULT;

			if ( -e "$emailDirectory$old_default_msg") {
				saveProblem($temp_body, $old_default_msg);
			} else {
				saveNewProblem($temp_body, $old_default_msg);
			}

			#save new default message as default.msg
			$temp_body = $cgi->param('body');
			$temp_body =~ s/\r\n/\n/g;
			$temp_body = "From: " . $cgi->param('from') . "\n" .
					   "Reply-To: " . $cgi->param('replyTo') . "\n" .
					   "Subject: " . $cgi->param('subject') . "\n" .
					   "Message: \n" . $temp_body;

			saveProblem($temp_body, $default_msg);
			$messageFileName = $default_msg;

		#if Send Email button was clicked
		} elsif ( $cgi->param('action') eq 'Send Email' ) {

			my @studentID = ();

			if ($cgi->param('To') eq 'classList' && defined($cgi->param('classList')) && $cgi->param('classList') ne 'None') {
				my $classlist = $cgi->param('classList');
				my $classListFile = "$templateDirectory$classlist";
				my @classList = ();
				checkClasslistFile($Global::noOfFieldsInClasslist,$classListFile);
				open(FILE, "$classListFile") || die "can't open $classListFile";
				@classList=<FILE>;
				close(FILE);

				foreach (@classList)   {                        ## read through classlist and send e-mail
                                                       ## message to all active students
    				unless ($_ =~ /\S/)  {next;}                    ## skip blank lines
    				chomp;
    				my @classListRecord=&getRecord($_);
    				my ($studentID, $lastName, $firstName, $status, $comment,  $section, $recitation, $email_address, $login_name)
       				  = @classListRecord;
    				unless (&dropStatus($status)) {
    					push (@studentID, $studentID);
    					$fn{$studentID} = $firstName;
						$ln{$studentID} = $lastName;
						$section{$studentID} = $section;
						$recitation{$studentID} = $recitation;
						$status{$studentID} = $status;
						$email{$studentID} = $email_address;
						$login{$studentID} = $login_name;
    				}
				}
			}
			elsif ($cgi->param('To') eq 'studentID' && defined($cgi->param('studentID'))) {
				@studentID = $cgi->param('studentID');
				my ($studentID, $login_name);

				foreach $studentID (@studentID) {
					$login_name = $studentID_LoginName_Hash{$studentID};
					&attachCLRecord($login_name);
					$fn{$studentID}			= CL_getStudentFirstName($login_name);
					$ln{$studentID}			= CL_getStudentLastName($login_name);
					$section{$studentID}	= CL_getClassSection($login_name);
					$recitation{$studentID}	= CL_getClassRecitation($login_name);
					$status{$studentID} 	= CL_getStudentStatus($login_name);
					$email{$studentID}		= CL_getStudentEmailAddress($login_name);
					$login{$studentID} 		= $login_name;
				}

			}
			elsif ($cgi->param('To') eq 'all_students') {
				@studentID = ();
				my ($studentID, $login_name, $status);

				foreach $login_name (@availableStudents) {
					&attachCLRecord($login_name);
					$status 		= CL_getStudentStatus($login_name);
					next if &dropStatus($status);
					$studentID		= CL_getStudentID($login_name);
					push(@studentID,$studentID);

					$fn{$studentID}			= CL_getStudentFirstName($login_name);
					$ln{$studentID}			= CL_getStudentLastName($login_name);
					$section{$studentID}	= CL_getClassSection($login_name);
					$recitation{$studentID}	= CL_getClassRecitation($login_name);
					$status{$studentID} 	= CL_getStudentStatus($login_name);
					$email{$studentID}		= CL_getStudentEmailAddress($login_name);
					$login{$studentID} 		= $login_name;
				}
			}
			else {
				&user_error('You didn\'t select any recipients.  Make sure you select either all student in the course, individual students or a whole classlist.');
			}

			my $mergeFile = '';

			#the radio button named 'merge' determines whether to take the selected mergefile
			#or one that was typed in.  A error message is given if select one and use the other
			$mergeFile = $scoringDirectory . $cgi->param('mergeFiles')
				if ($cgi->param('merge') eq 'mergeFiles' && defined($cgi->param('mergeFiles')) && $cgi->param('mergeFiles') ne 'None');

			$mergeFile = $templateDirectory . $cgi->param('mergeFile')
				if ($cgi->param('merge') eq 'mergeFile' && defined($cgi->param('mergeFile')) && $cgi->param('mergeFile') !~ m|/$|); #does not end in a /

			if ($mergeFile =~ /^[~.]/ || $mergeFile =~ /\.\./) {
				&user_error("For security reasons, you cannot specify a merge file from a directory higher than the email directory.  Please specify a different file or move the needed file to the email directory");
			}
			if ($cgi->param('body') =~ /(\$COL\[.*?\])/ && !(-e $mergeFile)) {
				&user_error("In order to use the \$COL[] you must specify a merge file. The file you specified does not exist.  Also, make sure you selected the right checkbox.");
			}


			my %mergeAArray = ();
			unless ($mergeFile eq '') {%mergeAArray = &delim2aa($mergeFile);}

			foreach  my $studentID (@studentID) {
				unless ((defined $mergeAArray{$studentID}) or ($mergeFile eq '')) {
					next if $cgi->param('no_record');
				}	
				@COL =();
				$SID = $studentID;
				$LN = defined $ln{$studentID} ? $ln{$studentID} :'';
				$FN = defined $fn{$studentID} ? $fn{$studentID} :'';
				$SECTION = defined $section{$studentID} ? $section{$studentID} :'';
				$RECITATION = defined $recitation{$studentID} ? $recitation{$studentID} :'';
				$EMAIL = defined $email{$studentID} ? $email{$studentID} :'';
				$STATUS =defined $status{$studentID} ?  $status{$studentID} :'';
				$LOGIN = $login{$studentID};

				my ($dbString, @dbArray);
				if (defined $mergeAArray{$SID}) {
					$dbString = $mergeAArray{$SID};	## get sid record from merge file
					@dbArray = &getRecord($dbString);
					unshift(@dbArray,$SID);
					unshift(@dbArray,"");			## note COL[1] is the first column
					@COL= @dbArray;				## put merge fields in COL array
					$endCol = @COL;				## \endCol-1 gives last field, etc
				}

				&user_error('You didn\'t enter any message.') if ($cgi->param('body') eq '');

				my $smtp = Net::SMTP->new($Global::smtpServer, Timeout=>10) || &internal_error("Couldn't contact SMTP server.");
				$smtp->mail($smtpSender);

				if ( $smtp->recipient($EMAIL)) {  # this one's okay, keep going
					$smtp->data(output() ) ||
					&internal_error("Unknown problem sending message data to SMTP server.");
				} else {			# we have a problem a problem with this address
					$smtp->reset;
					&internal_error("SMTP server doesn't like this address: <$EMAIL>.");
				}
				$smtp->quit;
			}
			&success;
		}
	}



#Begin Page
	print &htmlTOP("Send Mail for " . $course),
		$cgi->a( { -href=>"${cgiURL}login.pl?user=$user&key=$session_key&course=$course" },

			$cgi->img({ -name=>'upImg',
					  -src=>"${Global::upImgUrl}",
					  -align=>'right',
					  -border=>'1',
					  -alt=>'[Up]'
					})
			),
	$cgi->p;

	print "\n",
	 $cgi->hr, $cgi->br,
	 "\n\n", $cgi->h3({ -align=>'left' }, "WeBWorK Send Mail Page for $course"), "\n",
	 $cgi->p,
	 "From this page, you can send email to students.  You can opt to send email to only specific
	 students or to entire groups of students based on classlists that can be created from the
	 professor's page.  Any email can contain various macros to refer to information specific to
	 each student.  In particular, a merge file can be specified so that outside information, such
	 as students grades can be placed in an email.  This is most easily done by selecting the file
	 titled ${course}_totals.csv from the drop down list.  The information in this file is
	 obtained by specifying \$COL[n] with the number in the brackets indicating the data item from
	 the nth column of the merge file or, if n is negative, the nth column from the last column.
	 (e.g. \$COL[3] is the third column and \$COL[-2] is the <U>second</U> to last column in the merge file.
	 Messages can be saved and retrieved for later use.  Save as Default will cause the current message
	 to be the one that is loadedd when first coming to this page.  (The old default message will be
	 saved as default.old so that the last default can be restored manually by changing its name to
	 default.msg)",
	 $cgi->hr, "\n";


my %labels =();
$labels{alph} = 'Alphabetically';
$labels{section} = 'by section';
$labels{recitation} = 'by recitation';

# start form with hidden entries to pass info back to profSendMail.pl
	print $cgi->startform(-action=>"${cgiURL}profSendMail.pl"), "\n",
		 $cgi->hidden(-name=>"user", -value=>$user), "\n",
		 $cgi->hidden(-name=>"key", -value=>$session_key), "\n",
		 $cgi->hidden(-name=>"course", -value=>$course), "\n",
		 $cgi->hidden(-name=>"filename", -value=>$openfilename), "\n";

# # get all student emails and create a list
	print $cgi->p, $cgi->b('Send Email To: '), "\n", $cgi->br,
		 $cgi->input({-type=>'radio', -name=>'To', -value=>'all_students'}), " \n",
		 "Send e-mail to all current students in $course",
		$cgi->br, "or",$cgi->br;
	print  $cgi->input({-type=>'radio', -name=>'To', -value=>'studentID'}), " \n",
		 "Send e-mail to individual students (select as many as you like)<BR>";


	my ($lastName, $firstName, $studentID, $login_name, $section, $recitation, $label, $status, @all_sids, %fullnames, );
	@all_sids = ();
	foreach $login_name (@availableStudents) {
		&attachCLRecord($login_name);
		$status 		= CL_getStudentStatus($login_name);
		next if &dropStatus($status);
		$lastName		= CL_getStudentLastName($login_name);
		$firstName		= CL_getStudentFirstName($login_name);
		$studentID		= CL_getStudentID($login_name);
		$section		= CL_getClassSection($login_name);
		$recitation		= CL_getClassRecitation($login_name);

		if ($format eq 'section') {
		$label = ", $section";
		}
		elsif ($format eq 'recitation') {
		$label = ", $recitation";
		}
		else {
		$label = '';
		}
		$label = "$lastName, $firstName, $studentID, $login_name". $label;
		push (@all_sids, $studentID); #array for values of popup_menu
		$fullnames{$studentID} = $label;
	}

	print $cgi->popup_menu(-name=>'studentID',
					   -size=>'5',
					   -multiple=>undef,
					   -values=>\@all_sids,
					   -labels=>\%fullnames),
 		 "\n",
 	$cgi->br,
	"Order students \n",
	$cgi->radio_group(
		-name=>'format',
		-values=>['alph','section','recitation'],
		-default=>'alph',
		-labels=>\%labels
	),
	$cgi->br,
	$cgi->submit(-value=>'Reorder list now'),
		$cgi->br, "or",$cgi->br;

	print $cgi->input({-type=>'radio', -name=>'To', -value=>'classList'}), " \n",
		 "Select a classlist to send a message to: \n", $cgi->br,
		 "(Classlist files can be created from the Professor's Page)\n", $cgi->br;


# get all classlist files
#
#	opendir CLASSLISTDIR, $templateDirectory; # or wwerror($0, "Can't open directory $templateDirectory","","");
#		my @allFiles = grep !/^\./, readdir CLASSLISTDIR;
#	closedir CLASSLISTDIR;
#
#	my @classlistFiles = grep /\.lst$/, @allFiles; #all classlist files
#	my @sortedNames = sort @classlistFiles;
#
#	my $shortFileName = $defaultClasslistFile;
#
#	if ($shortFileName =~ m|/| ) {
#		$shortFileName =~ m|/([^/]*)$|; ## extract filename from full path name
#		$shortFileName = $1;
#	}
#
#	my @newSortedNames = grep !/^$shortFileName$/, @sortedNames;
#
#	if ($#newSortedNames != $#sortedNames) {
#		unshift @newSortedNames, $shortFileName;
#		@sortedNames = @newSortedNames;
#	}
	my ($ar_sortedNames, $hr_classlistLabels) = getClasslistFilesAndLabels($course);
	my @sortedNames = @$ar_sortedNames;
	my %classlistLabels = %$hr_classlistLabels;
	unshift(@sortedNames, "None");
	$classlistLabels{None} = 'None';

#create list of classlists
	print $cgi->popup_menu(-name=>'classList',
					   -values=>\@sortedNames,
					   -labels=>\%classlistLabels,
					   -default=>'None');

print $cgi->hr, $cgi->p, $cgi->b('Enter Message: '), "\n", $cgi->br;
#get message from given messageFileName
	my ($text, @text);
	my $header = '';
	my ($subject, $from, $replyTo);
	if (-e "$emailDirectory$messageFileName") {
	 	open FILE, "$emailDirectory$messageFileName";
		while ($header !~ s/Message:\s*$//m) { $header .= <FILE>; }
		$text = join '', <FILE>;
		$header =~ /^From:\s(.*)$/m;
		$from = $1 or $from = $defaultFrom; #given email address or default feedback address
		$header =~ /^Reply-To:\s(.*)$/m;
		$replyTo = $1 or $replyTo = $defaultReply;
		$header =~ /^Subject:\s(.*)$/m;
		$subject = $1;

	} else {
		# wwerror($0, "Message File $emailDirectory$messageFileName does not exist!");
	}

# show professors's name and email address
	print "\n", $cgi->p, $cgi->b('From:     '), $cgi->textfield(-name=>"from", -size=>40, -value=>$from, -override=>1),
		 "\n", $cgi->p, $cgi->b('Reply-To: '), $cgi->textfield(-name=>"replyTo", -size=>40, -value=>$replyTo, -override=>1);
		 
#create a textbox with the subject and a textarea with the message

	print "\n", $cgi->p, $cgi->b('Subject:  '), $cgi->textfield(-name=>'subject', -default=>$subject, -size=>40, -override=>1),
		$cgi->p,
		"\n", $cgi->p, $cgi->b('Message: ');

#show available macros
	print $cgi->br, $cgi->popup_menu(
						-name=>'dummyName',
						-values=>['', '$SID', '$FN', '$LN', '$SECTION', '$RECITATION','$STATUS', '$EMAIL', '$LOGIN', '$COL[3]', '$COL[-1]'],
						-labels=>{''=>'These macros can be used to insert student specific data:',
							'$SID'=>'$SID - Student ID',
							'$FN'=>'$FN - First name',
							'$LN'=>'$LN - Last name',
							'$SECTION'=>'$SECTION - Student\'s Section',
							'$RECITATION'=>'$RECITATION - Student\'s Recitation',
							'$STATUS'=>'$STATUS - C, Audit, Drop, etc.',
							'$EMAIL'=>'$EMAIL - Email address',
							'$LOGIN'=>'$LOGIN - Login',
							'$COL[3]'=>'$COL[3] - Third column in merge file',
							'$COL[-1]'=>'$COL[-1] - Last column in merge file'
							}
									), "\n";

	opendir SCORINGDIR, $scoringDirectory; # or wwerror($0, "Can't open directory $scoringDirectory","","");
	my @allFiles = grep !/^\./, readdir SCORINGDIR;
	closedir SCORINGDIR;

	my @mergeFiles = grep /\.csv$/, @allFiles; #all classlist files
	@sortedNames = sort @mergeFiles;
	unshift(@sortedNames, "None");

#print a merge file popup list
	print $cgi->br, "\nSelect a merge file: ",
		 $cgi->input({-type=>'radio', -name=>'merge', -value=>'mergeFiles', -checked=>undef}), ' ',
		 $cgi->popup_menu(-name=>'mergeFiles',
					   -values=>\@sortedNames,
					   -default=>"None"),
		 "or type in your own &nbsp;";

	my $shortDirectory = $emailDirectory;
	$shortDirectory =~ s|.*/(\w*/)$|$1|;
#and a textbox to type in your own merge file
	print $cgi->input({-type=>'radio', -name=>'merge', -value=>'mergeFile'}), ' ',
		 $cgi->textfield(-name=>'mergeFile',
		 			  -value=>$shortDirectory);
	print "\n", $cgi->br, $cgi->input({-type=>'checkbox', -name=>'no_record', -value=>1, }),
	'Do not send email if there is no record in merge file.',$cgi->br;

#print actual body of message
	print "\n", $cgi->br, $cgi->textarea(-name=>'body', -default=>$text, -rows=>$rows, -columns=>$columns, -override=>1);


#get all message files and create a list
	opendir EMAILDIR, $emailDirectory; # or wwerror($0, "Can't open directory $emailDirectory","","");
		my @messageFiles = grep /\.msg$/, readdir EMAILDIR; #all message files
	closedir EMAILDIR;

	my @sortedMessages = sort @messageFiles;

	print $cgi->p, $cgi->popup_menu(-name=>'openfilename', -values=>\@sortedMessages, -default=>$messageFileName);


#create all necessary action buttons
	print $cgi->submit(-name=>'action', -value=>'Open'), "\n", $cgi->br,
		 $cgi->textfield(-name=>'savefilename', -size => 20, -value=> "$messageFileName", -override=>1), ' ',
		 $cgi->submit(-name=>'action', -value=>'Save'), " \n",
		 $cgi->submit(-name=>'action', -value=>'Save as'), " \n",
		 $cgi->submit(-name=>'action', -value=>'Save as Default'), "\n", $cgi->br,
		 'For "Save As" choose a new filename.', $cgi->br, $cgi->br,
		 $cgi->submit(-name=>'action', -value=>'Send Email'), "\n",
		 $cgi->p, $cgi->submit(-name=>'action', -value=>'Revert to original and Resize message window'),
		 " Rows: ", $cgi->textfield(-name=>'rows', -size=>3, -value=>$rows),
		 " Columns: ", $cgi->textfield(-name=>'columns', -size=>3, -value=>$columns),
		 $cgi->br, "If you resize the message window, you will lose all unsaved changes.",
		 $cgi->end_form,
		 &htmlBOTTOM("profSendMail", \%inputs, 'profSendMailHelp.html');

# End of HTML


###### SUBROUTINES ######
sub saveProblem {
	my ($body, $probFileName)= @_;

	open (PROBLEM, ">${emailDirectory}$probFileName") ||
		wwerror($0, "Could not open ${emailDirectory}$probFileName for writing.
		Check that the  permissions for this problem are 660 (-rw-rw----)");
	print PROBLEM $body;
	close PROBLEM;
	chmod 0660, "${emailDirectory}${probFileName}" ||
	             print "Content-type: text/html\n\n
	                    CAN'T CHANGE PERMISSIONS ON FILE ${templateDirectory}${probFileName}";

}

sub saveNewProblem {
	my ($body, $new_file_name)= @_;
 #######check that the new file name doesn't exist
	if (-e "${emailDirectory}$new_file_name" ) {
		wwerror("Can not use this file name", "The file\n".
		"${emailDirectory}$new_file_name\n".
		"already exists.\n" .
		"<b>The new version was not saved.</b>\n" .
		"Go back and choose a different file name or\, if you really want to edit\n".
		"${templateDirectory}$new_file_name\,\n".
		"go back and hit the \&quot;Save updated version\&quot; button.");
	}

	wwerror ("Invalid file name", "The file name \"$new_file_name\" does not have a \".msg\" extension.
All email file names must end in the extension \".msg\"
<b>The file was not saved.</b>
Go back and choose a file name with a \".msg\" extension.") unless
		$new_file_name =~ m|\.msg$|;
 #######copy new version to the file new_file_name
	open (PROBLEM, ">${emailDirectory}$new_file_name") ||
		wwerror($0, "Could not open ${emailDirectory}$new_file_name for writing.
		Check that the  permissions for the directory ${emailDirectory} are 770 (drwxrwx---)");
	print PROBLEM $body;
	close PROBLEM;
	chmod 0660, "${emailDirectory}$new_file_name" ||
	             print "Content-type: text/html\n\n
	                    CAN'T CHANGE PERMISSIONS ON FILE ${emailDirectory}$new_file_name";

}

sub internal_error {
    my $msg = join " ", @_;
    print $cgi->header,
    	$cgi->start_html('-title' => "Internal Error"),
	$cgi->h1('Internal Error'),
	$cgi->b(HTML::Entities::encode($msg)),
	$cgi->p,
	"Your message could not be sent.  Please notify ",
	"&lt;", $cgi->a({href=>"mailto:$Global::webmaster"}, $Global::webmaster), "&gt;. ",
	$cgi->br,
	"We apologize for the inconvenience.",
	$cgi->end_html;
    exit(1);
}

sub user_error {
    my $msg = join " ", @_;
    print $cgi->header,
	$cgi->start_html('-title' => 'User error'),
	$cgi->h1('User error'),
	$cgi->p,
	$cgi->b(HTML::Entities::encode($msg)),
	$cgi->p,
        "Please hit the &quot;<B>Back</B>&quot; button on your browser to ",
	"try again, or notify ", $cgi->br,
	"&lt;", $cgi->a({href=>"mailto:$Global::webmaster"}, $Global::webmaster), "&gt; ",
	"if you believe this message is in error.",
	$cgi->end_html;
    exit(1);
}

sub check_destination {
    my($address_list) = @_;

    my (@address) = split(/\+*,\+*/, $address_list);
    for (@address) {
       &internal_error("Sorry, I'm not allowed to send mail to <$_>.")
           if !/$Global::legalAddress/;
    }
}

sub output {
	my ($msg, $body, $tmp);

	$body = $cgi->param('body');

	$tmp = $body;
	$tmp =~ s/(\$SID)/eval($1)/ge;
	$tmp =~ s/(\$LN)/eval($1)/ge;
	$tmp =~ s/(\$FN)/eval($1)/ge;
	$tmp =~ s/(\$STATUS)/eval($1)/ge;
	$tmp =~ s/(\$SECTION)/eval($1)/ge;
	$tmp =~ s/(\$RECITATION)/eval($1)/ge;
	$tmp =~ s/(\$EMAIL)/eval($1)/ge;
	$tmp =~ s/(\$LOGIN)/eval($1)/ge;
	$tmp =~ s/\$COL\[ *-/\$COL\[$endCol-/g;
	$tmp =~ s/(\$COL\[.*?\])/eval($1)/ge;


	$msg =
       # message header
       "From: "           . $cgi->param('from') . "\n" .
       "Reply-To: "       . $cgi->param('replyTo')   . "\n" .
       "Subject:  ". $cgi->param('subject') . "\n" .
	  "\n" . $tmp . "\n";

	$msg =~ s/\r//g;
	return $msg;
}

sub success {
    print $cgi->header,
    $cgi->start_html( '-title'=>'Email Sent'),
    $cgi->h1('Your message has been sent.'),
    $cgi->end_html;
    exit(0);
}
