#!/usr/bin/perl



## This file is profClasslist.pl
## It provides access to utilities for building, correcting and viewing classlist files
##

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

use lib '/ww/webwork/development/'; # mainWeBWorKDirectory;
use CGI qw(:standard);
use Global;
use Auth;
use strict;

my $logTimingData = 0;
my $beginTime;

# begin Timing code
if ($logTimingData == 1) {
	use Benchmark;
	$beginTime = new Benchmark;
}
# end Timing code


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

# get information from CGI inputs  (see also below for additional information)

my $Course 			= $inputs{'course'};
my $User 			= $inputs{'user'};
my $Session_key 	= $inputs{'key'};

# verify that information has been received
	unless($Course && $User && $Session_key) {
		&wwerror("$0","The script did not receive the proper input data.","","");
		die "The script profLogin.pl did not receive the proper input data.";
		}

# establish environment for this script

&Global::getCourseEnvironment($inputs{'course'});


my $cgiURL   				= getWebworkCgiURL;
my $courseScriptsDirectory 	= getCourseScriptsDirectory;
my $databaseDirectory 		= getCourseDatabaseDirectory;
my $htmlURL       			= getCourseHtmlURL;
my $scriptDirectory   		= getWebworkScriptDirectory;
my $templateDirectory       = getCourseTemplateDirectory;
my $dat                     = getDat;  
my $dd                      = getDirDelim();

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

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


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

#verify session key
	&verify_key($inputs{'user'}, $inputs{'key'}, $keyFile, $inputs{'course'});

# verify permissions are correct
	if ($permissions != $Global::instructor_permissions ) {
		print "permissions = $permissions instructor_permissions = $Global::instructor_permissions\n";
		print &html_NO_PERMISSION;
		exit(0);
		}
# get the rest of the information from the submitted form

my $format = $inputs{'format'};  #alph, section, or recitation
my $set_status = $inputs{'set_status'};  #locked or unlocked

# print HTML text
print &htmlTOP("Classlist Utilities");

# print navigation buttons
print qq!
<A HREF="${cgiURL}profLogin.pl?user=$inputs{'user'}&key=$inputs{'key'}&course=$inputs{'course'}">
<IMG SRC="${Global::upImgUrl}" align="right" BORDER=1 ALT="[Up]"></A><p>
!;

print <<EOF;
<HR><BR>

<h3 align="left">WeBWorK classlist editing programs for $Course</h3>

From this page you can edit classlist database or give a student a new password.
You can also import and export the database. <p>
EOF

my $classList_ref;
$format = '' unless defined $format;
if ($format eq 'section') {
		$classList_ref = getAllLoginNamesSortedBySectionThenByName();
}
elsif ($format eq 'recitation') {
		$classList_ref = getAllLoginNamesSortedByRecitationThenByName();
}
else {
		$classList_ref = getAllLoginNamesSortedByName();
}

my @classList = @$classList_ref;

if ((defined $set_status) and ($set_status eq 'lock')) {
	lock_CL_database();
}
elsif ((defined $set_status) and ($set_status eq 'unlock')) {
	unlock_CL_database();
}

my $status = get_CL_database_status();

if ($status eq 'locked') {
	print <<EOF;
	<P>
	<FONT COLOR='#ff00aa'><B>CLASSLIST DATABASE IS LOCKED</B></font> <P>
	This means the database can NOT be updated via the web but the database can be
	exported to and imported from an ascii comma separated (.cvs) classlist file.

	<HR NOSHADE>
	<H4 ALIGN=LEFT>
 	<IMG SRC="$Global::bluesquareImgUrl" BORDER=1  ALT="">
1. Unlock the classlist database for $Course.
</H4>

Unlock the database.

		<FORM METHOD = "POST" ACTION= "${cgiURL}profClasslist.pl">
		<INPUT TYPE="HIDDEN" NAME='set_status' VALUE='unlock'>
		<INPUT TYPE="HIDDEN" NAME='user' VALUE="$inputs{'user'}">
		<INPUT TYPE="HIDDEN" NAME='key' VALUE="$inputs{'key'}">
		<INPUT TYPE="HIDDEN" NAME='course' VALUE="$inputs{'course'}">
		<INPUT TYPE="HIDDEN" NAME='format' VALUE="$inputs{'format'}">
		<INPUT TYPE="SUBMIT" VALUE= 'Unlock'>
		</FORM>
EOF
}

elsif ($status eq 'unlocked') {

	print <<EOF;
	<P>
	<FONT COLOR='#ff00aa'><B>CLASSLIST DATABASE IS UNLOCKED</B></font> <P>
	This means the database can be updated via the web but the database can NOT be
	exported to and imported from an ascii comma separated (.cvs) classlist file.

	<HR NOSHADE>
	<H4 ALIGN=LEFT>
 	<IMG SRC="$Global::bluesquareImgUrl" BORDER=1  ALT="">
1. Lock the classlist database for $Course.
</H4>

Lock the database.

		<FORM METHOD = "POST" ACTION= "${cgiURL}profClasslist.pl">
		<INPUT TYPE="HIDDEN" NAME='set_status' VALUE='lock'>
		<INPUT TYPE="HIDDEN" NAME="user" VALUE="$inputs{'user'}">
		<INPUT TYPE="HIDDEN" NAME="key" VALUE="$inputs{'key'}">
		<INPUT TYPE="HIDDEN" NAME="course" VALUE="$inputs{'course'}">
		<INPUT TYPE="HIDDEN" NAME='format' VALUE="$inputs{'format'}">
		<INPUT TYPE="SUBMIT" VALUE= 'Lock'>
		</FORM>
EOF
}

print <<EOF;
<P>
<HR NOSHADE>
<H4 ALIGN=LEFT>
 <IMG SRC="$Global::bluesquareImgUrl" BORDER=1  ALT="">
2. Edit the classlist database for $Course.
</H4>

Select the student record that you wish to edit.  <BR>

		<FORM METHOD = "POST" ACTION= "${cgiURL}profEditClasslistDB.pl">
		<INPUT TYPE="SUBMIT" VALUE="Select student">
EOF



# enter available individual logins
	print qq! <BR><SELECT Name='studentLogin' >\n!;
	my ($lastName, $firstName, $studentID, $login_name, $section, $recitation, $label);
	
# get a list of logins to list as option values.  save this in a string as we will use it
# twice

	my $option_list ='';	
	foreach $login_name (@classList) {
		attachCLRecord($login_name);
											   ## student
		$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;
		$option_list .= "<OPTION VALUE = \"$login_name\">$label \n";
#		print "<OPTION VALUE = \"$login_name\">$label \n";
	}
	print $option_list;	
	print qq! \n</SELECT>\n!;

# resume printing the rest of the forms

print <<EOF;
		 <INPUT TYPE="HIDDEN" NAME="user" VALUE="$inputs{'user'}">
		 <INPUT TYPE="HIDDEN" NAME="key" VALUE="$inputs{'key'}">
		 <INPUT TYPE="HIDDEN" NAME="course" VALUE="$inputs{'course'}">
		 <INPUT TYPE="HIDDEN" NAME='save' VALUE='OFF'>
		 <INPUT TYPE="HIDDEN" NAME='firsttime' VALUE=1>


		 </FORM>
EOF

print <<EOF;
<P>
<HR NOSHADE>
<H4 ALIGN=LEFT>
 <IMG SRC="$Global::bluesquareImgUrl" BORDER=1  ALT="">
3. Give a student a new password for $Course.
</H4>

Select the student who needs a new password.  <BR>

		<FORM METHOD = "POST" ACTION= "${cgiURL}profNewPassword.pl">
		<INPUT TYPE="SUBMIT" VALUE="Select student">
EOF

# enter available individual logins
	print qq! <BR><SELECT Name='studentLogin' >\n!; 
	print $option_list;	
	print qq! \n</SELECT>\n!;

# resume printing the rest of the forms

print <<EOF;
		 <INPUT TYPE="HIDDEN" NAME="user" VALUE="$inputs{'user'}">
		 <INPUT TYPE="HIDDEN" NAME="key" VALUE="$inputs{'key'}">
		 <INPUT TYPE="HIDDEN" NAME="course" VALUE="$inputs{'course'}">
		 <INPUT TYPE="HIDDEN" NAME='save' VALUE='OFF'>
		 <INPUT TYPE="HIDDEN" NAME='firsttime' VALUE=1>


		 </FORM>
EOF



print <<EOF;
<P>
<HR NOSHADE>
<H4 ALIGN=LEFT>
 <IMG SRC="$Global::bluesquareImgUrl" BORDER=1  ALT="">
4. View the classlist database for $Course.
</H4>

Use this to see all the data in the classlist database.  You can edit the classlist database
by using item 2 above and you can add students to the classlist database from the
Add Student(s) Page.  You can also use item 5 to
export it to a classlist file suitable for editing by a spreadsheet program such as Excel.  Item 6
imports the classlist database from a classlist file.  You can use items 7 and 8 to download and 
upload classlist files to and from your personal computer.

EOF

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

print	$cgi->startform(-action=>"${cgiURL}profViewClasslistDB.pl"),
		$cgi->submit(-value=>'View classlist Database'), "\n",
		"Order students \n",
		$cgi->radio_group(
			-name=>'format',
			-values=>['alph','section','recitation'],
			-default=>'alph',
			-labels=>\%labels
		),
		$cgi->hidden(-name=>'course', -value=>"$inputs{'course'}"), "\n",
		$cgi->hidden(-name=>'user', -value=>"$inputs{'user'}"), "\n",
		$cgi->hidden(-name=>'key', -value=>"$inputs{'key'}"), "\n",
		$cgi->endform(), "\n",
		$cgi->p, "\n" ;

# resume printing the rest of the form


print <<EOF;
<P>
<HR NOSHADE>
<FONT COLOR='#ff00aa'><b>Before exporting or importing the
classlist database or downloading or uploading classlist files, make sure you understand
the difference between the classlist database and classlist files. Click on help below.</b></font><p>
<HR NOSHADE>
<H4 ALIGN=LEFT>
 <IMG SRC="$Global::bluesquareImgUrl" BORDER=1  ALT=""> 
5. Export the $Course classlist database to a classlist file.
</H4>
This will export the current classlist database to the
selected classlist file.  Note the classlist database must locked first. 

EOF

my $shortFileName = getCourseClasslistFile($Course);	                                                                                                                                                                                                                                                                                                                                                                                                                                   
if ($shortFileName =~ m|$dd|)  {                                                                                                                                                                                                                                   
    $shortFileName =~ m|$dd([^$dd]*)$|;  ## extract filename from full path name                                                                                                                                                                                   
    $shortFileName = $1;                                                                                                                                                                                                                                           
} 

print	$cgi->startform(-action=>"${cgiURL}profExportClasslistDatabase.pl"),"\n",
	 	$cgi->textfield(-name=>'savefilename', -size => 25, -value=> "$shortFileName", -override=>1), ' ',
		'Enter a new file name or use the default. The file will be saved with the extension .lst',"\n",p,
		$cgi->checkbox(-name=>'overWrite',-value => 1, -label => 'Overwrite existing file'),"\n", br,
		$cgi->checkbox(-name=>'backUp',-value => 1, -label => 'Backup existing file first',-checked, -override),"\n",p,	
		$cgi->submit(-value=>'Export classlist Database'), "\n",
		$cgi->hidden(-name=>'course', -value=>"$inputs{'course'}"), "\n",
		$cgi->hidden(-name=>'user', -value=>"$inputs{'user'}"), "\n",
		$cgi->hidden(-name=>'key', -value=>"$inputs{'key'}"), "\n",
		$cgi->endform(), "\n",
		$cgi->p, "\n";


print <<EOF;
<P>
<HR NOSHADE>

<H4 ALIGN=LEFT>
 <IMG SRC="$Global::bluesquareImgUrl" BORDER=1  ALT=""> 
6. Import the $Course classlist database from a classlist file.
</H4>
This will update the classlist database using the information from the
selected classlist file. Note the classlist database must locked first.
If you have a large classlist and/or have already built many sets, this may
take quite a bit of time.  Carefully select the classlist file and the 
options you want.<p> 

EOF

# get all classlist files
	my ($ar_sortedNames, $hr_classlistLabels) = getClasslistFilesAndLabels($Course);
	my @sortedNames = @$ar_sortedNames;
	my %classlistLabels = %$hr_classlistLabels;
						
print	$cgi->startform(-action=>"${cgiURL}profImportClasslistDatabase.pl"),
		$cgi->popup_menu(-name=>'classList',
		-values=>\@sortedNames,
		-labels=>\%classlistLabels), ' Select classlist file.',p,
						
		"If a student is in the current classlist database <FONT COLOR='#ff00aa'><b>and</b></FONT>
		is in the the selected classlist file:",'<BR>',
				
		$cgi->checkbox(-name=>'update_firstName',-value => 1, -label => 'update first name', -override), '<BR>',
		$cgi->checkbox(-name=>'update_lastName',-value => 1, -label => 'update last name', -override),'<BR>', 
		$cgi->checkbox(-name=>'update_status',-value => 1, -label => 'update status', -checked, -override),'<BR>', 
		$cgi->checkbox(-name=>'update_comment',-value => 1, -label => 'update comment', -override), '<BR>',
		$cgi->checkbox(-name=>'update_section',-value => 1, -label => 'update section', -override),'<BR>', 
		$cgi->checkbox(-name=>'update_recitation',-value => 1, -label => 'update recitation', -override),'<BR>', 
		$cgi->checkbox(-name=>'update_email_address',-value => 1, -label => 'update email_address', -override), '<p>',

		"If a student is in the current classlist database <FONT COLOR='#ff00aa'><b>but is not</b></FONT>
		in the the selected classlist file:",'<BR>',
		
		$cgi->input({-type=>'radio', -name=>'update_drop', -value=>'drop',-checked=>1}), " \n",
		"Change student's status to 'drop' in the classlist database.  This removes the student's login privileges and is the
		recommended action. \n", $cgi->br,
		$cgi->input({-type=>'radio', -name=>'update_drop', -value=>'leave'}), " \n",
		"Leave the student's records in the classlist database unchanged.\n", $cgi->br,
		$cgi->input({-type=>'radio', -name=>'update_drop', -value=>'remove' }), " \n",
		"Remove the student's records from the classlist database.\n", $cgi->br,
		
		$cgi->submit(-value=>'Import classlist Database'), "\n",p,
		$cgi->hidden(-name=>'course', -value=>"$inputs{'course'}"), "\n",
		$cgi->hidden(-name=>'user', -value=>"$inputs{'user'}"), "\n",
		$cgi->hidden(-name=>'key', -value=>"$inputs{'key'}"), "\n",
		$cgi->endform(), "\n",
		$cgi->p, "\n";


print <<EOF;
<P>
<HR NOSHADE>

<H4 ALIGN=LEFT>
 <IMG SRC="$Global::bluesquareImgUrl" BORDER=1  ALT="">
  
7. Download (or view) $Course classlist file(s) to your personal computer.
</H4>

You can download files for editing or viewing in either cvs (i.e. comma delimited), html, text, or
tab (i.e. tab delimited) format.  <BR>
csv is a supported format for Excel and is the recommended format if you use Excel. <BR> <BR>


		<FORM METHOD = "POST" ACTION= "${cgiURL}profDownloadClasslistFiles.pl">
		format:
		<INPUT TYPE=RADIO NAME="format" VALUE="csv" CHECKED>csv
		<INPUT TYPE=RADIO NAME="format" VALUE="html" >html
		<INPUT TYPE=RADIO NAME="format" VALUE="text" >text
		<INPUT TYPE=RADIO NAME="format" VALUE="tab" >tab  <BR>

		<INPUT TYPE="SUBMIT" VALUE="Select file(s)">

EOF

# resume printing the rest of the form

print <<EOF;
		 <INPUT TYPE="HIDDEN" NAME="user" VALUE="$inputs{'user'}">
		 <INPUT TYPE="HIDDEN" NAME="key" VALUE="$inputs{'key'}">
		 <INPUT TYPE="HIDDEN" NAME="course" VALUE="$inputs{'course'}">
		 <INPUT TYPE="HIDDEN" NAME="download" VALUE= 0 >
		 <INPUT TYPE="HIDDEN" NAME="fileName" VALUE= "" >
		 </FORM>
EOF



print <<EOF;
<P>
<HR NOSHADE>
<H4 ALIGN=LEFT>
 <IMG SRC="$Global::bluesquareImgUrl" BORDER=1  ALT="">
8. Upload $Course classlist files from your personal computer.
</H4>

You can upload classlist files from your personal computer in cvs (i.e. comma delimited),
tab (i.e. tab delimited), or html format.  Usually you would do this after exporting the 
classlist database to a file, downloading and then editing the file in Excel or some other 
editor or spreadsheet program.  Only valid classlist files
can be uploaded.  For csv format, the filename on your personal computer must have extension
.csv or .lst. For tab format, the extension must be .txt and for html format, the extension
must be .html or .htm.  The file will be saved on the server with extension .lst (e.g. MTH140A.csv would be
saved as MTH140A.lst).  Be very careful.  Students can change their own email
addresses and it is possible that a student my have changed his or her address after you 
started working on the file. This can only happen if you explicitly unlocked the classlist 
database after exporting it.

<FORM METHOD = 'POST' enctype='multipart/form-data' ACTION= "${cgiURL}profUploadClasslistFile.pl">

		format on personal computer:
		<INPUT TYPE=RADIO NAME="format" VALUE="csv" CHECKED>csv
		<INPUT TYPE=RADIO NAME="format" VALUE="tab" >tab
		<INPUT TYPE=RADIO NAME="format" VALUE="html" >html  <BR>
		<INPUT TYPE=CHECKBOX NAME="overWrite" VALUE=1 unchecked> Overwrite existing file
		<INPUT TYPE=CHECKBOX NAME="backUp" VALUE=1 checked> Backup existing file first	<BR>

File to upload: <input type=file name=upload><br>
<br>
<input type=submit value=UpLoad> the file.

		 <INPUT TYPE="HIDDEN" NAME="user" VALUE="$inputs{'user'}">
		 <INPUT TYPE="HIDDEN" NAME="key" VALUE="$inputs{'key'}">
		 <INPUT TYPE="HIDDEN" NAME="course" VALUE="$inputs{'course'}">
		 </FORM>
EOF

print <<EOF;
<P>
<HR NOSHADE>
<H4 ALIGN=LEFT>
 <IMG SRC="$Global::bluesquareImgUrl" BORDER=1  ALT="">
9. Simple editing of $Course classlist files.
</H4>

Use this for simple editing, e.g. changing a few items or  adding a couple of new students.
For more complicated editing, download the file to a preadsheet program such as Excel by option 7 above.
<FONT COLOR='#ff00aa'><b>Note that editing a classlist files has no effect on the classlist database.</b></font>

		<FORM METHOD = "POST" ACTION= "${cgiURL}profFormEditClasslistFiles.pl"> 

        <INPUT TYPE="SUBMIT" VALUE="Select file(s)">

EOF


    
# resume printing the rest of the form

print <<EOF;
         <INPUT TYPE="HIDDEN" NAME="user" VALUE="$inputs{'user'}">
         <INPUT TYPE="HIDDEN" NAME="key" VALUE="$inputs{'key'}">
         <INPUT TYPE="HIDDEN" NAME="course" VALUE="$inputs{'course'}">  
         <INPUT TYPE="HIDDEN" NAME="action" VALUE= "" >   
         <INPUT TYPE="HIDDEN" NAME="fileName" VALUE= "" >  
         <INPUT TYPE="HIDDEN" NAME="readWrite" VALUE= "readOnly" >                 
         </FORM>     
EOF




print &htmlBOTTOM("profClasslist.pl", \%inputs,'profClasslistHelp.html');

# begin Timing code
if ($logTimingData == 1) {
	my $endTime = new Benchmark;
	&Global::logTimingInfo($beginTime,$endTime,'profClasslist.pl',$Course,$User);
}
# end Timing code
exit;




