File:  [LON-CAPA] / loncom / interface / lonparmset.pm
Revision 1.113: download - view: text, annotated - select for diffs
Mon Jun 30 20:24:26 2003 UTC (21 years, 4 months ago) by sakharuk
Branches: MAIN
CVS tags: HEAD
Restored original name for oarameter allowing split problems between pages.

# The LearningOnline Network with CAPA
# Handler to set parameters for assessments
#
# $Id: lonparmset.pm,v 1.113 2003/06/30 20:24:26 sakharuk Exp $
#
# Copyright Michigan State University Board of Trustees
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# LON-CAPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# /home/httpd/html/adm/gpl.txt
#
# http://www.lon-capa.org/
#
###################################################################
###################################################################

=pod

=head1 NAME

lonparmset - Handler to set parameters for assessments and course

=head1 SYNOPSIS

lonparmset provides an interface to setting course parameters. 

=head1 DESCRIPTION

This module sets coursewide and assessment parameters.

=head1 INTERNAL SUBROUTINES

=over 4

=cut

###################################################################
###################################################################

package Apache::lonparmset;

use strict;
use Apache::lonnet;
use Apache::Constants qw(:common :http REDIRECT);
use Apache::lonhtmlcommon();
use Apache::loncommon;
use GDBM_File;
use Apache::lonhomework;
use Apache::lonxml;


my %courseopt;
my %useropt;
my %parmhash;

my @ids;
my %symbp;
my %mapp;
my %typep;
my %keyp;

my %maptitles;

my $uname;
my $udom;
my $uhome;
my $csec;
my $coursename;

##################################################
##################################################

=pod

=item parmval

Figure out a cascading parameter.

Inputs:  $what - a parameter spec (incluse part info and name I.E. 0.weight)
         $id   - a bighash Id number
         $def  - the resource's default value   'stupid emacs

Returns:  A list, the first item is the index into the remaining list of items of parm valuse that is the active one, the list consists of parm values at the 11 possible levels

11- resource default
10- map default
9 - General Course
8 - Map or Folder level in course
7 - resource level in course
6 - General for section
5 - Map or Folder level for section
4 - resource level in section
3 - General for specific student
2 - Map or Folder level for specific student
1 - resource level for specific student

=cut

##################################################
##################################################
sub parmval {
    my ($what,$id,$def)=@_;
    my $result='';
    my @outpar=();
# ----------------------------------------------------- Cascading lookup scheme

    my $symbparm=$symbp{$id}.'.'.$what;
    my $mapparm=$mapp{$id}.'___(all).'.$what;

    my $seclevel=$ENV{'request.course.id'}.'.['.$csec.'].'.$what;
    my $seclevelr=$ENV{'request.course.id'}.'.['.$csec.'].'.$symbparm;
    my $seclevelm=$ENV{'request.course.id'}.'.['.$csec.'].'.$mapparm;

    my $courselevel=$ENV{'request.course.id'}.'.'.$what;
    my $courselevelr=$ENV{'request.course.id'}.'.'.$symbparm;
    my $courselevelm=$ENV{'request.course.id'}.'.'.$mapparm;

# -------------------------------------------------------- first, check default

    if ($def) { $outpar[11]=$def; $result=11; }

# ----------------------------------------------------- second, check map parms

    my $thisparm=$parmhash{$symbparm};
    if ($thisparm) { $outpar[10]=$thisparm; $result=10; }

# --------------------------------------------------------- third, check course

    if (defined($courseopt{$courselevel})) {
	$outpar[9]=$courseopt{$courselevel};
	$result=9;
    }

    if (defined($courseopt{$courselevelm})) {
	$outpar[8]=$courseopt{$courselevelm};
	$result=8;
    }

    if (defined($courseopt{$courselevelr})) {
	$outpar[7]=$courseopt{$courselevelr};
	$result=7;
    }

    if (defined($csec)) {
        if (defined($courseopt{$seclevel})) {
	    $outpar[6]=$courseopt{$seclevel};
	    $result=6;
	}
        if (defined($courseopt{$seclevelm})) {
	    $outpar[5]=$courseopt{$seclevelm};
	    $result=5;
	}

        if (defined($courseopt{$seclevelr})) {
	    $outpar[4]=$courseopt{$seclevelr};
	    $result=4;
	}
    }

# ---------------------------------------------------------- fourth, check user

    if (defined($uname)) {
	if (defined($useropt{$courselevel})) {
	    $outpar[3]=$useropt{$courselevel};
	    $result=3;
	}

	if (defined($useropt{$courselevelm})) {
	    $outpar[2]=$useropt{$courselevelm};
	    $result=2;
	}

	if (defined($useropt{$courselevelr})) {
	    $outpar[1]=$useropt{$courselevelr};
	    $result=1;
	}
    }
    return ($result,@outpar);
}

##################################################
##################################################

=pod

=item valout

Format a value for output.

Inputs:  $value, $type

Returns: $value, formatted for output.  If $type indicates it is a date,
localtime($value) is returned.

=cut

##################################################
##################################################
sub valout {
    my ($value,$type)=@_;
    my $result = '';
    # Values of zero are valid.
    if (! $value && $value ne '0') {
	$result = '  ';
    } else {
        if ($type eq 'date_interval') {
            my ($sec,$min,$hour,$mday,$mon,$year)=gmtime($value);
            $year=$year-70;
            $mday--;
            if ($year) {
		$result.=$year.' yrs ';
            }
            if ($mon) {
		$result.=$mon.' mths ';
            }
            if ($mday) {
		$result.=$mday.' days ';
            }
            if ($hour) {
		$result.=$hour.' hrs ';
            }
            if ($min) {
		$result.=$min.' mins ';
            }
            if ($sec) {
		$result.=$sec.' secs ';
            }
            $result=~s/\s+$//;
        } elsif ($type=~/^date/) {
            $result = localtime($value);
        } else {
            $result = $value;
        }
    }
    return $result;
}

##################################################
##################################################

=pod

=item plink

Produces a link anchor.

Inputs: $type,$dis,$value,$marker,$return,$call

Returns: scalar with html code for a link which will envoke the 
javascript function 'pjump'.

=cut

##################################################
##################################################
sub plink {
    my ($type,$dis,$value,$marker,$return,$call)=@_;
    my $winvalue=$value;
    unless ($winvalue) {
	if ($type=~/^date/) {
            $winvalue=$ENV{'form.recent_'.$type};
        } else {
            $winvalue=$ENV{'form.recent_'.(split(/\_/,$type))[0]};
        }
    }
    return 
	'<a href="javascript:pjump('."'".$type."','".$dis."','".$winvalue."','"
	    .$marker."','".$return."','".$call."'".');">'.
		&valout($value,$type).'</a><a name="'.$marker.'"></a>';
}


sub startpage {
    my ($r,$id,$udom,$csec,$uname,$have_assesments)=@_;

    my $bodytag=&Apache::loncommon::bodytag('Set Course Parameters','',
                                            'onUnload="pclose()"');
    my $chooseopt=&Apache::loncommon::select_dom_form($udom,'udom').' '.
        &Apache::loncommon::selectstudent_link('parmform','uname','udom');
    my $selscript=&Apache::loncommon::studentbrowser_javascript();
    my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
    $r->print(<<ENDHEAD);
<html>
<head>
<title>LON-CAPA Course Parameters</title>
<script>

    function pclose() {
        parmwin=window.open("/adm/rat/empty.html","LONCAPAparms",
                 "height=350,width=350,scrollbars=no,menubar=no");
        parmwin.close();
    }

    $pjump_def

    function psub() {
        pclose();
        if (document.parmform.pres_marker.value!='') {
            document.parmform.action+='#'+document.parmform.pres_marker.value;
            var typedef=new Array();
            typedef=document.parmform.pres_type.value.split('_');
           if (document.parmform.pres_type.value!='') {
            if (typedef[0]=='date') {
                eval('document.parmform.recent_'+
                     document.parmform.pres_type.value+
		     '.value=document.parmform.pres_value.value;');
            } else {
                eval('document.parmform.recent_'+typedef[0]+
		     '.value=document.parmform.pres_value.value;');
            }
	   }
            document.parmform.submit();
        } else {
            document.parmform.pres_value.value='';
            document.parmform.pres_marker.value='';
        }
    }

    function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
        var options = "width=" + w + ",height=" + h + ",";
        options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
        options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
        var newWin = window.open(url, wdwName, options);
        newWin.focus();
    }
</script>
$selscript
</head>
$bodytag

<form method="post" action="/adm/parmset" name="envform">
<h3>Course Environment</h3>
<input type="submit" name="crsenv" value="Set Course Environment">
</form>
<hr />
<form method="post" action="/adm/parmset" name="parmform">
<h3>Course Assessments</h3>

<a href="/adm/helper/parameter.helper">Use Assignment Parameter Helper</a>, a
simpler interface to set open, due, or answer open dates for problems or
sequences.<br />&nbsp;<br />
ENDHEAD

    if (!$have_assesments) {
	$r->print('<font color="red">There are no assesment parameters in this course to set.</font><br />');	
    } else {
	$r->print(<<ENDHEAD);
<b>
Section/Group:
<input type="text" value="$csec" size="6" name="csec">
<br>
For User 
<input type="text" value="$uname" size="12" name="uname">
or ID
<input type="text" value="$id" size="12" name="id"> 
at Domain 
$chooseopt
</b>
<input type="hidden" value='' name="pres_value">
<input type="hidden" value='' name="pres_type">
<input type="hidden" value='' name="pres_marker">
ENDHEAD
    }
}

sub print_row {
    my ($r,$which,$part,$name,$rid,$default,$defaulttype,$display,$defbgone,
	$defbgtwo,$parmlev)=@_;
# get the values for the parameter in cascading order
# empty levels will remain empty
    my ($result,@outpar)=&parmval($$part{$which}.'.'.$$name{$which},
				  $rid,$$default{$which});
# get the type for the parameters
# problem: these may not be set for all levels
    my ($typeresult,@typeoutpar)=&parmval($$part{$which}.'.'.
                                          $$name{$which}.'.type',
				  $rid,$$defaulttype{$which});
# cascade down manually
    my $cascadetype=$defaulttype;
    for (my $i=$#typeoutpar;$i>0;$i--) {
	 if ($typeoutpar[$i]) { 
            $cascadetype=$typeoutpar[$i];
	} else {
            $typeoutpar[$i]=$cascadetype;
        }
    }
 
    my $parm=$$display{$which};

    if ($parmlev eq 'full' || $parmlev eq 'brief') {
        $r->print('<td bgcolor='.$defbgtwo.' align="center">'
                  .$$part{$which}.'</td>');
    } else {    
        $parm=~s|\[.*\]\s||g;
    }

    $r->print('<td bgcolor='.$defbgone.'>'.$parm.'</td>');
   
    my $thismarker=$which;
    $thismarker=~s/^parameter\_//;
    my $mprefix=$rid.'&'.$thismarker.'&';

    if ($parmlev eq 'general') {

        if ($uname) {
            &print_td($r,3,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
        } elsif ($csec) {
            &print_td($r,6,$defbgtwo,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display); 
        } else {
            &print_td($r,9,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display); 
        }
    } elsif ($parmlev eq 'map') {

        if ($uname) {
            &print_td($r,2,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
        } elsif ($csec) {
            &print_td($r,5,$defbgtwo,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
        } else {
            &print_td($r,8,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
        }
    } else {

        &print_td($r,11,'#FFDDDD',$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);

        if ($parmlev eq 'brief') {

           &print_td($r,7,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);

           if ($csec) {
               &print_td($r,4,$defbgtwo,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
           }
           if ($uname) {
               &print_td($r,1,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
           }
        } else {

           &print_td($r,10,'#FFDDDD',$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
           &print_td($r,9,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
           &print_td($r,8,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
           &print_td($r,7,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);

           if ($csec) {
               &print_td($r,6,$defbgtwo,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
               &print_td($r,5,$defbgtwo,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
               &print_td($r,4,$defbgtwo,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
           }
           if ($uname) {
               &print_td($r,3,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
               &print_td($r,2,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
               &print_td($r,1,$defbgone,$result,\@outpar,$mprefix,$_,\@typeoutpar,$display);
           }
        } # end of $brief if/else
    } # end of $parmlev if/else

    if ($parmlev eq 'full' || $parmlev eq 'brief') {
        $r->print('<td bgcolor=#CCCCFF align="center">'.
                  &valout($outpar[$result],$typeoutpar[$result]).'</td>');
    }
    my $sessionval=&Apache::lonnet::EXT('resource.'.$$part{$which}.
                                        '.'.$$name{$which},$symbp{$rid});
# this doesn't seem to work, and I don't think is correct
#    my $sessionvaltype=&Apache::lonnet::EXT('resource.'.$$part{$which}.
#                                      '.'.$$name{$which}.'.type',$symbp{$rid});
# this seems to work
    my $sessionvaltype=$typeoutpar[$result];
    if (!defined($sessionvaltype)) { $sessionvaltype=$$defaulttype{$which}; }
    $r->print('<td bgcolor=#999999 align="center"><font color=#FFFFFF>'.
                  &valout($sessionval,$sessionvaltype).'&nbsp;'.
                  '</font></td>');
    $r->print('</tr>');
    $r->print("\n");
}

sub print_td {
    my ($r,$which,$defbg,$result,$outpar,$mprefix,$value,$typeoutpar,$display)=@_;
    $r->print('<td bgcolor='.(($result==$which)?'"#AAFFAA"':$defbg).
              ' align="center">'.
              &plink($$typeoutpar[$which],$$display{$value},$$outpar[$which],
                     $mprefix."$which",'parmform.pres','psub').'</td>'."\n");
}

sub get_env_multiple {
    my ($name) = @_;
    my @values;
    if (defined($ENV{$name})) {
        # exists is it an array
        if (ref($ENV{$name})) {
            @values=@{ $ENV{$name} };
        } else {
            $values[0]=$ENV{$name};
        }
    }
    return(@values);
}

=pod

=item B<extractResourceInformation>: Given the course data hash, extractResourceInformation extracts lots of information about the course's resources into a variety of hashes.

Input: See list below:

=over 4

=item B<ids>: An array that will contain all of the ids in the course.

=item B<typep>: hash, id->type, where "type" contains the extension of the file, thus, I<problem exam quiz assess survey form>.

=item B<keyp>: hash, id->key list, will contain a comma seperated list of the meta-data keys available for the given id

=item B<allparms>: hash, name of parameter->display value (what is the display value?)

=item B<allparts>: hash, part identification->text representation of part, where the text representation is "[Part $part]"

=item B<allkeys>: hash, full key to part->display value (what's display value?)

=item B<allmaps>: hash, ???

=item B<fcat>: ???

=item B<defp>: hash, ???

=item B<mapp>: ??

=item B<symbp>: hash, id->full sym?

=back

=cut

sub extractResourceInformation {
    my $bighash = shift;
    my $ids = shift;
    my $typep = shift;
    my $keyp = shift;
    my $allparms = shift;
    my $allparts = shift;
    my $allkeys = shift;
    my $allmaps = shift;
    my $fcat = shift;
    my $defp = shift;
    my $mapp = shift;
    my $symbp = shift;
    my $maptitles=shift;

    foreach (keys %$bighash) {
	if ($_=~/^src\_(\d+)\.(\d+)$/) {
	    my $mapid=$1;
	    my $resid=$2;
	    my $id=$mapid.'.'.$resid;
	    my $srcf=$$bighash{$_};
	    if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
		$$ids[$#$ids+1]=$id;
		$$typep{$id}=$1;
		$$keyp{$id}='';
		foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'allpossiblekeys'))) {
		  if ($_=~/^parameter\_(.*)/) {
                    my $key=$_;
                    my $allkey=$1;
                    $allkey=~s/\_/\./g;
                    my $display= &Apache::lonnet::metadata($srcf,$key.'.display');
                    my $name=&Apache::lonnet::metadata($srcf,$key.'.name');
                    my $part= &Apache::lonnet::metadata($srcf,$key.'.part');
                    my $parmdis = $display;
                    $parmdis =~ s|(\[Part.*$)||g;
                    my $partkey = $part;
                    $partkey =~ tr|_|.|;
                    $$allparms{$name} = $parmdis;
                    $$allparts{$part} = "[Part $part]";
                    $$allkeys{$allkey}=$display;
                    if ($allkey eq $fcat) {
		        $$defp{$id}= &Apache::lonnet::metadata($srcf,$key);
		    }
		    if ($$keyp{$id}) {
		        $$keyp{$id}.=','.$key;
		    } else {
		        $$keyp{$id}=$key;
		    }
		  }
		}
		$$mapp{$id}=
		    &Apache::lonnet::declutter($$bighash{'map_id_'.$mapid});
                $$mapp{$mapid}=$$mapp{$id};
		$$allmaps{$mapid}=$$mapp{$id};
		$$maptitles{$mapid}=
 $$bighash{'title_'.$$bighash{'ids_'.&Apache::lonnet::clutter($$mapp{$id})}};
		$$maptitles{$$mapp{$id}}=$$maptitles{$mapid};
		$$symbp{$id}=$$mapp{$id}.
			'___'.$resid.'___'.
			    &Apache::lonnet::declutter($srcf);
                $$symbp{$mapid}=$$mapp{$id}.'___(all)';
	    }
	}
    }
}

##################################################
##################################################

=pod

=item assessparms

Show assessment data and parameters.  This is a large routine that should
be simplified and shortened... someday.

Inputs: $r

Returns: nothing

Variables used (guessed by Jeremy):

=over 4

=item B<pscat>: ParameterS CATegories? ends up a list of the types of parameters that exist, e.g., tol, weight, acc, opendate, duedate, answerdate, sig, maxtries, type.

=item B<psprt>: ParameterS PaRTs? a list of the parts of a problem that we are displaying? Used to display only selected parts?

=item B<allmaps>:

=back

=cut

##################################################
##################################################
sub assessparms {

    my $r=shift;
# -------------------------------------------------------- Variable declaration
    my %allkeys;
    my %allmaps;
    my %alllevs;

    $alllevs{'Resource Level'}='full';
#    $alllevs{'Resource Level [BRIEF]'}='brief';
    $alllevs{'Map Level'}='map';
    $alllevs{'Course Level'}='general';

    my %allparms;
    my %allparts;

    my %defp;
    %courseopt=();
    %useropt=();
    my %bighash=();

    @ids=();
    %symbp=();
    %typep=();

    my $message='';

    $csec=$ENV{'form.csec'};
    $udom=$ENV{'form.udom'};
    unless ($udom) { $udom=$r->dir_config('lonDefDomain'); }

    my @pscat=&get_env_multiple('form.pscat');
    my $pschp=$ENV{'form.pschp'};
    my @psprt=&get_env_multiple('form.psprt');
    if (!@psprt) { $psprt[0]='0'; }
    my $showoptions=$ENV{'form.showoptions'};

    my $pssymb='';
    my $parmlev='';
    my $prevvisit=$ENV{'form.prevvisit'};

#    unless ($parmlev==$ENV{'form.parmlev'}) {
#        $parmlev = 'full';
#    }
 
    unless ($ENV{'form.parmlev'}) {
        $parmlev = 'map';
    } else {
        $parmlev = $ENV{'form.parmlev'};
    }

# ----------------------------------------------- Was this started from grades?

    if (($ENV{'form.command'} eq 'set') && ($ENV{'form.url'})
	&& (!$ENV{'form.dis'})) {
	my $url=$ENV{'form.url'};
	$url=~s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
	$pssymb=&Apache::lonnet::symbread($url);
	if (!@pscat) { @pscat=('all'); }
	$pschp='';
        $parmlev = 'full';
    } elsif ($ENV{'form.symb'}) {
	$pssymb=$ENV{'form.symb'};
	if (!@pscat) { @pscat=('all'); }
	$pschp='';
        $parmlev = 'full';
    } else {
	$ENV{'form.url'}='';
    }

    my $id=$ENV{'form.id'};
    if (($id) && ($udom)) {
	$uname=(&Apache::lonnet::idget($udom,$id))[1];
	if ($uname) {
	    $id='';
	} else {
	    $message=
		"<font color=red>Unknown ID '$id' at domain '$udom'</font>";
	}
    } else {
	$uname=$ENV{'form.uname'};
    }
    unless ($udom) { $uname=''; }
    $uhome='';
    if ($uname) {
	$uhome=&Apache::lonnet::homeserver($uname,$udom);
        if ($uhome eq 'no_host') {
	    $message=
		"<font color=red>Unknown user '$uname' at domain '$udom'</font>";
	    $uname='';
        } else {
	    $csec=&Apache::lonnet::getsection($udom,$uname,
					      $ENV{'request.course.id'});
	    if ($csec eq '-1') {
		$message="<font color=red>".
		    "User '$uname' at domain '$udom' not ".
                    "in this course</font>";
		$uname='';
		$csec=$ENV{'form.csec'};
	    } else {
		my %name=&Apache::lonnet::userenvironment($udom,$uname,
		      ('firstname','middlename','lastname','generation','id'));
		$message="\n<p>\nFull Name: ".
		    $name{'firstname'}.' '.$name{'middlename'}.' '
			.$name{'lastname'}.' '.$name{'generation'}.
			    "<br>\nID: ".$name{'id'}.'<p>';
	    }
        }
    }

    unless ($csec) { $csec=''; }

    my $fcat=$ENV{'form.fcat'};
    unless ($fcat) { $fcat=''; }

# ------------------------------------------------------------------- Tie hashs
    if (!(tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
	      &GDBM_READER(),0640))) {
	$r->print("Unable to access course data. (File $ENV{'request.course.fn'}.db not tieable)");
	return ;
    }
    if (!(tie(%parmhash,'GDBM_File',
	      $ENV{'request.course.fn'}.'_parms.db',&GDBM_READER(),0640))) {
	$r->print("Unable to access parameter data. (File $ENV{'request.course.fn'}_parms.db not tieable)");
	return ;
    }

# --------------------------------------------------------- Get all assessments
    extractResourceInformation(\%bighash, \@ids, \%typep,\%keyp, \%allparms, \%allparts, \%allkeys, \%allmaps, $fcat, \%defp, \%mapp, \%symbp,\%maptitles);

    $mapp{'0.0'} = '';
    $symbp{'0.0'} = '';

# ---------------------------------------------------------- Anything to store?
    if ($ENV{'form.pres_marker'}) {
	my ($sresid,$spnam,$snum)=split(/\&/,$ENV{'form.pres_marker'});
	$spnam=~s/\_([^\_]+)$/\.$1/;
# ---------------------------------------------------------- Construct prefixes

	my $symbparm=$symbp{$sresid}.'.'.$spnam;
	my $mapparm=$mapp{$sresid}.'___(all).'.$spnam;
	
	my $seclevel=$ENV{'request.course.id'}.'.['.$csec.'].'.$spnam;
	my $seclevelr=$ENV{'request.course.id'}.'.['.$csec.'].'.$symbparm;
	my $seclevelm=$ENV{'request.course.id'}.'.['.$csec.'].'.$mapparm;
	
	my $courselevel=$ENV{'request.course.id'}.'.'.$spnam;
	my $courselevelr=$ENV{'request.course.id'}.'.'.$symbparm;
	my $courselevelm=$ENV{'request.course.id'}.'.'.$mapparm;
	
	my $storeunder='';
	if (($snum==9) || ($snum==3)) { $storeunder=$courselevel; }
	if (($snum==8) || ($snum==2)) { $storeunder=$courselevelm; }
	if (($snum==7) || ($snum==1)) { $storeunder=$courselevelr; }
	if ($snum==6) { $storeunder=$seclevel; }
	if ($snum==5) { $storeunder=$seclevelm; }
	if ($snum==4) { $storeunder=$seclevelr; }
	
	my $delete;
	if ($ENV{'form.pres_value'} eq '') { $delete=1;}
        my %storecontent = ($storeunder         => $ENV{'form.pres_value'},
                            $storeunder.'.type' => $ENV{'form.pres_type'});
	my $reply='';
	if ($snum>3) {
# ---------------------------------------------------------------- Store Course
#
# Expire sheets
	    &Apache::lonnet::expirespread('','','studentcalc');
	    if (($snum==7) || ($snum==4)) {
		&Apache::lonnet::expirespread('','','assesscalc',$symbp{$sresid});
	    } elsif (($snum==8) || ($snum==5)) {
		&Apache::lonnet::expirespread('','','assesscalc',$mapp{$sresid});
	    } else {
		&Apache::lonnet::expirespread('','','assesscalc');
	    }
# Store parameter
	    if ($delete) {
		$reply=&Apache::lonnet::del
		    ('resourcedata',[keys(%storecontent)],
		     $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
		     $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
	    } else {
		$reply=&Apache::lonnet::cput
		    ('resourcedata',\%storecontent,
		     $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
		     $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
	    }
	} else {
# ------------------------------------------------------------------ Store User
#
# Expire sheets
	    &Apache::lonnet::expirespread($uname,$udom,'studentcalc');
	    if ($snum==1) {
		&Apache::lonnet::expirespread
		    ($uname,$udom,'assesscalc',$symbp{$sresid});
	    } elsif ($snum==2) {
		&Apache::lonnet::expirespread
		    ($uname,$udom,'assesscalc',$mapp{$sresid});
	    } else {
		&Apache::lonnet::expirespread($uname,$udom,'assesscalc');
	    }
# Store parameter
	    if ($delete) {
		$reply=&Apache::lonnet::del
		    ('resourcedata',[keys(%storecontent)],$udom,$uname);
	    } else {
		$reply=&Apache::lonnet::cput
		    ('resourcedata',\%storecontent,$udom,$uname);
	    }
	}

	if ($reply=~/^error\:(.*)/) {
	    $message.="<font color=red>Write Error: $1</font>";
	}
# ---------------------------------------------------------------- Done storing
	$message.='<h3>Changes can take up to 10 minutes before being active for all students</h3>';
    }
# --------------------------------------------- Devalidate cache for this child
    &Apache::lonnet::devalidatecourseresdata(
                 $ENV{'course.'.$ENV{'request.course.id'}.'.num'},
                 $ENV{'course.'.$ENV{'request.course.id'}.'.domain'});
    &Apache::lonnet::clear_EXT_cache_status();
# -------------------------------------------------------------- Get coursedata
    %courseopt = &Apache::lonnet::dump
        ('resourcedata',
         $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
         $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
# --------------------------------------------------- Get userdata (if present)
    if ($uname) {
        %useropt=&Apache::lonnet::dump('resourcedata',$udom,$uname);
    }

# ------------------------------------------------------------------- Sort this

    @ids=sort  {
	if ($fcat eq '') {
	    $a<=>$b;
	} else {
	    my ($result,@outpar)=&parmval($fcat,$a,$defp{$a});
	    my $aparm=$outpar[$result];
	    ($result,@outpar)=&parmval($fcat,$b,$defp{$b});
	    my $bparm=$outpar[$result];
	    1*$aparm<=>1*$bparm;
	}
    } @ids;
#----------------------------------------------- if all selected, fill in array
    if ($pscat[0] eq "all" || !@pscat) {@pscat = (keys %allparms);}
    if ($psprt[0] eq "all" || !@psprt) {@psprt = (keys %allparts);}
# ------------------------------------------------------------------ Start page

    my $have_assesments=1;
    if (scalar(keys(%allkeys)) eq 0) { $have_assesments=0; }

    &startpage($r,$id,$udom,$csec,$uname,$have_assesments);

    if (!$have_assesments) {
	untie(%bighash);
	untie(%parmhash);
	return '';
    }
#    if ($ENV{'form.url'}) {
#	$r->print('<input type="hidden" value="'.$ENV{'form.url'}.
#		  '" name="url"><input type="hidden" name="command" value="set">');
#    }
    $r->print('<input type="hidden" value="true" name="prevvisit">');

    foreach ('tolerance','date_default','date_start','date_end',
	     'date_interval','int','float','string') {
	$r->print('<input type="hidden" value="'.
		  $ENV{'form.recent_'.$_}.'" name="recent_'.$_.'">');
    }

    $r->print('<h2>'.$message.'</h2><table>');
                        
    my $submitmessage;
    if (!$pssymb) {
        $r->print('<tr><td>Select Parameter Level</td><td colspan="2">');
        $r->print('<select name="parmlev">');
        foreach (reverse sort keys %alllevs) {
            $r->print('<option value="'.$alllevs{$_}.'"');
            if ($parmlev eq $alllevs{$_}) {
               $r->print(' selected'); 
            }
            $r->print('>'.$_.'</option>');
        }
        $r->print("</select></td>\n");

        $r->print('</tr>');

        $r->print('<tr><td>Select Enclosing Map or Folder</td>');
        $r->print('<td colspan="2"><select name="pschp">');
        $r->print('<option value="all">All Maps or Folders</option>');
        foreach (sort {$allmaps{$a} cmp $allmaps{$b}} keys %allmaps) {
            $r->print('<option value="'.$_.'"');
            if (($pschp eq $_)) { $r->print(' selected'); }
            $r->print('>'.$maptitles{$_}.($allmaps{$_}!~/^uploaded/?'  ['.$allmaps{$_}.']':'').'</option>');
        }
        $r->print("</select></td></tr>\n");
    } else {
        my ($map,$id,$resource)=split(/___/,$pssymb);
        $r->print("<tr><td>Specific Resource</td><td>$resource</td>");
        $r->print('<td><input type="submit" name="dis" value="'.$submitmessage.'"></td>');
        $r->print('</tr>');
        $r->print('<input type="hidden" value="'.$pssymb.'" name="symb">');
    }

    $r->print('<tr><td colspan="3"><hr /><input type="checkbox"');
    if ($showoptions eq 'show') {$r->print(" checked ");}
    $r->print(' name="showoptions" value="show">Show More Options<hr /></td></tr>');
#    $r->print("<tr><td>Show: $showoptions</td></tr>");
#    $r->print("<tr><td>pscat: @pscat</td></tr>");
#    $r->print("<tr><td>psprt: @psprt</td></tr>");
#    $r->print("<tr><td>fcat:  $fcat</td></tr>");

    if ($showoptions eq 'show') {
        my $tempkey;

        $r->print('<tr><td colspan="3" align="center">Select Parameters to View</td></tr>');

        $r->print('<tr><td colspan="2"><table>');
        $r->print('<tr><td><input type="checkbox" name="pscat" value="all"');
        $r->print(' checked') unless (@pscat);
        $r->print('>All Parameters</td>');

        my $cnt=0;
        foreach $tempkey (sort { $allparms{$a} cmp $allparms{$b} }
                      keys %allparms ) {
            ++$cnt;
            $r->print('</tr><tr>') unless ($cnt%2);
            $r->print('<td><input type="checkbox" name="pscat" ');
            $r->print('value="'.$tempkey.'"');
            if ($pscat[0] eq "all" || grep $_ eq $tempkey, @pscat) {
                $r->print(' checked');
            }
            $r->print('>'.$allparms{$tempkey}.'</td>');
        }
        $r->print('</tr></table>');

#        $r->print('<tr><td>Select Parts</td><td>');
        $r->print('<td><select multiple name="psprt" size="5">');
        $r->print('<option value="all"');
        $r->print(' selected') unless (@psprt);
        $r->print('>All Parts</option>');
        my %temphash=();
        foreach (@psprt) { $temphash{$_}=1; }
        foreach $tempkey (sort keys %allparts) {
            unless ($tempkey =~ /\./) {
                $r->print('<option value="'.$tempkey.'"');
                if ($psprt[0] eq "all" ||  $temphash{$tempkey}) {
                    $r->print(' selected');
                }
                $r->print('>'.$allparts{$tempkey}.'</option>');
            }
        }
        $r->print('</select></td></tr><tr><td colspan="3"><hr /></td></tr>');

        $r->print('<tr><td>Sort list by</td><td>');
        $r->print('<select name="fcat">');
        $r->print('<option value="">Enclosing Map or Folder</option>');
        foreach (sort keys %allkeys) {
            $r->print('<option value="'.$_.'"');
            if ($fcat eq $_) { $r->print(' selected'); }
            $r->print('>'.$allkeys{$_}.'</option>');
        }
        $r->print('</select></td>');

        $r->print('</tr><tr><td colspan="3"><hr /></td></tr>');

    } else { # hide options - include any necessary extras here

        $r->print('<input type="hidden" name="fcat" value="'.$fcat.'">'."\n");

        unless (@pscat) {
          foreach (keys %allparms ) {
            $r->print('<input type="hidden" name="pscat" value="'.$_.'">'."\n");
          }
        } else {
          foreach (@pscat) {
            $r->print('<input type="hidden" name="pscat" value="'.$_.'">'."\n");
          }
        }

        unless (@psprt) {
          foreach (keys %allparts ) {
            $r->print('<input type="hidden" name="psprt" value="'.$_.'">'."\n");
          }
        } else {
          foreach (@psprt) {
            $r->print('<input type="hidden" name="psprt" value="'.$_.'">'."\n");
          }
        }

    }
    $r->print('</table><br />');
    if (($prevvisit) || ($pschp) || ($pssymb)) {
        $submitmessage = "Update Course Assessment Parameter Display";
    } else {
        $submitmessage = "Set Course Assessment Parameters";
    }
    $r->print('<input type="submit" name="dis" value="'.$submitmessage.'">');

#    my @temp_psprt;
#    foreach my $t (@psprt) {
#	push(@temp_psprt, grep {eval (/^$t\./ || ($_ == $t))} (keys %allparts));
#    }

#    @psprt = @temp_psprt;

    my @temp_pscat;
    map {
        my $cat = $_;
        push(@temp_pscat, map { $_.'.'.$cat } @psprt);
    } @pscat;

    @pscat = @temp_pscat;

    if (($prevvisit) || ($pschp) || ($pssymb)) {
# ----------------------------------------------------------------- Start Table
        my @catmarker=map { tr|.|_|; 'parameter_'.$_; } @pscat;
        my $csuname=$ENV{'user.name'};
        my $csudom=$ENV{'user.domain'};

        if ($parmlev eq 'full' || $parmlev eq 'brief') {
           my $coursespan=$csec?8:5;
           $r->print('<p><table border=2>');
           $r->print('<tr><td colspan=5></td>');
           $r->print('<th colspan='.($coursespan).'>Any User</th>');
           if ($uname) {
               $r->print("<th colspan=3 rowspan=2>");
               $r->print("User $uname at Domain $udom</th>");
           }
           $r->print(<<ENDTABLETWO);
<th rowspan=3>Parameter in Effect</th>
<th rowspan=3>Current Session Value<br>($csuname at $csudom)</th>
</tr><tr><td colspan=5></td><th colspan=2>Resource Level</th>
<th colspan=3>in Course</th>
ENDTABLETWO
           if ($csec) {
                $r->print("<th colspan=3>in Section/Group $csec</th>");
           }
           $r->print(<<ENDTABLEHEADFOUR);
</tr><tr><th>Assessment URL and Title</th><th>Type</th>
<th>Enclosing Map or Folder</th><th>Part</th><th>Parameter Name</th>
<th>default</th><th>from Enclosing Map or Folder</th>
<th>general</th><th>for Enclosing Map or Folder</th><th>for Resource</th>
ENDTABLEHEADFOUR

           if ($csec) {
               $r->print('<th>general</th><th>for Enclosing Map or Folder</th><th>for Resource</th>');
           }

           if ($uname) {
               $r->print('<th>general</th><th>for Enclosing Map or Folder</th><th>for Resource</th>');
           }

           $r->print('</tr>');

           my $defbgone='';
           my $defbgtwo='';

           foreach (@ids) {

                my $rid=$_;
                my ($inmapid)=($rid=~/\.(\d+)$/);

                if (($pschp eq 'all') || ($allmaps{$pschp} eq $mapp{$rid}) ||
                    ($pssymb eq $symbp{$rid})) {
# ------------------------------------------------------ Entry for one resource
                    if ($defbgone eq '"E0E099"') {
                        $defbgone='"E0E0DD"';
                    } else {
                        $defbgone='"E0E099"';
                    }
                    if ($defbgtwo eq '"FFFF99"') {
                        $defbgtwo='"FFFFDD"';
                    } else {
                        $defbgtwo='"FFFF99"';
                    }
                    my $thistitle='';
                    my %name=   ();
                    undef %name;
                    my %part=   ();
                    my %display=();
                    my %type=   ();
                    my %default=();
                    my $uri=&Apache::lonnet::declutter($bighash{'src_'.$rid});

                    foreach (split(/\,/,$keyp{$rid})) {
                        my $tempkeyp = $_;
                        if (grep $_ eq $tempkeyp, @catmarker) {
                          $part{$_}=&Apache::lonnet::metadata($uri,$_.'.part');
                          $name{$_}=&Apache::lonnet::metadata($uri,$_.'.name');
                          $display{$_}=&Apache::lonnet::metadata($uri,$_.'.display');
                          unless ($display{$_}) { $display{$_}=''; }
                          $display{$_}.=' ('.$name{$_}.')';
                          $default{$_}=&Apache::lonnet::metadata($uri,$_);
                          $type{$_}=&Apache::lonnet::metadata($uri,$_.'.type');
                          $thistitle=&Apache::lonnet::metadata($uri,$_.'.title');
                        }
                    }
                    my $totalparms=scalar keys %name;
                    if ($totalparms>0) {
                        my $firstrow=1;

                        $r->print('<tr><td bgcolor='.$defbgone.
                             ' rowspan='.$totalparms.
                             '><tt><font size=-1>'.
                             join(' / ',split(/\//,$uri)).
                             '</font></tt><p><b>'.
                             "<a href=\"javascript:openWindow('/res/".$uri.
                             "', 'metadatafile', '450', '500', 'no', 'yes')\";".
                             " TARGET=_self>$bighash{'title_'.$rid}");

                        if ($thistitle) {
                            $r->print(' ('.$thistitle.')');
                        }
                        $r->print('</a></b></td>');
                        $r->print('<td bgcolor='.$defbgtwo.
                                      ' rowspan='.$totalparms.'>'.$typep{$rid}.
                                      '</td>');

                        $r->print('<td bgcolor='.$defbgone.
                                      ' rowspan='.$totalparms.
                                      '><tt><font size=-1>');

                        $r->print(' / res / ');
                        $r->print(join(' / ', split(/\//,$mapp{$rid})));

                        $r->print('</font></tt></td>');

                        foreach (sort keys %name) {
                            unless ($firstrow) {
                                $r->print('<tr>');
                            } else {
                                undef $firstrow;
                            }

                            &print_row($r,$_,\%part,\%name,$rid,\%default,
                                       \%type,\%display,$defbgone,$defbgtwo,
                                       $parmlev);
                        }
                    }
                }
            } # end foreach ids
# -------------------------------------------------- End entry for one resource
            $r->print('</table>');
        } # end of  brief/full
#--------------------------------------------------- Entry for parm level map
        if ($parmlev eq 'map') {
            my $defbgone = '"E0E099"';
            my $defbgtwo = '"FFFF99"';

            my %maplist;

            if ($pschp eq 'all') {
                %maplist = %allmaps; 
            } else {
                %maplist = ($pschp => $mapp{$pschp});
            }

#-------------------------------------------- for each map, gather information
            my $mapid;
	    foreach $mapid (sort {$maplist{$a} cmp $maplist{$b}} keys %maplist) {
                my $maptitle = $maplist{$mapid};

#-----------------------  loop through ids and get all parameter types for map
#-----------------------------------------          and associated information
                my %name = ();
                my %part = ();
                my %display = ();
                my %type = ();
                my %default = ();
                my $map = 0;

#		$r->print("Catmarker: @catmarker<br />\n");
               
                foreach (@ids) {
                  ($map)=(/([\d]*?)\./);
                  my $rid = $_;
        
#                  $r->print("$mapid:$map:   $rid <br /> \n");

                  if ($map eq $mapid) {
                    my $uri=&Apache::lonnet::declutter($bighash{'src_'.$rid});
#                    $r->print("Keys: $keyp{$rid} <br />\n");

#--------------------------------------------------------------------
# @catmarker contains list of all possible parameters including part #s
# $fullkeyp contains the full part/id # for the extraction of proper parameters
# $tempkeyp contains part 0 only (no ids - ie, subparts)
# When storing information, store as part 0
# When requesting information, request from full part
#-------------------------------------------------------------------
                    foreach (split(/\,/,$keyp{$rid})) {
                      my $tempkeyp = $_;
                      my $fullkeyp = $tempkeyp;
                      $tempkeyp =~ s/_\w+_/_0_/;
                      
                      if ((grep $_ eq $fullkeyp, @catmarker) &&(!$name{$tempkeyp})) {
                        $part{$tempkeyp}="0";
                        $name{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp.'.name');
                        $display{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp.'.display');
                        unless ($display{$tempkeyp}) { $display{$tempkeyp}=''; }
                        $display{$tempkeyp}.=' ('.$name{$tempkeyp}.')';
                        $display{$tempkeyp} =~ s/_\w+_/_0_/;
                        $default{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp);
                        $type{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp.'.type');
                      }
                    } # end loop through keys
                  }
                } # end loop through ids
                                 
#---------------------------------------------------- print header information
                my $foldermap=($maptitle=~/^uploaded/?'Folder':'Map');
                my $showtitle=$maptitles{$maptitle}.($maptitle!~/^uploaded/?' ['.$maptitle.']':'');
                $r->print(<<ENDMAPONE);
<center><h4>
<font color="red">Set Defaults for All Resources in $foldermap<br />
<i>$showtitle</i><br />
Specifically for
ENDMAPONE
                if ($uname) {
                    my %name=&Apache::lonnet::userenvironment($udom,$uname,
                      ('firstname','middlename','lastname','generation', 'id'));
                    my $person=$name{'firstname'}.' '.$name{'middlename'}.' '
                           .$name{'lastname'}.' '.$name{'generation'};
                    $r->print("User <i>$uname \($person\) </i> in \n");
                } else {
                    $r->print("<i>all</i> users in \n");
                }
            
                if ($csec) {$r->print("Section <i>$csec</i> of \n")};

                $r->print("<i>$coursename</i><br />");
                $r->print("</font></h4>\n");
#---------------------------------------------------------------- print table
                $r->print('<p><table border="2">');
                $r->print('<tr><th>Parameter Name</th>');
                $r->print('<th>Default Value</th>');
                $r->print('<th>Parameter in Effect</th></tr>');

	        foreach (sort keys %name) {
                    &print_row($r,$_,\%part,\%name,$mapid,\%default,
                           \%type,\%display,$defbgone,$defbgtwo,
                           $parmlev);
#                    $r->print("<tr><td>resource.$part{$_}.$name{$_},$symbp{$mapid}</td></tr>\n");
                }
                $r->print("</table></center>");
            } # end each map
        } # end of $parmlev eq map
#--------------------------------- Entry for parm level general (Course level)
        if ($parmlev eq 'general') {
            my $defbgone = '"E0E099"';
            my $defbgtwo = '"FFFF99"';

#-------------------------------------------- for each map, gather information
            my $mapid="0.0";
#-----------------------  loop through ids and get all parameter types for map
#-----------------------------------------          and associated information
            my %name = ();
            my %part = ();
            my %display = ();
            my %type = ();
            my %default = ();
               
            foreach (@ids) {
                my $rid = $_;
        
                my $uri=&Apache::lonnet::declutter($bighash{'src_'.$rid});

#--------------------------------------------------------------------
# @catmarker contains list of all possible parameters including part #s
# $fullkeyp contains the full part/id # for the extraction of proper parameters
# $tempkeyp contains part 0 only (no ids - ie, subparts)
# When storing information, store as part 0
# When requesting information, request from full part
#-------------------------------------------------------------------
                foreach (split(/\,/,$keyp{$rid})) {
                  my $tempkeyp = $_;
                  my $fullkeyp = $tempkeyp;
                  $tempkeyp =~ s/_\w+_/_0_/;
                  if ((grep $_ eq $fullkeyp, @catmarker) &&(!$name{$tempkeyp})) {
                    $part{$tempkeyp}="0";
                    $name{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp.'.name');
                    $display{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp.'.display');
                    unless ($display{$tempkeyp}) { $display{$tempkeyp}=''; }
                    $display{$tempkeyp}.=' ('.$name{$tempkeyp}.')';
                    $display{$tempkeyp} =~ s/_\w+_/_0_/;
                    $default{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp);
                    $type{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp.'.type');
                  }
                } # end loop through keys
            } # end loop through ids
                                 
#---------------------------------------------------- print header information
            $r->print(<<ENDMAPONE);
<center><h4>
<font color="red">Set Defaults for All Resources in Course
<i>$coursename</i><br />
ENDMAPONE
            if ($uname) {
                my %name=&Apache::lonnet::userenvironment($udom,$uname,
                  ('firstname','middlename','lastname','generation', 'id'));
                my $person=$name{'firstname'}.' '.$name{'middlename'}.' '
                       .$name{'lastname'}.' '.$name{'generation'};
                $r->print(" User <i>$uname \($person\) </i> \n");
            } else {
                $r->print("<i>ALL</i> USERS \n");
            }
            
            if ($csec) {$r->print("Section <i>$csec</i>\n")};
            $r->print("</font></h4>\n");
#---------------------------------------------------------------- print table
            $r->print('<p><table border="2">');
            $r->print('<tr><th>Parameter Name</th>');
            $r->print('<th>Default Value</th>');
            $r->print('<th>Parameter in Effect</th></tr>');

	    foreach (sort keys %name) {
                &print_row($r,$_,\%part,\%name,$mapid,\%default,
                       \%type,\%display,$defbgone,$defbgtwo,$parmlev);
#                    $r->print("<tr><td>resource.$part{$_}.$name{$_},$symbp{$mapid}</td></tr>\n");
            }
            $r->print("</table></center>");
        } # end of $parmlev eq general
    }
    $r->print('</form></body></html>');
    untie(%bighash);
    untie(%parmhash);
} # end sub assessparms


##################################################
##################################################

=pod

=item crsenv

Show and set course data and parameters.  This is a large routine that should
be simplified and shortened... someday.

Inputs: $r

Returns: nothing

=cut

##################################################
##################################################
sub crsenv {
    my $r=shift;
    my $setoutput='';
    my $bodytag=&Apache::loncommon::bodytag(
                             'Set Course Environment Parameters');
    my $dom = $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
    my $crs = $ENV{'course.'.$ENV{'request.course.id'}.'.num'};

    #
    # Go through list of changes
    foreach (keys %ENV) {
        next if ($_!~/^form\.(.+)\_setparmval$/);
        my $name  = $1;
        my $value = $ENV{'form.'.$name.'_value'};
        if ($name eq 'newp') {
            $name = $ENV{'form.newp_name'};
        }
        if ($name eq 'url') {
            $value=~s/^\/res\///;
            my $bkuptime=time;
            my @tmp = &Apache::lonnet::get
                ('environment',['url'],$dom,$crs);
            $setoutput.='Backing up previous URL: '.
                &Apache::lonnet::put
                ('environment',
                 {'top level map backup '.$bkuptime => $tmp[1] },
                 $dom,$crs).
                     '<br>';
        }
        #
        # Deal with modified default spreadsheets
        if ($name =~ /^spreadsheet_default_(classcalc|
                                            studentcalc|
                                            assesscalc)$/x) {
            my $sheettype = $1; 
            if ($sheettype eq 'classcalc') {
                # no need to do anything since viewing the sheet will
                # cause it to be updated. 
            } elsif ($sheettype eq 'studentcalc') {
                # expire all the student spreadsheets
                &Apache::lonnet::expirespread('','','studentcalc');
            } else {
                # expire all the assessment spreadsheets 
                #    this includes non-default spreadsheets, but better to
                #    be safe than sorry.
                &Apache::lonnet::expirespread('','','assesscalc');
                # expire all the student spreadsheets
                &Apache::lonnet::expirespread('','','studentcalc');
            }
        }
        #
        # Deal with the enrollment dates
        if ($name =~ /^default_enrollment_(start|end)_date$/) {
            $value=&Apache::lonhtmlcommon::get_date_from_form($name.'_value');
        }
        #
        # Let the user know we made the changes
        if ($name) {
            my $put_result = &Apache::lonnet::put('environment',
                                                  {$name=>$value},$dom,$crs);
            if ($put_result eq 'ok') {
                $setoutput.='Set <b>'.$name.'</b> to <b>'.$value.'</b>.<br />';
            } else {
                $setoutput.='Unable to set <b>'.$name.'</b> to '.
                    '<b>'.$value.'</b> due to '.$put_result.'.<br />';
            }
        }
    }
# ------------------------- Re-init course environment entries for this session

    &Apache::lonnet::coursedescription($ENV{'request.course.id'});

# -------------------------------------------------------- Get parameters again

    my %values=&Apache::lonnet::dump('environment',$dom,$crs);
    my $output='';
    if (! exists($values{'con_lost'})) {
        my %descriptions=
	    ('url'            => '<b>Top Level Map</b> '.
                                 '<a href="javascript:openbrowser'.
                                 "('envform','url','sequence')\">".
                                 'Select Map</a><br /><font color=red> '.
                                 'Modification may make assessment data '.
                                 'inaccessible</font>',
             'description'    => '<b>Course Description</b>',
             'courseid'       => '<b>Course ID or number</b><br />'.
                                 '(internal, optional)',
             'default_xml_style' => '<b>Default XML Style File</b> '.
                    '<a href="javascript:openbrowser'.
                    "('envform','default_xml_style'".
                    ",'sty')\">Select Style File</a><br>",
             'question.email' => '<b>Feedback Addresses for Resource Content '.
                                 'Questions</b><br />(<tt>user:domain,'.
                                 'user:domain(section;section;...;*;...),...</tt>)',
             'comment.email'  => '<b>Feedback Addresses for Course Content Comments</b><br />'.
                                 '(<tt>user:domain,user:domain(section;section;...;*;...),...</tt>)',
             'policy.email'   => '<b>Feedback Addresses for Course Policy</b>'.
                                 '<br />(<tt>user:domain,user:domain(section;section;...;*;...),...</tt>)',
             'hideemptyrows'  => '<b>Hide Empty Rows in Spreadsheets</b><br />'.
                                 '("<tt>yes</tt>" for default hiding)',
             'pageseparators'  => '<b>Visibly Separate Items on Pages</b><br />'.
                                 '("<tt>yes</tt>" for visible separation, '.
                                 'changes will not show until next login)',
             'pch.roles.denied'=> '<b>Disallow Resource Discussion for '.
                                  'Roles</b><br />"<tt>st</tt>": '.
                                  'student, "<tt>ta</tt>": '.
                                  'TA, "<tt>in</tt>": '.
                                  'instructor;<br /><tt>role,role,...</tt>) '.
	       Apache::loncommon::help_open_topic("Course_Disable_Discussion"),
             'pch.users.denied' => 
                          '<b>Disallow Resource Discussion for Users</b><br />'.
                                 '(<tt>user:domain,user:domain,...</tt>)',
             'spreadsheet_default_classcalc' 
                 => '<b>Default Course Spreadsheet</b> '.
                    '<a href="javascript:openbrowser'.
                    "('envform','spreadsheet_default_classcalc'".
                    ",'spreadsheet')\">Select Spreadsheet File</a><br />",
             'spreadsheet_default_studentcalc' 
                 => '<b>Default Student Spreadsheet</b> '.
                    '<a href="javascript:openbrowser'.
                    "('envform','spreadsheet_default_calc'".
                    ",'spreadsheet')\">Select Spreadsheet File</a><br />",
             'spreadsheet_default_assesscalc' 
                 => '<b>Default Assessment Spreadsheet</b> '.
                    '<a href="javascript:openbrowser'.
                    "('envform','spreadsheet_default_assesscalc'".
                    ",'spreadsheet')\">Select Spreadsheet File</a><br />",
	     'allow_limited_html_in_feedback'
	         => '<b>Allow limited HTML in discussion posts</b><br />'.
	            '(Set value to "<tt>yes</tt>" to allow)',
	     'rndseed'
	         => '<b>Randomization algorithm used</b> <br />'.
                    '<font color="red">Modifying this will make problems '.
                    'have different numbers and answers</font>',
             'problem_stream_switch'
                 => '<b>Allow problems to be split over pages</b><br />'.
                    ' ("<tt>yes</tt>" if allowed, anything else if not)',,
             'anonymous_quiz'
                 => '<b>Anonimous quiz/exam</b><br />'.
                    ' (<tt><b>yes</b> to avoid print students names </tt>)',
             'default_enrollment_start_date' => '<b>Default beginning date '.
                                                'when enrolling students</b>',
             'default_enrollment_end_date'   => '<b>Default ending date '.
                                                'when enrolling students</b>',
             'languages' => '<b>Languages used</b>'
             ); 
        my @Display_Order = ('url','description','courseid',
                             'default_xml_style','pageseparators',
                             'question.email','comment.email','policy.email',
                             'pch.roles.denied','pch.users.denied',
                             'allow_limited_html_in_feedback',
                             'languages',
                             'rndseed',
                             'problem_stream_switch',
                             'spreadsheet_default_classcalc',
                             'spreadsheet_default_studentcalc',
                             'spreadsheet_default_assesscalc', 
                             'hideemptyrows',
                             'default_enrollment_start_date',
                             'default_enrollment_end_date',
                             );
	foreach my $parameter (sort(keys(%values))) {
	    if (! $descriptions{$parameter}) {
                $descriptions{$parameter}=$parameter;
                push(@Display_Order,$parameter);
	    }
	}
        foreach my $parameter (@Display_Order) {
            my $description = $descriptions{$parameter};
            # onchange is javascript to automatically check the 'Set' button.
            my $onchange = 'onFocus="javascript:window.document.forms'.
                "['envform'].elements['".$parameter."_setparmval']".
                '.checked=true;"';
            $output .= '<tr><td>'.$description.'</td>';
            if ($parameter =~ /^default_enrollment_(start|end)_date$/) {
                $output .= '<td>'.
                    &Apache::lonhtmlcommon::date_setter('envform',
                                                        $parameter.'_value',
                                                        $values{$parameter},
                                                        $onchange).
                                                        '</td>';
            } else {
                $output .= '<td>'.
                    &Apache::lonhtmlcommon::textbox($parameter.'_value',
                                                    $values{$parameter},
                                                    40,$onchange).'</td>';
            }
            $output .= '<td>'.
                &Apache::lonhtmlcommon::checkbox($parameter.'_setparmval').
                '</td>';
            $output .= "</tr>\n";
	}
        my $onchange = 'onFocus="javascript:window.document.forms'.
            '[\'envform\'].elements[\'newp_setparmval\']'.
            '.checked=true;"';
	$output.='<tr><td><i>Create New Environment Variable</i><br />'.
	    '<input type="text" size=40 name="newp_name" '.
                $onchange.' /></td><td>'.
            '<input type="text" size=40 name="newp_value" '.
                $onchange.' /></td><td>'.
	    '<input type="checkbox" name="newp_setparmval" /></td></tr>';
    }
    $r->print(<<ENDENV);
<html>
<script type="text/javascript" language="Javascript" >
    var editbrowser;
    function openbrowser(formname,elementname,only,omit) {
        var url = '/res/?';
        if (editbrowser == null) {
            url += 'launch=1&';
        }
        url += 'catalogmode=interactive&';
        url += 'mode=parmset&';
        url += 'form=' + formname + '&';
        if (only != null) {
            url += 'only=' + only + '&';
        } 
        if (omit != null) {
            url += 'omit=' + omit + '&';
        }
        url += 'element=' + elementname + '';
        var title = 'Browser';
        var options = 'scrollbars=1,resizable=1,menubar=0';
        options += ',width=700,height=600';
        editbrowser = open(url,title,options,'1');
        editbrowser.focus();
    }
</script>
<head>
<title>LON-CAPA Course Environment</title>
</head>
$bodytag
<form method="post" action="/adm/parmset" name="envform">
$setoutput
<p>
<table border=2>
<tr><th>Parameter</th><th>Value</th><th>Set?</th></tr>
$output
</table>
<input type="submit" name="crsenv" value="Set Course Environment">
</form>
</body>
</html>    
ENDENV
}

##################################################
##################################################

=pod

=item * handler

Main handler.  Calls &assessparms and &crsenv subroutines.

=cut

##################################################
##################################################
    use Data::Dumper;
sub handler {
    my $r=shift;

    if ($r->header_only) {
	$r->content_type('text/html');
	$r->send_http_header;
	return OK;
    }
    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});

# ----------------------------------------------------- Needs to be in a course

    if (($ENV{'request.course.id'}) && 
	(&Apache::lonnet::allowed('opa',$ENV{'request.course.id'}))) {

        $r->content_type('text/html');
        $r->send_http_header;
 
        $coursename=$ENV{'course.'.$ENV{'request.course.id'}.'.description'};

	unless (($ENV{'form.crsenv'}) || (!$ENV{'request.course.fn'})) {
# --------------------------------------------------------- Bring up assessment
	    &assessparms($r);
# ---------------------------------------------- This is for course environment
	} else {
	    &crsenv($r);
	}
    } else {
# ----------------------------- Not in a course, or not allowed to modify parms
	$ENV{'user.error.msg'}=
	    "/adm/parmset:opa:0:0:Cannot modify assessment parameters";
	return HTTP_NOT_ACCEPTABLE;
    }
    return OK;
}

1;
__END__

=pod

=back

=cut




FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>