#!/usr/local/bin/perl


## This file is profHousekeeping.pl
## It provides access to utilities deleting uneeded files, etc.
##

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

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

# begin Timing code
use Benchmark;
my $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 $courseDirectory		= $Global::coursesDirectory . $Course . $Global::dirDelim;
my $courseScriptsDirectory 	= getCourseScriptsDirectory;
my $databaseDirectory 		= getCourseDatabaseDirectory;
my $htmlURL       		= getCourseHtmlURL;
my $scriptDirectory   		= getWebworkScriptDirectory;
my $templateDirectory           = getCourseTemplateDirectory;
my $dat                     	= getDat; 

require "${scriptDirectory}$Global::DBglue_pl";
require "${scriptDirectory}$Global::FILE_pl";
require "${scriptDirectory}$Global::HTMLglue_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 ) {
	    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
	# nothing further to get in this case

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

# print navigation button
print $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 Housekeeping Utilities for $Course"), "\n",
        $cgi->p,
	"From this page, you can recover disk space by removing old tmp files,
	compress the gdbm database, show active users, edit the Course Environment file, etc.";

# remove tmp files 
print heading('Cleanup', "1. Cleanup $Course:"),
	$cgi->startform(-action=>"${cgiURL}profRemoveTmpFiles.pl"),
	$cgi->submit(-value=>'Remove unnecessary tmp files'), "\n",
	hiddens('user', 'key', 'course'),
	$cgi->endform(), "\n",
	$cgi->p, "This removes unnecessary temporary fiels and may recover quite a bit of disk space.";


# compress database
print heading('Compress', "2. Compress the webworkdatabase for $Course:"),
	$cgi->startform(-action=>"${cgiURL}profCompress_GDBM_webwork-database.pl"),
	$cgi->submit(-value=>'Compress gdbm database'), "\n",
	hiddens('user', 'key', 'course'),
	$cgi->endform(), "\n",
	$cgi->p, "If $Course uses the gdbm database, this should be run monthly to significantly reduce the size of the database file.  if $Course does not use the gdbm database, the operation will abort and nothing will be done.";

# active users
print heading('Active', "3. Show active users in $Course:"),
	$cgi->startform(-action=>"${cgiURL}profShowActiveUsers.pl"),
	$cgi->submit(-value=>'Show Active Users'), "\n",
	hiddens('user', 'key', 'course'),
	$cgi->endform(), "\n",
	$cgi->p, "This lists all users who are currently logged into $Course.";

# webworkcourse.ph
my $filename = "${courseDirectory}$Global::courseEnvironmentFile";
my ($date, $label, @stat);
if (-e $filename) {
	@stat = stat($filename);
	$date = $stat[9];
	$date = formatDateAndTime($date);
	$date =~ s|\s*at.*||;
	$label = "  Last Changed $date";
}

print heading('Environment', "4. Edit Course Environment File for $Course:"),
	$cgi->startform(-action=>"${cgiURL}profEditCourseFiles.pl"),
	$cgi->submit(-value=>'Edit Course Environment File'), "$label\n",
	hiddens('user', 'key', 'course'),
	$cgi->hidden(-name=>'filename', -value=>$Global::courseEnvironmentFile), "\n",
	$cgi->hidden(-name=>'ext', -value=>'ph'), "\n",
	$cgi->endform(), "\n",
	$cgi->p, "This lets you edit the Course Environment File for $Course.";


print &htmlBOTTOM("profHousekeeping.pl", \%inputs);

# begin Timing code
my $endTime = new Benchmark;
&Global::logTimingInfo($beginTime,$endTime,"profHousekeeping.pl",$inputs{'course'},$inputs{'user'});
# end Timing code
exit;

################################################################################
#
# HELPFUL METHODS
#
################################################################################

#returns the horizontal line, blue square, and heading for each option
#in the list, eliminating the need to repeat this code each time it is needed
#this does NOT PRINT the info, so that it can be incorporated into other text
sub heading {
        my $link = shift; #name for internal link (used for shortcuts on some pages)
        my $text = shift; #text used as the main heading

        return "\n",
                 $cgi->p, "\n",
                 $cgi->a({-name=>$link}), "\n",
                 $cgi->hr({ -noshade=>undef }), "\n",
                 $cgi->h4({ -align=>'LEFT' },
                                "\n" . $cgi->img({-src=>"$Global::bluesquareImgUrl", -border=>1, -alt=>'' }) . "\n" .
                                $text ), "\n";
}

#prints hidden form fields for each of given cgi parameters
#if a given parameter does not exist, a note is placed in the html to that affect
#this does NOT PRINT the info, so that it can be incorporated into other text
sub hiddens {
	my @params = @_;
	my $out;
	
	foreach my $param (@params) {
		if (exists $inputs{$param}) {
			$out .= $cgi->hidden(-name=>"$param", -value=>"$inputs{$param}") . "\n";
		} else {
			$out .= $cgi->p . "\nExpected cgi parameter $param does not exist or is empty";
		}
	}
	
	$out;
}