File:  [LON-CAPA] / loncom / interface / lonparmset.pm
Revision 1.603: download - view: text, annotated - select for diffs
Mon Jan 3 20:08:24 2022 UTC (2 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Faster table load for single (known) symb.

# The LearningOnline Network with CAPA
# Handler to set parameters for assessments
#
# $Id: lonparmset.pm,v 1.603 2022/01/03 20:08:24 raeburn 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 content parameters in a 
course.

It contains all the code for the "Content and Problem Settings" UI, except
for the helpers parameter.helper and resettimes.helper, and lonhelper.pm,
and lonblockingmenu.pm.

=head1 DESCRIPTION

This module sets coursewide and assessment parameters.

=head1 INTERNAL SUBROUTINES

=over

=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 values that is the active one, the list consists of parm values at the 18 possible levels

18 - General Course
17 - Map or Folder level in course (recursive) 
16 - Map or Folder level in course (non-recursive)
15 - resource default
14 - map default
13 - resource level in course
12 - General for section
11 - Map or Folder level for section (recursive)
10 - Map or Folder level for section (non-recursive)
9 - resource level in section
8 - General for group
7 - Map or Folder level for group (recursive)
6 - Map or Folder level for group (non-recursive)
5 - resource level in group
4 - General for specific student
3 - Map or Folder level for specific student (recursive)
2 - Map or Folder level for specific student (non-recursive)
1 - resource level for specific student

=item parmval_by_symb()

=item reset_caches()

=item cacheparmhash() 

=item parmhash()

=item symbcache()

=item preset_defaults()

=item date_sanity_info()

=item storeparm()

Store a parameter by symb

    Takes
    - symb
    - name of parameter
    - level
    - new value
    - new type
    - username
    - userdomain

=item log_parmset()

=item storeparm_by_symb_inner()

=item valout()

Format a value for output.

Inputs:  $value, $type, $editable

Returns: $value, formatted for output.  If $type indicates it is a date,
localtime($value) is returned.
$editable will return an icon to click on

=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'.

=item page_js()

=item startpage()

=item print_row()

=item print_td()

=item check_other_groups()

=item parm_control_group()

=item extractResourceInformation() : 

 extractResourceInformation extracts lots of information about all of the the course's resources into a variety of hashes.

Input: See list below

=over 4

=item * B<env{'user.name'}> : Current username

=item * B<env{'user.domain'}> : Domain of current user.

=item * B<env{"request.course.fn"}> : Course

=back

Outputs: See list below:

=over 4

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

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

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

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

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

=item * B<allmaps> (out) : hash, ???

=item * B<mapp> : ??

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

=item * B<maptitles>

=item * B<uris>

=item * B<keyorder>

=item * B<defkeytype>

=back

=item isdateparm()

=item parmmenu()

=item partmenu()

=item usermenu()

=item displaymenu()

=item mapmenu()

=item levelmenu()

=item sectionmenu()

=item keysplit()

=item keysinorder()

=item keysinorder_bytype()

=item keysindisplayorder()

=item standardkeyorder()

=item assessparms() : 

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

Inputs: $r - the Apache request object.
  
Returns: nothing

Variables used (guessed by Jeremy):

=over

=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<@catmarker> contains list of all possible parameters including part #s

=item * B<$fullkeyp> contains the full part/id # for the extraction of proper parameters

=item * B<$tempkeyp> contains part 0 only (no ids - ie, subparts)
        When storing information, store as part 0
        When requesting information, request from full part

=back

=item tablestart()

=item tableend()

=item extractuser()

=item parse_listdata_key()

=item listdata()

=item date_interval_selector()

=item get_date_interval_from_form()

=item default_selector()

=item string_selector()

=item dateshift()

=item newoverview()

=item secgroup_lister()

=item overview()

=item clean_parameters()

=item date_shift_one()

=item date_shift_two()

=item parse_key()

=item header()

Output html header for page

=item print_main_menu()

=item output_row()

Set portfolio metadata

=item order_meta_fields()

=item addmetafield()

=item setrestrictmeta()

=item get_added_meta_fieldnames()

=item get_deleted_meta_fieldnames()

=item defaultsetter()

=item components()

=item load_parameter_names()

=item parm_change_log()

=item handler() : 

Main handler.  Calls &assessparms subroutine.

=back

=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;
use Apache::lonlocal;
use Apache::lonnavmaps;
use Apache::longroup;
use Apache::lonrss;
use HTML::Entities;
use LONCAPA qw(:DEFAULT :match);


##################################################
# CONTENT AND PROBLEM SETTINGS HTML PAGE HEADER/FOOTER
##################################################

# Page header
#
# @param {Apache2::RequestRec} $r - Apache request object
# @param {string} $mode - selected tab, 'parmset' for course and problem settings, or 'coursepref' for course settings
# @param {string} $crstype - course type ('Community' for community settings)
sub startSettingsScreen {
    my ($r,$mode,$crstype)=@_;

    my $tabtext = &mt('Course Settings');
    if ($crstype eq 'Community') {
        $tabtext = &mt('Community Settings');
    } 
    $r->print("\n".'<ul class="LC_TabContentBigger" id="main">');
    $r->print("\n".'<li'.($mode eq 'coursepref'?' class="active"':'').'><a href="/adm/courseprefs"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.
                                          $tabtext.
                                          '&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>');

    $r->print("\n".'<li'.($mode eq 'parmset'?' class="active"':'').' id="tabbededitor"><a href="/adm/parmset"><b>'.
                                                                 &mt('Content and Problem Settings').'</b></a></li>');
    $r->print("\n".'</ul>'."\n");
    $r->print('<div class="LC_Box" style="clear:both;margin:0;" id="parameditor"><div id="maincoursedoc" style="margin:0 0;padding:0 0;"><div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">');
}

# Page footer
sub endSettingsScreen {
   my ($r)=@_;
   $r->print('</div></div></div>');
}



##################################################
# (mostly) TABLE MODE
# (parmval is also used for the log of parameter changes)
##################################################

# Calls parmval_by_symb, getting the symb from $id with &symbcache.
#
# @param {string} $what - part info and parameter name separated by a dot, e.g. '0.weight'
# @param {string} $id - resource id or map pc
# @param {string} $def - the resource's default value for this parameter
# @param {string} $uname - user name
# @param {string} $udom - user domain
# @param {string} $csec - section name
# @param {string} $cgroup - group name
# @param {hash reference} $courseopt - course parameters hash (result of lonnet::get_courseresdata, dump of course's resourcedata.db)
# @returns {Array}
sub parmval {
    my ($what,$id,$def,$uname,$udom,$csec,$cgroup,$courseopt)=@_;
    return &parmval_by_symb($what,&symbcache($id),$def,$uname,$udom,$csec,
                                                           $cgroup,$courseopt);
}

# Returns an array containing
# - the most specific level that is defined for that parameter (integer)
# - an array with the level as index and the parameter value as value (when defined)
#   (level 1 is the most specific and will have precedence)
#
# @param {string} $what - part info and parameter name separated by a dot, e.g. '0.weight'
# @param {string} $symb - resource symb or map src
# @param {string} $def - the resource's default value for this parameter
# @param {string} $uname - user name
# @param {string} $udom - user domain
# @param {string} $csec - section name
# @param {string} $cgroup - group name
# @param {hash reference} $courseopt - course parameters hash (result of lonnet::get_courseresdata, dump of course's resourcedata.db)
# @returns {Array}
sub parmval_by_symb {
    my ($what,$symb,$def,$uname,$udom,$csec,$cgroup,$courseopt)=@_;

    my $useropt;
    if ($uname ne '' && $udom ne '') {
        $useropt = &Apache::lonnet::get_userresdata($uname,$udom);
    }

    my $result='';
    my @outpar=();
# ----------------------------------------------------- Cascading lookup scheme
    my $map=(&Apache::lonnet::decode_symb($symb))[0];
    $map = &Apache::lonnet::deversion($map);
    
    # NOTE: some of that code looks redondant with code in lonnavmaps::parmval_real,
    # any change should be reflected there.
    
    my $symbparm=$symb.'.'.$what;
    my $recurseparm=$map.'___(rec).'.$what; 
    my $mapparm=$map.'___(all).'.$what;

    my $grplevel=$env{'request.course.id'}.'.['.$cgroup.'].'.$what;
    my $grplevelr=$env{'request.course.id'}.'.['.$cgroup.'].'.$symbparm;
    my $grpleveli=$env{'request.course.id'}.'.['.$cgroup.'].'.$recurseparm;
    my $grplevelm=$env{'request.course.id'}.'.['.$cgroup.'].'.$mapparm;

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

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


# --------------------------------------------------------- first, check course

# 18 - General Course
    if (defined($$courseopt{$courselevel})) {
        $outpar[18]=$$courseopt{$courselevel};
        $result=18;
    }

# 17 - Map or Folder level in course (recursive) 
    if (defined($$courseopt{$courseleveli})) {
        $outpar[17]=$$courseopt{$courseleveli};
        $result=17;
    }

# 16 - Map or Folder level in course (non-recursive)
    if (defined($$courseopt{$courselevelm})) {
        $outpar[16]=$$courseopt{$courselevelm};
        $result=16;
    }

# ------------------------------------------------------- second, check default

# 15 - resource default
    if (defined($def)) { $outpar[15]=$def; $result=15; }

# ------------------------------------------------------ third, check map parms

    
# 14 - map default
    my $thisparm=&parmhash($symbparm);
    if (defined($thisparm)) { $outpar[14]=$thisparm; $result=14; }

# 13 - resource level in course
    if (defined($$courseopt{$courselevelr})) {
        $outpar[13]=$$courseopt{$courselevelr};
        $result=13;
    }

# ------------------------------------------------------ fourth, back to course
    if ($csec ne '') {
# 12 - General for section
        if (defined($$courseopt{$seclevel})) {
            $outpar[12]=$$courseopt{$seclevel};
            $result=12;
        }
# 11 - Map or Folder level for section (recursive)
        if (defined($$courseopt{$secleveli})) {
            $outpar[11]=$$courseopt{$secleveli};
            $result=11;
        }
# 10 - Map or Folder level for section (non-recursive)
        if (defined($$courseopt{$seclevelm})) {
            $outpar[10]=$$courseopt{$seclevelm};
            $result=10;
        }
# 9 - resource level in section
        if (defined($$courseopt{$seclevelr})) {
            $outpar[9]=$$courseopt{$seclevelr};
            $result=9;
        }
    }
# ------------------------------------------------------ fifth, check course group
    if ($cgroup ne '') {
# 8 - General for group
        if (defined($$courseopt{$grplevel})) {
            $outpar[8]=$$courseopt{$grplevel};
            $result=8;
        }
# 7 - Map or Folder level for group (recursive)
        if (defined($$courseopt{$grpleveli})) {
            $outpar[7]=$$courseopt{$grpleveli};
            $result=7;
        }
# 6 - Map or Folder level for group (non-recursive)
        if (defined($$courseopt{$grplevelm})) {
            $outpar[6]=$$courseopt{$grplevelm};
            $result=6;
        }
# 5 - resource level in group
        if (defined($$courseopt{$grplevelr})) {
            $outpar[5]=$$courseopt{$grplevelr};
            $result=5;
        }
    }

# ---------------------------------------------------------- sixth, check user

    if ($uname ne '') {
# 4 - General for specific student
        if (defined($$useropt{$courselevel})) {
            $outpar[4]=$$useropt{$courselevel};
            $result=4;
        }

# 3 - Map or Folder level for specific student (recursive)
        if (defined($$useropt{$courseleveli})) {
            $outpar[3]=$$useropt{$courseleveli};
            $result=3;
        }

# 2 - Map or Folder level for specific student (non-recursive)
        if (defined($$useropt{$courselevelm})) {
            $outpar[2]=$$useropt{$courselevelm};
            $result=2;
        }

# 1 - resource level for specific student
        if (defined($$useropt{$courselevelr})) {
            $outpar[1]=$$useropt{$courselevelr};
            $result=1;
        }
    }
    return ($result,@outpar);
}



# --- Caches local to lonparmset


# Reset lonparmset caches (called at the beginning and end of the handler).
sub reset_caches {
    &resetparmhash();
    &resetsymbcache();
    &resetrulescache();
}

# cache for map parameters, stored temporarily in $env{'request.course.fn'}_parms.db
# (these parameters come from param elements in .sequence files created with the advanced RAT)
{
    my $parmhashid; # course identifier, to initialize the cache only once for a course
    my %parmhash; # the parameter cache
    # reset map parameter hash
    sub resetparmhash {
        undef($parmhashid);
        undef(%parmhash);
    }

    # dump the _parms.db database into %parmhash
    sub cacheparmhash {
        if ($parmhashid eq  $env{'request.course.fn'}) { return; }
        my %parmhashfile;
        if (tie(%parmhashfile,'GDBM_File',
            $env{'request.course.fn'}.'_parms.db',&GDBM_READER(),0640)) {
            %parmhash=%parmhashfile;
            untie(%parmhashfile);
            $parmhashid=$env{'request.course.fn'};
        }
    }

    # returns a parameter value for an identifier symb.parts.parameter, using the map parameter cache
    sub parmhash {
        my ($id) = @_;
        &cacheparmhash();
        return $parmhash{$id};
    }
}

# cache resource id or map pc -> resource symb or map src, using lonnavmaps to find association
{
    my $symbsid; # course identifier, to initialize the cache only once for a course
    my %symbs; # hash id->symb
    # reset the id->symb cache
    sub resetsymbcache {
        undef($symbsid);
        undef(%symbs);
    }

    # returns the resource symb or map src corresponding to a resource id or map pc
    # (using lonnavmaps and a cache)
    sub symbcache {
        my $id=shift;
        if ($symbsid ne $env{'request.course.id'}) {
            undef(%symbs);
        }
        if (!$symbs{$id}) {
            my $navmap = Apache::lonnavmaps::navmap->new();
            if ($id=~/\./) {
                my $resource=$navmap->getById($id);
                $symbs{$id}=$resource->symb();
            } else {
                my $resource=$navmap->getByMapPc($id);
                $symbs{$id}=&Apache::lonnet::declutter($resource->src());
            }
            $symbsid=$env{'request.course.id'};
        }
        return $symbs{$id};
    }
}

# cache for parameter default actions (stored in parmdefactions.db)
{
    my $rulesid; # course identifier, to initialize the cache only once for a course
    my %rules; # parameter default actions hash
    sub resetrulescache {
        undef($rulesid);
        undef(%rules);
    }

    # returns the value for a given key in the parameter default action hash
    sub rulescache {
        my $id=shift;
        if ($rulesid ne $env{'request.course.id'}
            && !defined($rules{$id})) {
            my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
            my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
            %rules=&Apache::lonnet::dump('parmdefactions',$dom,$crs);
            $rulesid=$env{'request.course.id'};
        }
        return $rules{$id};
    }
}


# Returns the values of the parameter type default action
# "default value when manually setting".
# If none is defined, ('','','','','') is returned.
#
# @param {string} $type - parameter type
# @returns {Array<string>} - (hours, min, sec, value)
sub preset_defaults {
    my $type=shift;
    if (&rulescache($type.'_action') eq 'default') {
        # yes, there is something
        return (&rulescache($type.'_hours'),
            &rulescache($type.'_min'),
            &rulescache($type.'_sec'),
            &rulescache($type.'_value'));
    } else {
        # nothing there or something else
        return ('','','','','');
    }
}


# Checks that a date is after enrollment start date and before
# enrollment end date.
# Returns HTML with a warning if it is not, or the empty string otherwise.
# This is used by both overview and table modes.
#
# @param {integer} $checkdate - the date to check.
# @returns {string} - HTML possibly containing a localized warning message.
sub date_sanity_info {
   my $checkdate=shift;
   unless ($checkdate) { return ''; }
   my $result='';
   my $crsprefix='course.'.$env{'request.course.id'}.'.';
   if ($env{$crsprefix.'default_enrollment_end_date'}) {
      if ($checkdate>$env{$crsprefix.'default_enrollment_end_date'}) {
         $result.='<div class="LC_warning">'
                 .&mt('After course enrollment end!')
                 .'</div>';
      }
   }
   if ($env{$crsprefix.'default_enrollment_start_date'}) {
      if ($checkdate<$env{$crsprefix.'default_enrollment_start_date'}) {
         $result.='<div class="LC_warning">'
                 .&mt('Before course enrollment start!')
                 .'</div>';
      }
   }
# Preparation for additional warnings about dates in the past/future.
# An improved, more context sensitive version is recommended,
# e.g. warn for due and answer dates which are defined before the corresponding open date, etc.
#   if ($checkdate<time) {
#      $result.='<div class="LC_info">'
#              .'('.&mt('in the past').')'
#              .'</div>';
#      }
#   if ($checkdate>time) {
#      $result.='<div class="LC_info">'
#              .'('.&mt('in the future').')'
#              .'</div>';
#      }
   return $result;
}


# Store a parameter value and type by ID, also triggering more parameter changes based on parameter default actions.
#
# @param {string} $sresid - resource id or map pc
# @param {string} $spnam - part info and parameter name separated by a dot or underscore, e.g. '0.weight'
# @param {integer} $snum - level
# @param {string} $nval - new value
# @param {string} $ntype - new type
# @param {string} $uname - username
# @param {string} $udom - userdomain
# @param {string} $csec - section name
# @param {string} $cgroup - group name
sub storeparm {
    my ($sresid,$spnam,$snum,$nval,$ntype,$uname,$udom,$csec,$cgroup)=@_;
    &storeparm_by_symb(&symbcache($sresid),$spnam,$snum,$nval,$ntype,$uname,$udom,$csec,'',$cgroup);
}

my %recstack; # hash parameter name -> 1 when a parameter was used before in a recursive call to storeparm_by_symb

# Store a parameter value and type by symb, also triggering more parameter changes based on parameter default actions.
# Uses storeparm_by_symb_inner to actually store the parameter, ignoring any returned error.
#
# @param {string} $symb - resource symb or map src
# @param {string} $spnam - part info and parameter name separated by a dot or underscore, e.g. '0.weight'
# @param {integer} $snum - level
# @param {string} $nval - new value
# @param {string} $ntype - new type
# @param {string} $uname - username
# @param {string} $udom - userdomain
# @param {string} $csec - section name
# @param {boolean} $recflag - should be true for recursive calls to storeparm_by_symb, false otherwise
# @param {string} $cgroup - group name
sub storeparm_by_symb {
    my ($symb,$spnam,$snum,$nval,$ntype,$uname,$udom,$csec,$recflag,$cgroup)=@_;
    unless ($recflag) {
        # first time call
        %recstack=();
        $recflag=1;
    }
    # store parameter
    &storeparm_by_symb_inner
    ($symb,$spnam,$snum,$nval,$ntype,$uname,$udom,$csec,$cgroup);
    # don't do anything if parameter was reset
    unless ($nval) { return; }
    my ($prefix,$parm)=($spnam=~/^(.*[\_\.])([^\_\.]+)$/);
    # remember that this was set
    $recstack{$parm}=1;
    # what does this trigger?
    foreach my $triggered (split(/\:/,&rulescache($parm.'_triggers'))) {
        # don't backfire
        unless ((!$triggered) || ($recstack{$triggered})) {
            my $action=&rulescache($triggered.'_action');
            my ($whichaction,$whichparm)=($action=~/^(.*\_)([^\_]+)$/);
            # set triggered parameter on same level
            my $newspnam=$prefix.$triggered;
            my $newvalue='';
            my $active=1;
            if ($action=~/^when\_setting/) {
            # are there restrictions?
                if (&rulescache($triggered.'_triggervalue')=~/\w/) {
                    $active=0;
                    foreach my $possiblevalue (split(/\s*\,\s*/,&rulescache($triggered.'_triggervalue'))) {
                        if (lc($possiblevalue) eq lc($nval)) { $active=1; }
                    }
                }
                $newvalue=&rulescache($triggered.'_value');
            } else {
                my $totalsecs=((&rulescache($triggered.'_days')*24+&rulescache($triggered.'_hours'))*60+&rulescache($triggered.'_min'))*60+&rulescache($triggered.'_sec');
                if ($action=~/^later\_than/) {
                    $newvalue=$nval+$totalsecs;
                } else {
                    $newvalue=$nval-$totalsecs;
                }
            }
            if ($active) {
                &storeparm_by_symb($symb,$newspnam,$snum,$newvalue,&rulescache($triggered.'_type'),
                        $uname,$udom,$csec,$recflag,$cgroup);
            }
        }
    }
    return '';
}

# Adds all given arguments to the course parameter log.
# @returns {string} - the answer to the lonnet query.
sub log_parmset {
    return &Apache::lonnet::write_log('course','parameterlog',@_);
}

# Store a parameter value and type by symb, without using the parameter default actions.
# Expire related sheets.
#
# @param {string} $symb - resource symb or map src
# @param {string} $spnam - part info and parameter name separated by a dot, e.g. '0.weight'
# @param {integer} $snum - level
# @param {string} $nval - new value
# @param {string} $ntype - new type
# @param {string} $uname - username
# @param {string} $udom - userdomain
# @param {string} $csec - section name
# @param {string} $cgroup - group name
# @returns {string} - HTML code with an error message if the parameter could not be stored.
sub storeparm_by_symb_inner {
# ---------------------------------------------------------- Get symb, map, etc
    my ($symb,$spnam,$snum,$nval,$ntype,$uname,$udom,$csec,$cgroup)=@_;
# ---------------------------------------------------------- Construct prefixes
    $spnam=~s/\_([^\_]+)$/\.$1/;
    my $map=(&Apache::lonnet::decode_symb($symb))[0];
    $map = &Apache::lonnet::deversion($map);

    my $symbparm=$symb.'.'.$spnam;
    my $recurseparm=$map.'___(rec).'.$spnam;
    my $mapparm=$map.'___(all).'.$spnam;

    my $grplevel=$env{'request.course.id'}.'.['.$cgroup.'].'.$spnam;
    my $grplevelr=$env{'request.course.id'}.'.['.$cgroup.'].'.$symbparm;
    my $grpleveli=$env{'request.course.id'}.'.['.$cgroup.'].'.$recurseparm;
    my $grplevelm=$env{'request.course.id'}.'.['.$cgroup.'].'.$mapparm;

    my $seclevel=$env{'request.course.id'}.'.['.$csec.'].'.$spnam;
    my $seclevelr=$env{'request.course.id'}.'.['.$csec.'].'.$symbparm;
    my $secleveli=$env{'request.course.id'}.'.['.$csec.'].'.$recurseparm;
    my $seclevelm=$env{'request.course.id'}.'.['.$csec.'].'.$mapparm;

    my $courselevel=$env{'request.course.id'}.'.'.$spnam;
    my $courselevelr=$env{'request.course.id'}.'.'.$symbparm;
    my $courseleveli=$env{'request.course.id'}.'.'.$recurseparm;
    my $courselevelm=$env{'request.course.id'}.'.'.$mapparm;

    my $storeunder='';
    my $possreplace='';
    if (($snum==18) || ($snum==4)) { $storeunder=$courselevel; }
    if (($snum==17) || ($snum==3)) { 
        $storeunder=$courseleveli;
        $possreplace=$courselevelm; 
    } 
    if (($snum==16) || ($snum==2)) { 
        $storeunder=$courselevelm;
        $possreplace=$courseleveli;
    }
    if (($snum==13) || ($snum==1)) { $storeunder=$courselevelr; }
    if ($snum==12) { $storeunder=$seclevel; }
    if ($snum==11) { 
        $storeunder=$secleveli;
        $possreplace=$seclevelm; 
    }
    if ($snum==10) { 
        $storeunder=$seclevelm;
        $possreplace=$secleveli;
    }
    if ($snum==9) { $storeunder=$seclevelr; }
    if ($snum==8) { $storeunder=$grplevel; }
    if ($snum==7) { 
        $storeunder=$grpleveli;
        $possreplace=$grplevelm;
    }
    if ($snum==6) {
        $storeunder=$grplevelm;
        $possreplace=$grpleveli;
    }
    if ($snum==5) { $storeunder=$grplevelr; }


    my $delete;
    if ($nval eq '') { $delete=1;}
    my %storecontent = ($storeunder         => $nval,
            $storeunder.'.type' => $ntype);
    my $reply='';
    
    if ($snum>4) {
# ---------------------------------------------------------------- Store Course
#
        my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        # Expire sheets
        &Apache::lonnet::expirespread('','','studentcalc');
        if (($snum==13) || ($snum==9) || ($snum==5)) {
            &Apache::lonnet::expirespread('','','assesscalc',$symb);
        } elsif (($snum==17) || ($snum==16) || ($snum==11) || ($snum==10) || ($snum==7) || ($snum==6)) {
            &Apache::lonnet::expirespread('','','assesscalc',$map);
        } else {
            &Apache::lonnet::expirespread('','','assesscalc');
        }
        # Store parameter
        if ($delete) {
            $reply=&Apache::lonnet::del
            ('resourcedata',[keys(%storecontent)],$cdom,$cnum);
                &log_parmset(\%storecontent,1);
        } else {
            $reply=&Apache::lonnet::cput
            ('resourcedata',\%storecontent,$cdom,$cnum);
            &log_parmset(\%storecontent);
            if ($possreplace) {
                my $resdata = &Apache::lonnet::get_courseresdata($cnum,$cdom);
                if (ref($resdata) eq 'HASH') {
                    if (exists($resdata->{$possreplace})) {
                        if (&Apache::lonnet::del
                            ('resourcedata',[$possreplace,$possreplace.'.type'],$cdom,$cnum) eq 'ok') {
                            &log_parmset({$possreplace => '', $possreplace.'.type' => $ntype},1);   
                        }
                    }
                }
            }
        }
        &Apache::lonnet::devalidatecourseresdata($cnum,$cdom);
    } else {
# ------------------------------------------------------------------ Store User
#
        # Expire sheets
        &Apache::lonnet::expirespread($uname,$udom,'studentcalc');
        if ($snum==1) {
            &Apache::lonnet::expirespread
            ($uname,$udom,'assesscalc',$symb);
        } elsif (($snum==2) || ($snum==3)) {
            &Apache::lonnet::expirespread
            ($uname,$udom,'assesscalc',$map);
        } else {
            &Apache::lonnet::expirespread($uname,$udom,'assesscalc');
        }
        # Store parameter
        if ($delete) {
            $reply=&Apache::lonnet::del
            ('resourcedata',[keys(%storecontent)],$udom,$uname);
            &log_parmset(\%storecontent,1,$uname,$udom);
        } else {
            $reply=&Apache::lonnet::cput
            ('resourcedata',\%storecontent,$udom,$uname);
            &log_parmset(\%storecontent,0,$uname,$udom);
            if ($possreplace) {
                my $resdata = &Apache::lonnet::get_userresdata($uname,$udom);
                if (ref($resdata) eq 'HASH') {
                    if (exists($resdata->{$possreplace})) {
                        if (&Apache::lonnet::del
                            ('resourcedata',[$possreplace,$possreplace.'.type'],$udom,$uname) eq 'ok') {
                            &log_parmset({$possreplace => '',$possreplace.'.type' => $ntype},1,
                                          $uname,$udom);
                        }
                    }
                }
            }
        }
        &Apache::lonnet::devalidateuserresdata($uname,$udom);
    }

    if ($reply=~/^error\:(.*)/) {
        return "<span class=\"LC_error\">Write Error: $1</span>";
    }
    return '';
}


# Returns HTML with the value of the given parameter,
# using a readable format for dates, and
# a warning if there is a problem with a date.
# Used by table mode.
# Returns HTML for the editmap.png image if no value is defined and $editable is true.
#
# @param {string} $value - the parameter value
# @param {string} $type - the parameter type
# @param {boolean} $editable - Set to true to get an icon when no value is defined.
sub valout {
    my ($value,$type,$editable)=@_;
    my $result = '';
    # Values of zero are valid.
    if (! $value && $value ne '0') {
        if ($editable) {
            $result =
                '<img src="/res/adm/pages/editmap.png"'
               .' alt="'.&mt('Change').'"'
               .' title="'.&mt('Change').'" style="border:0;" />';
        } else {
            $result='&nbsp;';
        }
    } else {
        if ($type eq 'date_interval') {
            my ($totalsecs,$donesuffix) = split(/_/,$value,2);
            my ($usesdone,$donebuttontext,$proctor,$secretkey);
            if ($donesuffix =~ /^done\:([^\:]+)\:(.*)$/) {
                $donebuttontext = $1;
                (undef,$proctor,$secretkey) = split(/_/,$2);
                $usesdone = 'done';
            } elsif ($donesuffix =~ /^done(|_.+)$/) {
                $donebuttontext = &mt('Done');
                ($usesdone,$proctor,$secretkey) = split(/_/,$donesuffix);
            }
            my ($sec,$min,$hour,$mday,$mon,$year)=gmtime($totalsecs);
            my @timer;
            $year=$year-70;
            $mday--;
            if ($year) {
#               $result.=&mt('[quant,_1,yr]',$year).' ';
                push(@timer,&mt('[quant,_1,yr]',$year));
            }
            if ($mon) {
#               $result.=&mt('[quant,_1,mth]',$mon).' ';
                push(@timer,&mt('[quant,_1,mth]',$mon));
            }
            if ($mday) {
#               $result.=&mt('[quant,_1,day]',$mday).' ';
                push(@timer,&mt('[quant,_1,day]',$mday));
            }
            if ($hour) {
#               $result.=&mt('[quant,_1,hr]',$hour).' ';
                push(@timer,&mt('[quant,_1,hr]',$hour));
            }
            if ($min) {
#               $result.=&mt('[quant,_1,min]',$min).' ';
                push(@timer,&mt('[quant,_1,min]',$min));
            }
            if ($sec) {
#               $result.=&mt('[quant,_1,sec]',$sec).' ';
                push(@timer,&mt('[quant,_1,sec]',$sec));
            }
#           $result=~s/\s+$//;
            if (!@timer) { # Special case: all entries 0 -> display "0 secs" intead of empty field to keep this field editable
                push(@timer,&mt('[quant,_1,sec]',0));
            }
            $result.=join(", ",@timer);
            if ($usesdone eq 'done') {
                if ($secretkey) {
                    $result .= ' '.&mt('+ "[_1]" with proctor key: [_2]',$donebuttontext,$secretkey);  
                } else {
                    $result .= ' + "'.$donebuttontext.'"';
                }
            }
        } elsif (&isdateparm($type)) {
            $result = &Apache::lonlocal::locallocaltime($value).
                &date_sanity_info($value);
        } else {
            $result = $value;
            $result=~s/\,/\, /gs;
            $result = &HTML::Entities::encode($result,'"<>&');
        }
    }
    return $result;
}


# Returns HTML containing a link on a parameter value, for table mode.
# The link uses the javascript function 'pjump'.
#
# @param {string} $type - parameter type
# @param {string} $dis - dialog title for editing the parameter value and type
# @param {string} $value - parameter value
# @param {string} $marker - identifier for the parameter, "resource id&part_parameter name&level", will be passed as pres_marker when the user submits a change.
# @param {string} $return - prefix for the name of the form and field names that will be used to submit the form ('parmform.pres')
# @param {string} $call - javascript function to call to submit the form ('psub')
# @param {boolean} $recursive - true if link is for a map/folder where parameter is currently set to be recursive.
# @param {string} $extra - optional additional information to send as tenth arg in call to javascript pjump function.
sub plink {
    my ($type,$dis,$value,$marker,$return,$call,$recursive,$extra)=@_;
    my $winvalue=$value;
    unless ($winvalue) {
        if (&isdateparm($type) || (&is_specialstring($type))) {
            $winvalue=$env{'form.recent_'.$type};
        } elsif ($type eq 'string_yesno') {
            if ($env{'form.recent_string'} =~ /^(yes|no)$/i) {
                $winvalue=$env{'form.recent_string'};
            }
        } else {
            $winvalue=$env{'form.recent_'.(split(/\_/,$type))[0]};
        }
    }
    my ($parmname)=((split(/\&/,$marker))[1]=~/\_([^\_]+)$/);
    my ($hour,$min,$sec,$val)=&preset_defaults($parmname);
    unless (defined($winvalue)) { $winvalue=$val; }
    my $valout = &valout($value,$type,1);
    my $unencmarker = $marker;
    foreach my $item (\$type, \$dis, \$winvalue, \$marker, \$return, \$call,
              \$hour, \$min, \$sec, \$extra) {
        $$item = &HTML::Entities::encode($$item,'"<>&');
        $$item =~ s/\'/\\\'/g;
    }
    return '<table width="100%"><tr valign="top" align="right"><td><a name="'.$unencmarker.'" /></td></tr><tr><td align="center">'.
    '<a href="javascript:pjump('."'".$type."','".$dis."','".$winvalue."','"
        .$marker."','".$return."','".$call."','".$hour."','".$min."','".$sec."','".$extra."'".');">'.
        $valout.'</a></td></tr>'.($recursive?'<tr><td align="center" class="LC_parm_recursive">'.
                                              &mt('recursive').'</td></tr>' : '').'</table>';

}

# Javascript for table mode.
sub page_js {

    my $selscript=&Apache::loncommon::studentbrowser_javascript();
    my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();

    return(<<ENDJS);
<script type="text/javascript">
// <![CDATA[

    $pjump_def

    function psub() {
        var specstring = /^string_!(yesno|any)/i;
        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') || 
                    (specstring.test(document.parmform.pres_type.value)))  {
                    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
ENDJS

}

# Javascript to show or hide the map selection (function showHide_courseContent),
# for table and overview modes.
sub showhide_js {
    return <<"COURSECONTENTSCRIPT";

function showHide_courseContent() {
    var parmlevValue=document.getElementById("parmlev").value;
    if (parmlevValue == 'general') {
        document.getElementById('mapmenu').style.display="none";
    } else {
        if ((parmlevValue == "full") || (parmlevValue == "map")) {
            document.getElementById('mapmenu').style.display ="";
        } else {
            document.getElementById('mapmenu').style.display="none";
        }
    }
    return;
}

COURSECONTENTSCRIPT
}

# Javascript functions showHideLenient and toggleParmTextbox, for overview mode
sub toggleparmtextbox_js {
    return <<"ENDSCRIPT";

if (!document.getElementsByClassName) {
    function getElementsByClassName(node, classname) {
        var a = [];
        var re = new RegExp('(^| )'+classname+'( |$)');
        var els = node.getElementsByTagName("*");
        for(var i=0,j=els.length; i<j; i++)
            if(re.test(els[i].className))a.push(els[i]);
        return a;
    }
}

function showHideLenient() {
    var lenients;
    var setRegExp = /^set_/;
    if (document.getElementsByClassName) {
        lenients = document.getElementsByClassName('LC_lenient_radio');
    } else {
        lenients = getElementsByClassName(document.body,'LC_lenient_radio');
    }
    if (lenients != 'undefined') {
        for (var i=0; i<lenients.length; i++) {
            if (lenients[i].checked) {
                if (lenients[i].value == 'weighted') {
                    if (setRegExp.test(lenients[i].name)) {
                        var identifier = lenients[i].name.replace(setRegExp,'');
                        toggleParmTextbox(document.parmform,identifier);
                    }
                }
            }
        }
    }
    return;
}

function toggleParmTextbox(form,key) {
    var divfortext = document.getElementById('LC_parmtext_'+key);
    if (divfortext) {
        var caller = form.elements['set_'+key];
        if (caller.length) {
            for (i=0; i<caller.length; i++) {
                if (caller[i].checked) {
                    if (caller[i].value == 'weighted') {
                        divfortext.style.display = 'inline';
                    } else {
                        divfortext.style.display = 'none';
                    }
                }
            }
        }
    }
    return;
}

ENDSCRIPT
}

# Javascript function validateParms, for overview mode
sub validateparms_js {
    return <<'ENDSCRIPT';

function validateParms() {
    var textRegExp = /^settext_/;
    var tailLenient = /\.lenient$/;
    var patternRelWeight = /^\-?[\d.]+$/;
    var patternLenientStd = /^(yes|no|default)$/;
    var ipRegExp = /^setip/;
    var ipallowRegExp = /^setipallow_/;
    var ipdenyRegExp = /^setipdeny_/; 
    var deeplinkRegExp = /^deeplink_/;
    var dlListScopeRegExp = /^deeplink_(state|others|listing|scope)_/; 
    var dlLinkProtectRegExp = /^deeplink_protect_/;
    var dlLtidRegExp = /^deeplink_ltid_/;
    var dlLticRegExp = /^deeplink_ltic_/;
    var dlKeyRegExp = /^deeplink_key_/;
    var dlMenusRegExp = /^deeplink_menus_/;
    var dlCollsRegExp = /^deeplink_colls_/;
    var patternIP = /[\[\]\*\.a-zA-Z\d\-]+/;
    if ((document.parmform.elements.length != 'undefined')  && (document.parmform.elements.length) != 'null') {
        if (document.parmform.elements.length) {
            for (i=0; i<document.parmform.elements.length; i++) {
                var name=document.parmform.elements[i].name;
                if (textRegExp.test(name)) {
                    var identifier = name.replace(textRegExp,'');
                    if (tailLenient.test(identifier)) {
                        if (document.parmform.elements['set_'+identifier].length) {
                            for (var j=0; j<document.parmform.elements['set_'+identifier].length; j++) {
                                if (document.parmform.elements['set_'+identifier][j].checked) {
                                    if (!(patternLenientStd.test(document.parmform.elements['set_'+identifier][j].value))) {
                                        var relweight = document.parmform.elements[i].value;
                                        relweight = relweight.replace(/^\s+|\s+$/g,'');
                                        if (!patternRelWeight.test(relweight)) {
                                            relweight = '0.0';
                                        }
                                        if (document.parmform.elements['set_'+identifier][j].value == 'weighted') {
                                            document.parmform.elements['set_'+identifier][j].value = relweight;
                                        } else {
                                            document.parmform.elements['set_'+identifier][j].value += ','+relweight;
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                } else if (ipRegExp.test(name)) {
                    if (ipallowRegExp.test(name)) {
                        var identifier = name.replace(ipallowRegExp,'');
                        var possallow = document.parmform.elements[i].value;
                        possallow = possallow.replace(/^\s+|\s+$/g,'');
                        if (patternIP.test(possallow)) {
                            if (document.parmform.elements['set_'+identifier].value) {
                                possallow = ','+possallow;
                            }
                            document.parmform.elements['set_'+identifier].value += possallow;
                        }
                    } else if (ipdenyRegExp.test(name)) {
                        var identifier = name.replace(ipdenyRegExp,'');
                        var possdeny = document.parmform.elements[i].value;
                        possdeny = possdeny.replace(/^\s+|\s+$/g,'');
                        if (patternIP.test(possdeny)) {
                            possdeny = '!'+possdeny;
                            if (document.parmform.elements['set_'+identifier].value) {
                                possdeny = ','+possdeny;
                            }
                            document.parmform.elements['set_'+identifier].value += possdeny;
                        }
                    }
                } else if (deeplinkRegExp.test(name)) {
                    if (dlListScopeRegExp.test(name)) {
                        var identifier =  name.replace(dlListScopeRegExp,'');
                        var idx = document.parmform.elements[i].selectedIndex;
                        if (idx > 0) { 
                            var possdeeplink = document.parmform.elements[i].options[idx].value
                            possdeeplink = possdeeplink.replace(/^\s+|\s+$/g,'');
                            if (document.parmform.elements['set_'+identifier].value) {
                                possdeeplink = ','+possdeeplink;
                            }
                            document.parmform.elements['set_'+identifier].value += possdeeplink;
                        }
                    } else if (dlLinkProtectRegExp.test(name)) {
                        if (document.parmform.elements[i].checked) {
                            var identifier =  name.replace(dlLinkProtectRegExp,'');
                            var posslinkurl = document.parmform.elements[i].value;
                            posslinkurl = posslinkurl.replace(/^\s+|\s+$/g,'');
                            if (document.parmform.elements['set_'+identifier].value) {
                                posslinkurl = ','+posslinkurl;
                            }
                            document.parmform.elements['set_'+identifier].value += posslinkurl;
                        }
                    } else if (dlLtidRegExp.test(name)) {
                        var identifier = name.replace(dlLtidRegExp,'');
                        if (isRadioSet('deeplink_protect_'+identifier,'ltid')) {
                            var possltid = document.parmform.elements[i].value;
                            possltid = possltid.replace(/\D+/g,'');
                            if (possltid.length) {
                                if (document.parmform.elements['set_'+identifier].value) {
                                    possltid = ':'+possltid;
                                }
                                document.parmform.elements['set_'+identifier].value += possltid;
                            } else {
                                document.parmform.elements['set_'+identifier].value = '';
                                alert("A link type of 'domain LTI launch' was selected but no domain LTI launcher was selected.\nPlease select one, or choose a different supported link type.");
                                return false;  
                            }
                        }
                    } else if (dlLticRegExp.test(name)) {
                        var identifier = name.replace(dlLticRegExp,'');
                        if (isRadioSet('deeplink_protect_'+identifier,'ltic')) {
                            var possltic = document.parmform.elements[i].value;
                            possltic = possltic.replace(/\D+/g,'');
                            if (possltic.length) {
                                if (document.parmform.elements['set_'+identifier].value) {
                                    possltic = ':'+possltic;
                                }
                                document.parmform.elements['set_'+identifier].value += possltic;
                            } else {
                                document.parmform.elements['set_'+identifier].value = '';
                                alert("A link type of 'course LTI launch' was selected but no course LTI launcher was selected.\nPlease select one, or choose a different supported link type.");
                                return false;
                            }
                        }
                    } else if (dlKeyRegExp.test(name)) {
                        var identifier = name.replace(dlKeyRegExp,'');
                        if (isRadioSet('deeplink_protect_'+identifier,'key')) {
                            var posskey = document.parmform.elements[i].value;
                            posskey = posskey.replace(/^\s+|\s+$/g,'');
                            var origlength = posskey.length;
                            posskey = posskey.replace(/[^a-zA-Z\d_.!@#$%^&*()+=-]/g,'');
                            var newlength = posskey.length;
                            if (newlength > 0) {
                                var change = origlength - newlength;
                                if (change) {
                                    alert(change+' disallowed character(s) removed from deeplink key'); 
                                }
                                if (document.parmform.elements['set_'+identifier].value) {
                                    posskey = ':'+posskey;
                                }
                                document.parmform.elements['set_'+identifier].value += posskey;
                            } else {
                                document.parmform.elements['set_'+identifier].value = '';
                                if (newlength < origlength) {
                                    alert("A link type of 'deep with key' was selected but the key value was blank, after removing disallowed characters.\nPlease enter a key using one or more of: a-zA-Z0-9_.!@#$%^&*()+=-");
                                } else {
                                    alert("A link type of 'deep with key' was selected but the key value was blank.\nPlease enter a key.");
                                }
                                return false;
                            }
                        }
                    } else if (dlMenusRegExp.test(name)) {
                        if (document.parmform.elements[i].checked) {
                            var identifier =  name.replace(dlMenusRegExp,'');
                            var posslinkmenu = document.parmform.elements[i].value;
                            posslinkmenu = posslinkmenu.replace(/^\s+|\s+$/g,'');
                            if (posslinkmenu == 'std') {
                                posslinkmenu = '0';
                                if (document.parmform.elements['set_'+identifier].value) {
                                    posslinkmenu = ','+posslinkmenu;
                                }
                                document.parmform.elements['set_'+identifier].value += posslinkmenu;
                            }
                        }
                    } else if (dlCollsRegExp.test(name)) {
                        var identifier =  name.replace(dlCollsRegExp,'');
                        if (isRadioSet('deeplink_menus_'+identifier,'colls')) {
                            var posslinkmenu = document.parmform.elements[i].value;
                            if (document.parmform.elements['set_'+identifier].value) {
                                posslinkmenu = ','+posslinkmenu;
                            }
                            document.parmform.elements['set_'+identifier].value += posslinkmenu;
                        }
                    }
                }
            }
        }
    }
    return true;
}

function isRadioSet(name,expected) {
    var menuitems = document.getElementsByName(name);
    var radioLength = menuitems.length;
    result = false;
    if (radioLength  > 1) {
        for (var j=0; j<radioLength; j++) {
            if (menuitems[j].checked) {
                if (menuitems[j].value == expected) {
                    result = true;
                    break;
                }
            }
        }
    }
    return result;
}

ENDSCRIPT
}

# Javascript initialization, for overview mode
sub ipacc_boxes_js  {
    my $remove = &mt('Remove');
    return <<"END";
\$(document).ready(function() {
    var wrapper         = \$(".LC_string_ipacc_wrap");
    var add_button      = \$(".LC_add_ipacc_button");
    var ipaccRegExp     = /^LC_string_ipacc_/;

    \$(add_button).click(function(e){
        e.preventDefault();
        var identifier = \$(this).closest("div").attr("id");
        identifier = identifier.replace(ipaccRegExp,'');
        \$(this).closest('div').find('.LC_string_ipacc_inner').append('<div><input type="text" name="setip'+identifier+'" /><a href="#" class="LC_remove_ipacc">$remove</a></div>');
    });

    \$(wrapper).delegate(".LC_remove_ipacc","click", function(e){
        e.preventDefault(); \$(this).closest("div").remove();
    })
});


END
}

# Javascript function toggleSecret, for overview mode.
sub done_proctor_js {
    return <<"END";
function toggleSecret(form,radio,key) {
    var radios = form[radio+key];
    if (radios.length) {
        for (var i=0; i<radios.length; i++) {
            if (radios[i].checked) {
                if (radios[i].value == '_done_proctor') {
                    if (document.getElementById('done_'+key+'_proctorkey')) {
                        document.getElementById('done_'+key+'_proctorkey').type='text';
                    }
                } else {
                    if (document.getElementById('done_'+key+'_proctorkey')) {
                        document.getElementById('done_'+key+'_proctorkey').type='hidden';
                        document.getElementById('done_'+key+'_proctorkey').value='';
                    }
                }
            }
        }
    }
}
END

}

# Javascript function toggle
sub deeplink_js {
    return <<"END";
function toggleDeepLink(form,item,key) {
    var radios = form['deeplink_'+item+'_'+key];
    if (radios.length) {
        var keybox;
        if (document.getElementById('deeplink_key_'+item+'_'+key)) {
            keybox = document.getElementById('deeplink_key_'+item+'_'+key);
        }
        var divoptions = new Array();
        if (item == 'protect') {
            divoptions = ['ltic','ltid'];
        } else {
            if (item == 'menus') {
                divoptions = ['colls'];
            }
        }
        var seldivs = new Array();
        if ((item == 'protect') || (item == 'menus')) {
            for (var i=0; i<divoptions.length; i++) {
                if (document.getElementById('deeplinkdiv_'+divoptions[i]+'_'+item+'_'+key)) {
                    seldivs[i] = document.getElementById('deeplinkdiv_'+divoptions[i]+'_'+item+'_'+key);
                } else {
                    seldivs[i] = '';
                }
            }
        }
        for (var i=0; i<radios.length; i++) {
            if (radios[i].checked) {
                if ((item == 'protect') || (item == 'menus')) {
                    for (var j=0; j<seldivs.length; j++) {
                        if (radios[i].value == divoptions[j]) {
                            if (seldivs[j] != '') {
                                seldivs[j].style.display = 'inline-block';
                            }
                            if (item == 'protect') {
                                keybox.type = 'hidden';
                                keybox.value = '';
                            }
                        } else {
                            if (seldivs[j] != '') {
                                seldivs[j].style.display = 'none';
                                form['deeplink_'+divoptions[j]+'_'+key].selectedIndex = 0;
                            }
                        }
                    }
                    if (item == 'protect') {
                        if (radios[i].value == 'key') {
                            keybox.type = 'text';
                        } else {
                            keybox.type = 'hidden';
                        }
                    }
                }
            }
        }
    }
}
END

}

# Prints HTML page start for table mode.
# @param {Apache2::RequestRec} $r - the Apache request
# @param {string} $psymb - resource symb
# @param {string} $crstype - course type (Community / Course / Placement Test)
sub startpage {
    my ($r,$psymb,$crstype) = @_;

    my %loaditems = (
                      'onload'   => "group_or_section('cgroup')",
                    );
    if (!$psymb) {
        $loaditems{'onload'} = "showHide_courseContent(); group_or_section('cgroup'); resize_scrollbox('mapmenuscroll','1','1');";
    }

    if ((($env{'form.command'} eq 'set') && ($env{'form.url'}) &&
            (!$env{'form.dis'})) || ($env{'form.symb'})) {
        &Apache::lonhtmlcommon::add_breadcrumb({help=>'Problem_Parameters',
            text=>"Problem Parameters"});
    } else {
        &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/parmset?action=settable',
            text=>"Table Mode",
            help => 'Course_Setting_Parameters'});
    }
    my $js = &page_js().'
<script type="text/javascript">
// <![CDATA[
'.
            &Apache::lonhtmlcommon::resize_scrollbox_js('params').'
// ]]>
</script>
';
    my $start_page =
        &Apache::loncommon::start_page('Set/Modify Course Parameters',$js,
                                       {'add_entries' => \%loaditems,});
    my $breadcrumbs =
    &Apache::lonhtmlcommon::breadcrumbs('Table Mode Parameter Setting','Table_Mode');
    my $escfilter=&Apache::lonhtmlcommon::entity_encode($env{'form.filter'});
    my $escpart=&Apache::lonhtmlcommon::entity_encode($env{'form.part'});
    $r->print($start_page.$breadcrumbs);
    &startSettingsScreen($r,'parmset',$crstype);
    $r->print(<<ENDHEAD);
<form method="post" action="/adm/parmset?action=settable" name="parmform">
<input type="hidden" value="" name="pres_value" />
<input type="hidden" value="" name="pres_type" />
<input type="hidden" value="" name="pres_marker" />
<input type="hidden" value="1" name="prevvisit" />
<input type="hidden" value="$escfilter" name="filter" />
<input type="hidden" value="$escpart" name="part" />
ENDHEAD
}


# Prints a row for table mode (except for the tr start).
# Every time a hash reference is passed, a single entry is used, so print_row
# could just use these values, but why make it simple when it can be complicated ?
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {string} $which - parameter key ('parameter_'.part.'_'.name)
# @param {hash reference} $part - parameter key -> parameter part (can be problem part.'_'.response id for response parameters)
# @param {hash reference} $name - parameter key -> parameter name
# @param {hash reference} $symbp - map pc or resource/map id -> map src.'___(all)' or resource symb
# @param {string} $rid - resource id
# @param {hash reference} $default - parameter key -> resource parameter default value
# @param {hash reference} $defaulttype - parameter key -> resource parameter default type
# @param {hash reference} $display - parameter key -> full title for the parameter
# @param {string} $defbgone - user level and other levels background color
# @param {string} $defbgtwo - section level background color, also used for part number
# @param {string} $defbgthree - group level background color
# @param {string} $parmlev - parameter level (Resource:'full', Map:'map', Course:'general')
# @param {string} $uname - user name
# @param {string} $udom - user domain
# @param {string} $csec - section name
# @param {string} $cgroup - group name
# @param {array reference} $usersgroups - list of groups the user belongs to, if any
# @param {boolean} $noeditgrp - true if no edit is allowed for group level parameters
# @param {boolean} $readonly - true if no editing allowed.
# @param {array reference} - $recurseup - list of maps containing current one, ending at top-level.
# @param {hash reference} - $maptitles - - hash map id or src -> map title 
# @param {hash reference} - $allmaps_inverted - hash map src -> map pc
# @param {scalar reference} - $reclinks - number of "parameter in effect" cells with link to map where recursive param was set 
sub print_row {
    my ($r,$which,$part,$name,$symbp,$rid,$default,$defaulttype,$display,$defbgone,
    $defbgtwo,$defbgthree,$parmlev,$uname,$udom,$csec,$cgroup,$usersgroups,$noeditgrp,
    $readonly,$recurseup,$maptitles,$allmaps_inverted,$reclinks)=@_;
    my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $courseopt=&Apache::lonnet::get_courseresdata($cnum,$cdom);
    my $numlinks = 0;

    # 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},$uname,$udom,$csec,$cgroup,$courseopt);
    # 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},$uname,$udom,$csec,$cgroup,$courseopt);
    # cascade down manually
    my $cascadetype=$$defaulttype{$which};
    for (my $i=18;$i>0;$i--) {
        if ($typeoutpar[$i]) {
            $cascadetype=$typeoutpar[$i];
        } else {
            $typeoutpar[$i]=$cascadetype;
        }
    }
    my $parm=$$display{$which};

    if ($parmlev eq 'full') {
        $r->print('<td style="background-color:'.$defbgtwo.';" align="center">'
                  .($$part{$which} eq '0'?'0 ('.&mt('default').')':$$part{$which}).'</td>');
    } else {
        $parm=~s|\[.*\]\s||g;
    }
    my $automatic=&rulescache(($which=~/\_([^\_]+)$/)[0].'_triggers');
    if ($automatic) {
        $parm.='<span class="LC_warning"><br />'.&mt('Automatically sets').' '.join(', ',split(/\:/,$automatic)).'</span>';
    }
    $r->print('<td>'.$parm.'</td>');

    my $thismarker=$which;
    $thismarker=~s/^parameter\_//;
    my $mprefix=$rid.'&'.$thismarker.'&';
    my ($parmname)=($thismarker=~/\_([^\_]+)$/);
    my ($othergrp,$grp_parm,$controlgrp,$effective_parm,$effparm_rec,$effparm_level,
        $eff_groupparm,$recurse_check,$recursinfo,$extra);
    if ((ref($recurseup) eq 'ARRAY') && (@{$recurseup} > 0)) {
        if ($result eq '') {
            $recurse_check = 1;
        } elsif (($uname ne '') && ($result > 3)) {
            $recurse_check = 1;
        } elsif (($cgroup ne '') && ($result > 7)) {
            $recurse_check = 1;
        } elsif (($csec ne '') && ($result > 11)) {
            $recurse_check = 1;
        } elsif ($result > 17) {
            $recurse_check = 1;
        }
        if ($recurse_check) {
            my $what = $$part{$which}.'.'.$$name{$which};
            my $prefix;
            if (($uname ne '') && ($udom ne '')) {
                my $useropt = &Apache::lonnet::get_userresdata($uname,$udom);
                $prefix = $env{'request.course.id'};
                $recursinfo = &get_recursive($recurseup,$useropt,$what,$prefix);
                if (ref($recursinfo) eq 'ARRAY') {
                    $effparm_rec = 1;
                    $effparm_level = &mt('user: [_1]',$uname);
                }
            }
            if (($cgroup ne '') && (!$effparm_rec)) {
                $prefix = $env{'request.course.id'}.'.['.$cgroup.']';
                $recursinfo = &get_recursive($recurseup,$courseopt,$what,$prefix);
                if (ref($recursinfo) eq 'ARRAY') {
                    $effparm_rec = 1;
                    $effparm_level = &mt('group: [_1]',$cgroup);
                }
            }
            if (($csec ne '') && (!$effparm_rec)) {
                $prefix = $env{'request.course.id'}.'.['.$csec.']';
                $recursinfo = &get_recursive($recurseup,$courseopt,$what,$prefix);
                if (ref($recursinfo) eq 'ARRAY') {
                    $effparm_rec = 1;
                    $effparm_level = &mt('section: [_1]',$csec);
                }
            }
            if (!$effparm_rec) {
                $prefix = $env{'request.course.id'};
                $recursinfo = &get_recursive($recurseup,$courseopt,$what,$prefix); 
                if (ref($recursinfo) eq 'ARRAY') {
                    $effparm_rec = 1;
                }
            }
        }
    }
    if ((!$effparm_rec) && ($result == 17 || $result == 11 || $result == 7 || $result == 3)) {
        $effparm_rec = 1;
    }
    if ((!$effparm_rec) && 
        (($$name{$which} eq 'encrypturl') || ($$name{$which} eq 'hiddenresource')) && 
        ($result == 16 || $result == 10 || $result == 6 || $result == 2)) {
        $effparm_rec = 1;
    }
    if ($parmname eq 'deeplink') {
        my ($domltistr,$crsltistr);
        my %lti =
            &Apache::lonnet::get_domain_lti($env{'course.'.$env{'request.course.id'}.'.domain'},
                                            'provider');
        if (keys(%lti)) {
            foreach my $item (sort { $a <=> $b }  (keys(%lti))) {
                if (ref($lti{$item}) eq 'HASH') {
                    unless ($lti{$item}{'requser'}) {
                        $domltistr .= $item.':'.&escape(&escape($lti{$item}{'consumer'})).',';
                    }
                }
            }
            $domltistr =~ s/,$//;
            if ($domltistr) {
                $extra = 'ltid_'.$domltistr;
            }
        }
        my %courselti = &Apache::lonnet::get_course_lti($cnum,$cdom);
        if (keys(%courselti)) {
            foreach my $item (sort { $a <=> $b } keys(%courselti)) {
                if (($item =~ /^\d+$/) && (ref($courselti{$item}) eq 'HASH')) {
                    $crsltistr .= $item.':'.&escape(&escape($courselti{$item}{'name'})).',';
                }
            }
            $crsltistr =~ s/,$//;
            if ($crsltistr) {
                if ($extra) {
                    $extra .= '&';
                }
                $extra .= 'ltic_'.$crsltistr;
            }
        }
        if ($env{'course.'.$env{'request.course.id'}.'.menucollections'}) {
            my @colls;
            foreach my $item (split(/;/,$env{'course.'.$env{'request.course.id'}.'.menucollections'})) {
                my ($num,$value) = split(/\%/,$item);
                if ($num =~ /^\d+$/) {
                    push(@colls,$num);
                }
            }
            if (@colls) {
                if ($extra) {
                    $extra .= '&';
                }
                $extra .= 'menus_'.join(',',@colls);
            }
        }
    }
    if ($parmlev eq 'general') {
        if ($uname) {
            &print_td($r,4,$defbgone,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,'',$extra);
        } elsif ($cgroup) {
            &print_td($r,8,$defbgthree,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,$noeditgrp,$readonly,'',$extra);
        } elsif ($csec) {
            &print_td($r,12,$defbgtwo,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,'',$extra);
        } else {
            &print_td($r,18,$defbgone,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,'',$extra);
        }
    } elsif ($parmlev eq 'map') {
        if ($uname) {
            &print_td($r,2,$defbgone,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,1,$extra);
        } elsif ($cgroup) {
            &print_td($r,6,$defbgthree,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,$noeditgrp,$readonly,1,$extra);
        } elsif ($csec) {
            &print_td($r,10,$defbgtwo,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,1,$extra);
        } else {
            &print_td($r,16,$defbgone,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,1,$extra);
        }
    } else {
        if ($uname) {
            if (@{$usersgroups} > 1) {
                (my $coursereply,$othergrp,$grp_parm,$controlgrp,my $grp_is_rec) =
                    &check_other_groups($$part{$which}.'.'.$$name{$which},
                       $rid,$cgroup,$defbgone,$usersgroups,$result,$courseopt);
                if (($coursereply) && ($result > 4)) {
                    if (defined($controlgrp)) {
                        if ($cgroup ne $controlgrp) {
                            $eff_groupparm = $grp_parm;
                            undef($result);
                            undef($effparm_rec);
                            if ($grp_is_rec) {
                                 $effparm_rec = 1;
                            }
                        }
                    }
                }
            }
        }

        &print_td($r,18,$defbgone,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,'',$extra);
        &print_td($r,16,$defbgone,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,1,$extra);
        &print_td($r,15,'#FFDDDD',$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,'',$extra);
        &print_td($r,14,'#FFDDDD',$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,'',$extra);
        &print_td($r,13,$defbgone,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,'',$extra);

        if ($csec) {
            &print_td($r,12,$defbgtwo,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,'',$extra);
            &print_td($r,10,$defbgtwo,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,1,$extra);
            &print_td($r,9,$defbgtwo,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,'',$extra);
        }

        if ($cgroup) {
            &print_td($r,8,$defbgthree,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,$noeditgrp,$readonly,'',$extra);
            &print_td($r,6,$defbgthree,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,$noeditgrp,$readonly,1,$extra);
            &print_td($r,5,$defbgthree,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,$noeditgrp.$readonly,'',$extra);
        }

        if ($uname) {
            if ($othergrp) {
                $r->print($othergrp);
            }
            &print_td($r,4,$defbgone,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,'',$extra);
            &print_td($r,2,$defbgone,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,1,$extra);
            &print_td($r,1,$defbgone,$result,\@outpar,$mprefix,$which,\@typeoutpar,$display,'',$readonly,'',$extra);
        }
    } # end of $parmlev if/else
    if (ref($recursinfo) eq 'ARRAY') {
        my $rectitle = &mt('recursive');
        if ((ref($maptitles) eq 'HASH') && (exists($maptitles->{$recursinfo->[2]}))) {
            if ((ref($allmaps_inverted) eq 'HASH') && (exists($allmaps_inverted->{$recursinfo->[2]}))) {
                $rectitle = &mt('set in: [_1]','"'.
                                '<a href="javascript:pjumprec('."'".$allmaps_inverted->{$recursinfo->[2]}."',".
                                                              "'$parmname','$$part{$which}'".');">'.
                                $maptitles->{$recursinfo->[2]}.'</a>"');
              
                $numlinks ++;
            }
        }
        my ($parmname)=($thismarker=~/\_([^\_]+)$/);
        $effective_parm = &valout($recursinfo->[0],$recursinfo->[1]);
        $r->print('<td style="background-color:#CCCCFF;" align="center">'.$effective_parm.
                  '<br /><span class="LC_parm_recursive">'.$rectitle.'&nbsp;'.
                  $effparm_level.'</span></td>');
    } else {
        if ($result) {
            $effective_parm = &valout($outpar[$result],$typeoutpar[$result]);
        }
        if ($eff_groupparm) {
            $effective_parm = $eff_groupparm;
        }
        $r->print('<td style="background-color:#CCCCFF;" align="center">'.$effective_parm.
                  ($effparm_rec?'<br /><span class="LC_parm_recursive">'.&mt('recursive').
                                '</span>':'').'</td>');
    }
    if ($parmlev eq 'full') {
        my $sessionval=&Apache::lonnet::EXT('resource.'.$$part{$which}.
                                        '.'.$$name{$which},$$symbp{$rid});
        my $sessionvaltype=$typeoutpar[$result];
        if (!defined($sessionvaltype)) {
            $sessionvaltype=$$defaulttype{$which};
        }
        $r->print('<td style="background-color:#999999;" align="center"><font color="#FFFFFF">'.
                  &valout($sessionval,$sessionvaltype).'&nbsp;'.
                  '</font></td>');
    }
    $r->print('</tr>');
    $r->print("\n");
    if (($numlinks) && (ref($reclinks))) {
        $$reclinks = $numlinks;
    }
}

# Prints a cell for table mode.
#
# FIXME: some of these parameter names are uninspired ($which and $value)
# Also, it would make more sense to pass the display for this cell rather
# than the full display hash and the key to use.
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {integer} $which - level
# @param {string} $defbg - cell background color
# @param {integer} $result - the most specific level that is defined for that parameter
# @param {array reference} $outpar - array level -> parameter value (when defined)
# @param {string} $mprefix - resource id.'&'.part.'_'.parameter name.'&'
# @param {string} $value - parameter key ('parameter_'.part.'_'.name)
# @param {array reference} $typeoutpar - array level -> parameter type (when defined)
# @param {hash reference} $display - parameter key -> full title for the parameter
# @param {boolean} $noeditgrp - true if no edit is allowed for group level parameters
# @param {boolean} $readonly -true if editing not allowed.
# @param {boolean} $ismaplevel - true if level is for a map.
# @param {string} $extra - extra information to pass to plink.
sub print_td {
    my ($r,$which,$defbg,$result,$outpar,$mprefix,$value,$typeoutpar,$display,
        $noeditgrp,$readonly,$ismaplevel,$extra)=@_;
    my ($ineffect,$recursive,$currval,$currtype,$currlevel);
    $ineffect = 0;
    $currval = $$outpar[$which];
    $currtype = $$typeoutpar[$which];
    $currlevel = $which;
    if (($result) && ($result == $which)) {
        $ineffect = 1;
    } 
    if ($ismaplevel) {
        if ($mprefix =~ /(hiddenresource|encrypturl)\&/) {
            if (($result) && ($result == $which)) {
                $recursive = 1;
            }
        } elsif ($$outpar[$which+1] ne '') {
            $recursive = 1;
            $currlevel = $which+1;
            $currval = $$outpar[$currlevel];
            $currtype = $$typeoutpar[$currlevel];
            if (($result) && ($result == $currlevel)) {
                $ineffect = 1;
            }
        }
    }
    $r->print('<td style="background-color:'.($ineffect?'#AAFFAA':$defbg).
              ';" align="center">');
    my $nolink = 0;
    if ($readonly) {
        $nolink = 1;
    } else { 
        if ($which == 14 || $which == 15 || $mprefix =~ /mapalias\&$/) {
            $nolink = 1;
        } elsif (($env{'request.course.sec'} ne '') && ($which > 12)) {
            $nolink = 1;
        } elsif ($which == 5 || $which ==  6 || $which == 7 || $which == 8) {
            if ($noeditgrp) {
                $nolink = 1;
            }
        } elsif ($mprefix =~ /availablestudent\&$/) {
            $nolink = 1;
        } elsif ($mprefix =~ /examcode\&$/) {
            unless ($which == 2) {
                $nolink = 1;
            }
        }
    }
    if ($nolink) {
        my ($parmname)=((split(/\&/,$mprefix))[1]=~/\_([^\_]+)$/);
        $r->print(&valout($currval,$currtype));
    } else {
        $r->print(&plink($currtype,
                         $$display{$value},$currval,
                         $mprefix.$currlevel,'parmform.pres','psub',$recursive,
                         $extra));
    }
    $r->print('</td>'."\n");
}

# Returns HTML and other info for the cell added when a user is selected
# and that user is in several groups. This is the cell with the title "Control by other group".
#
# @param {string} $what - parameter part.'.'.parameter name
# @param {string} $rid - resource id
# @param {string} $cgroup - group name
# @param {string} $defbg - cell background color
# @param {array reference} $usersgroups - list of groups the user belongs to, if any
# @param {integer} $result - level
# @param {hash reference} $courseopt - course parameters hash (result of lonnet::get_courseresdata, dump of course's resourcedata.db)
# @returns {Array} - array (parameter value for the other group, HTML for the cell, HTML with the value, name of the other group, true if recursive)
sub check_other_groups {
    my ($what,$rid,$cgroup,$defbg,$usersgroups,$result,$courseopt) = @_;
    my $courseid = $env{'request.course.id'};
    my $output;
    my $symb = &symbcache($rid);
    my $symbparm=$symb.'.'.$what;
    my $map=(&Apache::lonnet::decode_symb($symb))[0];
    my $recurseparm=$map.'___(rec).'.$what; 
    my $mapparm=$map.'___(all).'.$what;
    my ($coursereply,$resultitem,$resultgroup,$resultlevel,$resulttype) =
          &parm_control_group($courseid,$usersgroups,$symbparm,$mapparm,
                              $recurseparm,$what,$courseopt);
    my $bgcolor = $defbg;
    my ($grp_parm,$grp_is_rec);
    if (($coursereply) && ($cgroup ne $resultgroup)) {
        my ($parmname) = ($what =~ /\.([^.]+)$/);
        if ($result > 3) {
            $bgcolor = '#AAFFAA';
        }
        $grp_parm = &valout($coursereply,$resulttype);
        $output = '<td style="background-color:'.$bgcolor.';" align="center">';
        if ($resultgroup && $resultlevel) {
            if ($resultlevel eq 'recursive') {
                $resultlevel = 'map/folder';
                $grp_is_rec = 1;
            }
            $output .= '<small><b>'.$resultgroup.'</b> ('.$resultlevel.'): </small>'.$grp_parm.
                       ($grp_is_rec?'<span class="LC_parm_recursive">'.&mt('recursive').'</span>':'');
             
        } else {
            $output .= '&nbsp;';
        }
        $output .= '</td>';
    } else {
        $output .= '<td style="background-color:'.$bgcolor.';">&nbsp;</td>';
    }
    return ($coursereply,$output,$grp_parm,$resultgroup,$grp_is_rec);
}

# Looks for a group with a defined parameter for given user and parameter.
# Used by check_other_groups.
#
# @param {string} $courseid - the course id
# @param {array reference} $usersgroups - list of groups the user belongs to, if any
# @param {string} $symbparm - end of the course parameter hash key for the group resource level
# @param {string} $mapparm - end of the course parameter hash key for the group map/folder level
# @param {string} $recurseparm - end of the course parameter hash key for the group recursive level
# @param {string} $what - parameter part.'.'.parameter name
# @param {hash reference} $courseopt - course parameters hash
# @returns {Array} - (parameter value for the group, course parameter hash key for the parameter, name of the group, level name, parameter type)
sub parm_control_group {
    my ($courseid,$usersgroups,$symbparm,$mapparm,$recurseparm,$what,$courseopt) = @_;
    my ($coursereply,$resultitem,$resultgroup,$resultlevel,$resulttype);
    my $grpfound = 0;
    my @levels = ($symbparm,$mapparm,$recurseparm,$what);
    my @levelnames = ('resource','map/folder','recursive','general');
    foreach my $group (@{$usersgroups}) {
        if ($grpfound) { last; }
        for (my $i=0; $i<@levels; $i++) {
            my $item = $courseid.'.['.$group.'].'.$levels[$i];
            if (defined($$courseopt{$item})) {
                $coursereply = $$courseopt{$item};
                $resultitem = $item;
                $resultgroup = $group;
                $resultlevel = $levelnames[$i];
                $resulttype = $$courseopt{$item.'.type'};
                $grpfound = 1;
                last;
            }
        }
    }
    return($coursereply,$resultitem,$resultgroup,$resultlevel,$resulttype);
}



# Extracts lots of information about all of the the course's resources into a variety of hashes, using lonnavmaps and lonnet::metadata.
# All the parameters are references and are filled by the sub.
#
# @param {array reference} $ids - resource and map ids
# @param {hash reference} $typep - hash resource/map id -> resource type (file extension)
# @param {hash reference} $keyp - hash resource/map id -> comma-separated list of parameter keys from lonnet::metadata
# @param {hash reference} $allparms - hash parameter name -> parameter title
# @param {hash reference} $allparts - hash parameter part -> part title (a parameter part can be problem part.'_'.response id for response parameters)
# @param {hash reference} $allmaps - hash map pc -> map src
# @param {hash reference} $mapp - hash map pc or resource/map id -> enclosing map src
# @param {hash reference} $symbp - hash map pc or resource/map id -> map src.'___(all)' for a map or resource symb for a resource
# @param {hash reference} $maptitles - hash map pc or src -> map title (this should really be two separate hashes)
# @param {hash reference} $uris - hash resource/map id -> resource src
# @param {hash reference} $keyorder - hash parameter key -> appearance rank for this parameter when looking through every resource and every parameter, starting at 100 (integer)
# @param {hash reference} $defkeytype - hash parameter name -> parameter type
sub extractResourceInformation {
    my $ids = shift;
    my $typep = shift;
    my $keyp = shift;
    my $allparms = shift;
    my $allparts = shift;
    my $allmaps = shift;
    my $mapp = shift;
    my $symbp = shift;
    my $maptitles=shift;
    my $uris=shift;
    my $keyorder=shift;
    my $defkeytype=shift;
    my $pssymb=shift;

    my $keyordercnt=100;

    my $navmap = Apache::lonnavmaps::navmap->new();
    return unless(ref($navmap));
    my @allres;
    if ($pssymb ne '') {
        my $res = $navmap->getBySymb($pssymb);
        if (ref($res)) {
            @allres = ($res);
        }
    }
    if (!@allres) { 
        @allres=$navmap->retrieveResources(undef,undef,1,undef,1);
    }
    foreach my $resource (@allres) {
        my $id=$resource->id();
        my ($mapid,$resid)=split(/\./,$id);
        if ($mapid eq '0') { next; }
        $$ids[$#$ids+1]=$id;
        my $srcf=$resource->src();
        $srcf=~/\.(\w+)$/;
        $$typep{$id}=$1;
        my $toolsymb;
        if ($srcf =~ /ext\.tool$/) {
            $toolsymb = $resource->symb();
        }
        $$keyp{$id}='';
        $$uris{$id}=$srcf;

        foreach my $key (split(/\,/,&Apache::lonnet::metadata($srcf,'allpossiblekeys',$toolsymb))) {
            next if ($key!~/^parameter_/);

# Hidden parameters
            next if (&Apache::lonnet::metadata($srcf,$key.'.hidden',$toolsymb) eq 'parm');
#
# allparms is a hash of parameter names
#
            my $name=&Apache::lonnet::metadata($srcf,$key.'.name',$toolsymb);
            if (!exists($$allparms{$name}) || $$allparms{$name} =~ m/^\s*$/ ) {
                my ($display,$parmdis);
                $display = &standard_parameter_names($name);
                if ($display eq '') {
                    $display= &Apache::lonnet::metadata($srcf,$key.'.display',$toolsymb);
                    $parmdis = $display;
                    $parmdis =~ s/\s*\[Part.*$//g;
                } else {
                    $parmdis = &mt($display);
                }
                $$allparms{$name}=$parmdis;
                if (ref($defkeytype)) {
                    $$defkeytype{$name}=
                    &Apache::lonnet::metadata($srcf,$key.'.type',$toolsymb);
                }
            }

#
# allparts is a hash of all parts
#
            my $part= &Apache::lonnet::metadata($srcf,$key.'.part',$toolsymb);
            $$allparts{$part} = &mt('Part: [_1]',$part);
#
# Remember all keys going with this resource
#
            if ($$keyp{$id}) {
                $$keyp{$id}.=','.$key;
            } else {
                $$keyp{$id}=$key;
            }   
#
# Put in order
#
            unless ($$keyorder{$key}) {
                $$keyorder{$key}=$keyordercnt;
                $keyordercnt++;
            }
        }


        if (!exists($$mapp{$mapid})) {
            $$mapp{$id}=
            &Apache::lonnet::declutter($resource->enclosing_map_src());
            $$mapp{$mapid}=$$mapp{$id};
            $$allmaps{$mapid}=$$mapp{$id};
            if ($mapid eq '1') {
                $$maptitles{$mapid}=&mt('Main Content');
            } else {
                $$maptitles{$mapid}=&Apache::lonnet::gettitle($$mapp{$id});
            }
            $$maptitles{$$mapp{$id}}=$$maptitles{$mapid};
            $$symbp{$mapid}=$$mapp{$id}.'___(all)';  # Added in rev. 1.57, but seems not to be used.
                                                     # Lines 1038 and 1114 which use $symbp{$mapid}
                                                     # are commented out in rev. 1.57
        } else {
            $$mapp{$id} = $$mapp{$mapid};
        }
        $$symbp{$id}=&Apache::lonnet::encode_symb($$mapp{$id},$resid,$srcf);
    }
}

sub get_recursive {
    my ($recurseup,$resdata,$what,$prefix) = @_; 
    if ((ref($resdata) eq 'HASH') && (ref($recurseup) eq 'ARRAY')) {
        foreach my $item (@{$recurseup}) {
            my $norecursechk=$prefix.'.'.$item.'___(all).'.$what;
            if (defined($resdata->{$norecursechk})) {
                if ($what =~ /\.(encrypturl|hiddenresource)$/) {
                    my $type = $resdata->{$norecursechk.'.type'};
                    return [$resdata->{$norecursechk},$type,$item];
                } else {
                    last;
                }
            }
            my $recursechk=$prefix.'.'.$item.'___(rec).'.$what;
            if (defined($resdata->{$recursechk})) {
                my $type = $resdata->{$recursechk.'.type'};
                return [$resdata->{$recursechk},$type,$item];
            }
        }
    }
    return;
}


# Tells if a parameter type is a date.
#
# @param {string} type - parameter type
# @returns{boolean} - true if it is a date
sub isdateparm {
    my $type=shift;
    return (($type=~/^date/) && (!($type eq 'date_interval')));
}

# Determine if parameter type is specialized string type (i.e.,
# not just string or string_yesno.  

sub is_specialstring {
    my $type=shift;
    return (($type=~/^string_/) && ($type ne 'string_yesno'));
}

# Prints the HTML and Javascript to select parameters, with various shortcuts.
#
# @param {Apache2::RequestRec} $r - the Apache request
sub parmmenu {
    my ($r)=@_;
    $r->print(<<ENDSCRIPT);
<script type="text/javascript">
// <![CDATA[
    function checkall(value, checkName) {

        var li = "_li";
        var displayOverview = "";
        
        if (value == false) {
            displayOverview = "none"
        }

        for (i=0; i<document.forms.parmform.elements.length; i++) {
            ele = document.forms.parmform.elements[i];
            if (ele.name == checkName) {
                document.forms.parmform.elements[i].checked=value;
            }
        }
    }

    function checkthis(thisvalue, checkName) {
        for (i=0; i<document.forms.parmform.elements.length; i++) {
            ele = document.forms.parmform.elements[i];
            if (ele.name == checkName) {
                if (ele.value == thisvalue) {
                    document.forms.parmform.elements[i].checked=true;
                }
            }
        }
    }

    function checkdates() {
        checkthis('duedate','pscat');
        checkthis('opendate','pscat');
        checkthis('answerdate','pscat');
    }

    function checkdisset() {
        checkthis('discussend','pscat');
        checkthis('discusshide','pscat');
        checkthis('discussvote','pscat');
    }

    function checkcontdates() {
        checkthis('contentopen','pscat');
        checkthis('contentclose','pscat');
    }

    function checkvisi() {
        checkthis('hiddenresource','pscat');
        checkthis('encrypturl','pscat');
        checkthis('problemstatus','pscat');
        checkthis('contentopen','pscat');
        checkthis('opendate','pscat');
    }

    function checkparts() {
        checkthis('hiddenparts','pscat');
        checkthis('display','pscat');
        checkthis('ordered','pscat');
    }

    function checkstandard() {
        checkall(false,'pscat');
        checkdates();
        checkthis('weight','pscat');
        checkthis('maxtries','pscat');
        checkthis('type','pscat');
        checkthis('problemstatus','pscat');
    }

// ]]>
</script>
ENDSCRIPT

    $r->print('<hr />');
    &shortCuts($r);
    $r->print('<hr />');
}

# Returns parameter categories.
#
# @returns {hash} - category name -> title in English
sub categories {
    return ('time_settings' => 'Time Settings',
    'grading' => 'Grading',
    'tries' => 'Tries',
    'problem_appearance' => 'Problem Appearance',
    'behaviour_of_input_fields' => 'Behaviour of Input Fields',
    'hiding' => 'Hiding',
    'high_level_randomization' => 'High Level Randomization',
    'slots' => 'Slots',
    'file_submission' => 'File Submission',
    'misc' => 'Miscellaneous' ); 
}

# Returns the category for each parameter.
#
# @returns {hash} - parameter name -> category name
sub lookUpTableParameter {
 
    return ( 
        'opendate' => 'time_settings',
        'duedate' => 'time_settings',
        'answerdate' => 'time_settings',
        'interval' => 'time_settings',
        'contentopen' => 'time_settings',
        'contentclose' => 'time_settings',
        'discussend' => 'time_settings',
        'printstartdate' => 'time_settings',
        'printenddate' => 'time_settings',
        'weight' => 'grading',
        'handgrade' => 'grading',
        'maxtries' => 'tries',
        'hinttries' => 'tries',
        'randomizeontries' => 'tries',
        'type' => 'problem_appearance',
        'problemstatus' => 'problem_appearance',
        'display' => 'problem_appearance',
        'ordered' => 'problem_appearance',
        'numbubbles' => 'problem_appearance',
        'tol' => 'behaviour_of_input_fields',
        'sig' => 'behaviour_of_input_fields',
        'turnoffunit' => 'behaviour_of_input_fields',
        'hiddenresource' => 'hiding',
        'hiddenparts' => 'hiding',
        'discusshide' => 'hiding',
        'buttonshide' => 'hiding',
        'turnoffeditor' => 'hiding',
        'encrypturl' => 'hiding',
        'deeplink' => 'hiding',
        'randomorder' => 'high_level_randomization',
        'randompick' => 'high_level_randomization',
        'available' => 'slots',
        'useslots' => 'slots',
        'availablestudent' => 'slots',
        'uploadedfiletypes' => 'file_submission',
        'maxfilesize' => 'file_submission',
        'cssfile' => 'misc',
        'mapalias' => 'misc',
        'acc' => 'misc',
        'maxcollaborators' => 'misc',
        'scoreformat' => 'misc',
        'lenient' => 'grading',
        'retrypartial' => 'tries',
        'discussvote'  => 'misc',
        'examcode' => 'high_level_randomization',
    );
}

# Adds the given parameter name to an array of arrays listing all parameters for each category.
#
# @param {string} $name - parameter name
# @param {array reference} $catList - array reference category name -> array reference of parameter names
sub whatIsMyCategory {
    my $name = shift;
    my $catList = shift;
    my @list;
    my %lookUpList = &lookUpTableParameter; #Initilize the lookupList
    my $cat = $lookUpList{$name};
    if (defined($cat)) {
        if (!defined($$catList{$cat})){
            push @list, ($name);
            $$catList{$cat} = \@list;
        } else {
            push @{${$catList}{$cat}}, ($name);     
        }
    } else {
        if (!defined($$catList{'misc'})){
            push @list, ($name);
            $$catList{'misc'} = \@list;
        } else {
            push @{${$catList}{'misc'}}, ($name);     
        }
    }        
}

# Sorts parameter names based on appearance order.
#
# @param {array reference} name - array reference of parameter names
# @param {hash reference} $keyorder - hash parameter key -> appearance rank
# @returns {Array} - array of parameter names
sub keysindisplayorderCategory {
    my ($name,$keyorder)=@_;
    return sort {
        $$keyorder{'parameter_0_'.$a} <=> $$keyorder{'parameter_0_'.$b}; 
    } ( @{$name});
}

# Returns a hash category name -> order, starting at 1 (integer)
#
# @returns {hash}
sub category_order {
    return (
        'time_settings' => 1,
        'grading' => 2,
        'tries' => 3,
        'problem_appearance' => 4,
        'hiding' => 5,
        'behaviour_of_input_fields' => 6,
        'high_level_randomization'  => 7,
        'slots' => 8,
        'file_submission' => 9,
        'misc' => 10
    );

}

# Prints HTML to let the user select parameters, from a list of all parameters organized by category.
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {hash reference} $allparms - hash parameter name -> parameter title
# @param {array reference} $pscat - list of selected parameter names
# @param {hash reference} $keyorder - hash parameter key -> appearance rank
sub parmboxes {
    my ($r,$allparms,$pscat,$keyorder)=@_;
    my %categories = &categories();
    my %category_order = &category_order();
    my %categoryList = (
        'time_settings' => [],
        'grading' => [],
        'tries' => [],
        'problem_appearance' => [],
        'behaviour_of_input_fields' => [],
        'hiding' => [],
        'high_level_randomization' => [],
        'slots' => [],
        'file_submission' => [],
        'misc' => [],
    );

    foreach my $tempparameter (keys(%$allparms)) {
        &whatIsMyCategory($tempparameter, \%categoryList);
    }
    #part to print the parm-list
    foreach my $key (sort { $category_order{$a} <=> $category_order{$b} } keys(%categoryList)) {
        next if (@{$categoryList{$key}} == 0);
        next if ($key eq '');
        $r->print('<div class="LC_Box LC_400Box">'
                 .'<h4 class="LC_hcell">'.&mt($categories{$key}).'</h4>'."\n");
        foreach my $tempkey (&keysindisplayorderCategory($categoryList{$key},$keyorder)) {
            next if ($tempkey eq '');
            $r->print('<span class="LC_nobreak">'
                     .'<label><input type="checkbox" name="pscat" '
                     .'value="'.$tempkey.'" ');
            if ($$pscat[0] eq "all" || grep $_ eq $tempkey, @{$pscat}) {
                $r->print( ' checked="checked"');
            }
            $r->print(' />'.($$allparms{$tempkey}=~/\S/ ? $$allparms{$tempkey}
                                                      : $tempkey)
                     .'</label></span><br />'."\n");
        }
        $r->print('</div>');
    }
    $r->print("\n");
}

# Prints HTML with shortcuts to select groups of parameters in one click, or deselect all.
#
# @param {Apache2::RequestRec} $r - the Apache request
sub shortCuts {
    my ($r)=@_;

    # Parameter Selection
    $r->print(
        &Apache::lonhtmlcommon::start_funclist(&mt('Parameter Selection'))
       .&Apache::lonhtmlcommon::add_item_funclist(
            '<a href="javascript:checkall(true, \'pscat\')">'.&mt('Select All').'</a>')
       .&Apache::lonhtmlcommon::add_item_funclist(
            '<a href="javascript:checkstandard()">'.&mt('Select Common Only').'</a>')
       .&Apache::lonhtmlcommon::add_item_funclist(
            '<a href="javascript:checkall(false, \'pscat\')">'.&mt('Unselect All').'</a>')
       .&Apache::lonhtmlcommon::end_funclist()
    );

    # Add Selection for...
    $r->print(
        &Apache::lonhtmlcommon::start_funclist(&mt('Add Selection for...'))
       .&Apache::lonhtmlcommon::add_item_funclist(
            '<a href="javascript:checkdates()">'.&mt('Problem Dates').'</a>')
       .&Apache::lonhtmlcommon::add_item_funclist(
            '<a href="javascript:checkcontdates()">'.&mt('Content Dates').'</a>')
       .&Apache::lonhtmlcommon::add_item_funclist(
            '<a href="javascript:checkdisset()">'.&mt('Discussion Settings').'</a>')
       .&Apache::lonhtmlcommon::add_item_funclist(
            '<a href="javascript:checkvisi()">'.&mt('Visibilities').'</a>')
       .&Apache::lonhtmlcommon::add_item_funclist(
            '<a href="javascript:checkparts()">'.&mt('Part Parameters').'</a>')
       .&Apache::lonhtmlcommon::end_funclist()
    );
}

# Prints HTML to select parts to view (except for the title).
# Used by table and overview modes.
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {hash reference} $allparts - hash parameter part -> part title
# @param {array reference} $psprt - list of selected parameter parts
sub partmenu {
    my ($r,$allparts,$psprt)=@_;
    my $selsize = 1+scalar(keys(%{$allparts}));
    if ($selsize > 8) {
        $selsize = 8;
    }

    $r->print('<select multiple="multiple" name="psprt" size="'.$selsize.'">');
    $r->print('<option value="all"');
    $r->print(' selected="selected"') unless (@{$psprt}); # useless, the array is never empty
    $r->print('>'.&mt('All Parts').'</option>');
    my %temphash=();
    foreach (@{$psprt}) { $temphash{$_}=1; }
    foreach my $tempkey (sort {
                if ($a==$b) { return ($a cmp $b) } else { return ($a <=> $b); }
            } keys(%{$allparts})) {
        unless ($tempkey =~ /\./) {
            $r->print('<option value="'.$tempkey.'"');
            if ($$psprt[0] eq "all" ||  $temphash{$tempkey}) {
                $r->print(' selected="selected"');
            }
            $r->print('>'.$$allparts{$tempkey}.'</option>');
        }
    }
    $r->print('</select>');
}

# Prints HTML to select a user and/or a group.
# Used by table mode.
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {string} $uname - selected user name
# @param {string} $id - selected Student/Employee ID
# @param {string} $udom - selected user domain
# @param {string} $csec - selected section name
# @param {string} $cgroup - selected group name
# @param {string} $parmlev - parameter level (Resource:'full', Map:'map', Course:'general')
# @param {array reference} $usersgroups - list of groups the user belongs to, if any
# @param {string} $pssymb - resource symb (when a single resource is selected)
sub usermenu {
    my ($r,$uname,$id,$udom,$csec,$cgroup,$parmlev,$usersgroups,$pssymb)=@_;
    my $chooseopt=&Apache::loncommon::select_dom_form($udom,'udom').' '.
                  &Apache::loncommon::selectstudent_link('parmform','uname','udom','condition').
                  &Apache::lonhtmlcommon::scripttag(<<ENDJS);
function setCourseadv(form,caller) {
    if (caller.value == 'st') {
        form.courseadv.value = 'none';
    } else {
        form.courseadv.value = '';
    }
    return;
}
ENDJS

    my (%chkroles,$stuonly,$courseadv);
    if ($env{'form.userroles'} eq 'any') {
        $chkroles{'any'} = ' checked="checked"';
    } else {
        $chkroles{'st'} = ' checked="checked"';
        $courseadv = 'none';
    }
    my $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
    if ($crstype eq 'Community') {
        $stuonly = &mt('member only');
    } else {
        $stuonly = &mt('student only');
    }
    $chooseopt .= '<br /><span class="LC_cusr_subheading">'.
                  &mt("User's role").':&nbsp;'.
                  '<label><input type="radio" name="userroles" value="st"'.$chkroles{'st'}.' onclick="setCourseadv(this.form,this);" />'.
                  $stuonly.'</label>&nbsp;&nbsp;'.
                  '<label><input type="radio" name="userroles" value="any"'.$chkroles{'any'}.' onclick="setCourseadv(this.form,this);" />'.
                  &mt('any role').'</label><input type="hidden" id="courseadv" name="courseadv" value="'.$courseadv.'" /></span>';
    my $sections='';
    my %sectionhash = &Apache::loncommon::get_sections();

    my $groups;
    my %grouphash;
    if (($pssymb) || &Apache::lonnet::allowed('mdg',$env{'request.course.id'})) {
        %grouphash = &Apache::longroup::coursegroups();
    } elsif ($env{'request.course.groups'} ne '') {
        map { $grouphash{$_} = 1; } split(/:/,$env{'request.course.groups'});
    }

    my $g_s_header='';
    my $g_s_footer='';

    my $currsec = $env{'request.course.sec'};
    if ($currsec) {
        $sections=&mt('Section:').' '.$currsec;
        if (%grouphash) {
            $sections .= ';'.('&nbsp;' x2);
        }
    } elsif (%sectionhash && $currsec eq '') {
        $sections=&mt('Section:').' <select name="csec"';
        if (%grouphash && $parmlev ne 'full') {
            $sections .= qq| onchange="group_or_section('csec')" |;
        }
        $sections .= '>';
    foreach my $section ('',sort(keys(%sectionhash))) {
        $sections.='<option value="'.$section.'" '.
        ($section eq $csec?'selected="selected"':'').'>'.$section.
                                                              '</option>';
        }
        $sections.='</select>';
    }

    if (%sectionhash && %grouphash && $parmlev ne 'full' && $currsec eq '') {
        $sections .= '&nbsp;'.&mt('or').'&nbsp;';
        $sections .= qq|
<script type="text/javascript">
// <![CDATA[
function group_or_section(caller) {
   if (caller == "cgroup") {
       if (document.parmform.cgroup.selectedIndex != 0) {
           document.parmform.csec.selectedIndex = 0;
       }
   } else {
       if (document.parmform.csec.selectedIndex != 0) {
           document.parmform.cgroup.selectedIndex = 0;
       }
   }
}
// ]]>
</script>
|;
    } else {
        $sections .= qq|
<script type="text/javascript">
// <![CDATA[
function group_or_section(caller) {
    return;
}
// ]]>
</script>
|;
    }

    if (%grouphash) {
        $groups=&mt('Group').': <select name="cgroup"';
        if (%sectionhash && $env{'form.action'} eq 'settable' && $currsec eq '') {
            $groups .= qq| onchange="group_or_section('cgroup')" |;
        }
        $groups .= '>';
        foreach my $grp ('',sort(keys(%grouphash))) {
            $groups.='<option value="'.$grp.'" ';
            if ($grp eq $cgroup) {
                unless ((defined($uname)) && ($grp eq '')) {
                    $groups .=  'selected="selected" ';
                }
            } elsif (!defined($cgroup)) {
                if (@{$usersgroups} == 1) {
                    if ($grp eq $$usersgroups[0]) {
                        $groups .=  'selected="selected" ';
                    }
                }
            }
            $groups .= '>'.$grp.'</option>';
        }
        $groups.='</select>';
    }

    if (%sectionhash || %grouphash) {
        $r->print(&Apache::lonhtmlcommon::row_title(&mt('Group/Section')));
        $r->print($sections.$groups);
        $r->print(&Apache::lonhtmlcommon::row_closure());
    } else {
        $r->print($sections); 
    }

    $r->print(&Apache::lonhtmlcommon::row_title(&mt('User')));
    $r->print(&mt('For User [_1] or Student/Employee ID [_2] at Domain [_3]'
                 ,'<input type="text" value="'.$uname.'" size="12" name="uname" />'
                 ,'<input type="text" value="'.$id.'" size="12" name="id" /> '
                 ,$chooseopt));
}

# Prints HTML to select parameters from a list of all parameters.
# Uses parmmenu and parmboxes.
# Used by table and overview modes.
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {hash reference} $allparms - hash parameter name -> parameter title
# @param {array reference} $pscat - list of selected parameter names
# @param {hash reference} $keyorder - hash parameter key -> appearance rank
# @param {string} [$divid] - name used to give an id to the HTML element for the scroll box
sub displaymenu {
    my ($r,$allparms,$pscat,$keyorder,$divid)=@_;

    $r->print(&Apache::lonhtmlcommon::start_pick_box());
    $r->print(&Apache::lonhtmlcommon::row_title(&mt('Select Parameters to View')));

    &parmmenu($r);
    $r->print(&Apache::loncommon::start_scrollbox('480px','440px','200px',$divid));
    &parmboxes($r,$allparms,$pscat,$keyorder);
    $r->print(&Apache::loncommon::end_scrollbox());

    $r->print(&Apache::lonhtmlcommon::row_closure(1));
    $r->print(&Apache::lonhtmlcommon::end_pick_box());
 
}

# Prints HTML to select a map.
# Used by table mode and overview mode.
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {hash reference} $allmaps - hash map pc -> map src
# @param {string} $pschp - selected map pc, or 'all'
# @param {hash reference} $maptitles - hash map id or src -> map title
# @param {hash reference} $symbp - hash map pc or resource/map id -> map src.'___(all)' or resource symb
sub mapmenu {
    my ($r,$allmaps,$pschp,$maptitles,$symbp)=@_;
    my %allmaps_inverted = reverse %$allmaps;
    my $navmap = Apache::lonnavmaps::navmap->new();
    my $tree=[];
    my $treeinfo={};
    if (defined($navmap)) {
        my $it=$navmap->getIterator(undef,undef,undef,1,1,undef);
        my $curRes;
        my $depth = 0;
        my %parent = ();
        my $startcount = 5;
        my $lastcontainer = $startcount;
# preparing what is to show ...
        while ($curRes = $it->next()) {
            if ($curRes == $it->BEGIN_MAP()) {
                $depth++;
                $parent{$depth}= $lastcontainer;
            }
            if ($curRes == $it->END_MAP()) {
                $depth--;
                $lastcontainer = $parent{$depth};
            }
            if (ref($curRes)) {
                my $symb = $curRes->symb();
                my $ressymb = $symb;
                if (($curRes->is_sequence()) || ($curRes->is_page())) {
                    my $type = 'sequence';
                    if ($curRes->is_page()) {
                        $type = 'page';
                    }
                    my $id= $curRes->id();
                    my $srcf = $curRes->src();
                    my $resource_name = &Apache::lonnet::gettitle($srcf);
                    if(!exists($treeinfo->{$id})) {
                        push(@$tree,$id);
                        my $enclosing_map_folder = &Apache::lonnet::declutter($curRes->enclosing_map_src());        
                        $treeinfo->{$id} = {
                                    depth => $depth,
                                    type  => $type,
                                    name  => $resource_name,
                                    enclosing_map_folder => $enclosing_map_folder,
                                    };
                    }
                }
            }
        }
    }
# Show it ...    
    $r->print(&Apache::lonhtmlcommon::row_title(&mt('Select Enclosing Map or Folder'),'','',' id="mapmenu"'));
    if ((ref($tree) eq 'ARRAY') && (ref($treeinfo) eq 'HASH')) {
        my $icon = '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />';
        my $whitespace =
            '<img src="'
           .&Apache::loncommon::lonhttpdurl('/adm/lonIcons/whitespace_21.gif')
           .'" alt="" />';

        # Info about selectable folders/maps
        $r->print(
            '<div class="LC_info">'
           .&mt('You can only select maps and folders which have modifiable settings.')
           .' '.&Apache::loncommon::help_open_topic('Parameter_Set_Folder') 
           .'</div>'
        );

        $r->print(&Apache::loncommon::start_scrollbox('700px','680px','400px','mapmenuscroll'));
        $r->print(&Apache::loncommon::start_data_table(undef,'mapmenuinner'));

        # Display row: "All Maps or Folders"
        $r->print(
            &Apache::loncommon::start_data_table_row(undef,'picklevel')
           .'<td>'
           .'<label>'
           .'<input type="radio" name="pschp"'
        );
        $r->print(' checked="checked"') if ($pschp eq 'all' || !$pschp);
        $r->print(
            ' value="all" />&nbsp;'.$icon.'&nbsp;'
           .&mt('All Maps or Folders')
           .'</label>'
           .'<hr /></td>'
           .&Apache::loncommon::end_data_table_row()
        );

        # Display row: "Main Content"
        if (exists($$allmaps{1})) {
            $r->print(
                &Apache::loncommon::start_data_table_row()
               .'<td>'
               .'<label>'
               .'<input type="radio" name="pschp" value="1"'
            );
            $r->print(' checked="checked"') if ($pschp eq '1');
            $r->print(
                '/>&nbsp;'.$icon.'&nbsp;'
               .$$maptitles{1}
               .($$allmaps{1} !~/^uploaded/?' ['.$$allmaps{1}.']':'')
               .'</label>'
               .'</td>'
               .&Apache::loncommon::end_data_table_row()
            );
        }

        # Display rows for all course maps and folders
        foreach my $id (@{$tree}) {
            my ($mapid,$resid)=split(/\./,$id);
            # Indentation
            my $depth = $treeinfo->{$id}->{'depth'};
            my $indent;
            for (my $i = 0; $i < $depth; $i++) {
                $indent.= $whitespace;
            }
            $icon =  '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />';
            if ($treeinfo->{$id}->{'type'} eq 'page') {
                $icon = '<img src="/adm/lonIcons/navmap.page.open.gif" alt="" />';
            }
            my $symb_name = $$symbp{$id};
            my ($front, $tail) = split (/___${resid}___/, $symb_name);
            $symb_name = $tail;
            $r->print(
                &Apache::loncommon::start_data_table_row()
               .'<td>'
               .'<label>'
            );
            # Only offer radio button for folders/maps which can be parameterized
            if ($allmaps_inverted{$symb_name}) {
                $r->print(
                    '<input type ="radio" name="pschp"'
                   .' value="'.$allmaps_inverted{$symb_name}.'"'
                );
                $r->print(' checked="checked"') if ($allmaps_inverted{$symb_name} eq $pschp);
                $r->print('/>');
            } else {
                $r->print($whitespace);
            }
            $r->print(
                $indent.$icon.'&nbsp;'
               .$treeinfo->{$id}->{name}
               .($$allmaps{$mapid}!~/^uploaded/?' ['.$$allmaps{$mapid}.']':'')
               .'</label>'
               .'</td>'
               .&Apache::loncommon::end_data_table_row()
            );
        }

        $r->print(&Apache::loncommon::end_data_table().
                  '<br style="line-height:2px;" />'.
                  &Apache::loncommon::end_scrollbox());
    }
}

# Prints HTML to select the parameter level (resource, map/folder or course).
# Used by table and overview modes.
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {hash reference} $alllevs - all parameter levels, hash English title -> value
# @param {string} $parmlev - selected level value (full|map|general), or ''
sub levelmenu {
    my ($r,$alllevs,$parmlev)=@_;

    $r->print(&Apache::lonhtmlcommon::row_title(&mt('Select Parameter Level').
                                                &Apache::loncommon::help_open_topic('Course_Parameter_Levels')));
    $r->print('<select id="parmlev" name="parmlev" onchange="showHide_courseContent()">');
    foreach my $lev (reverse(sort(keys(%{$alllevs})))) {
        $r->print('<option value="'.$$alllevs{$lev}.'"');
        if ($parmlev eq $$alllevs{$lev}) {
            $r->print(' selected="selected"');
        }
        $r->print('>'.&mt($lev).'</option>');
    }
    $r->print("</select>");
}


# Returns HTML to select a section (with a select HTML element).
# Used by overview mode.
#
# @param {array reference} $selectedsections - list of selected section ids
# @returns {string}
sub sectionmenu {
    my ($selectedsections)=@_;
    my %sectionhash = &Apache::loncommon::get_sections();
    return '' if (!%sectionhash);

    my (@possibles,$disabled);
    if ($env{'request.course.sec'} ne '') {
        @possibles = ($env{'request.course.sec'});
        $selectedsections = [$env{'request.course.sec'}];
        $disabled = ' disabled="disabled"';
    } else {
        @possibles = ('all',sort(keys(%sectionhash)));
    }
    my $output = '<select name="Section" multiple="multiple" size="8"'.$disabled.'>';
    foreach my $s (@possibles) {
        $output .= '    <option value="'.$s.'"';
        if ((@{$selectedsections}) && (grep(/^\Q$s\E$/,@{$selectedsections}))) {  
            $output .= ' selected="selected"';
        }
        $output .= '>'."$s</option>\n";
    }
    $output .= "</select>\n";
    return $output;
}

# Returns HTML to select a group (with a select HTML element).
# Used by overview mode.
#
# @param {array reference} $selectedgroups - list of selected group names
# @returns {string}
sub groupmenu {
    my ($selectedgroups)=@_;
    my %grouphash;
    if (&Apache::lonnet::allowed('mdg',$env{'request.course.id'})) {
        %grouphash = &Apache::longroup::coursegroups();
    } elsif ($env{'request.course.groups'} ne '') {
         map { $grouphash{$_} = 1; } split(/:/,$env{'request.course.groups'});
    }
    return '' if (!%grouphash);

    my $output = '<select name="Group" multiple="multiple" size="8">';
    foreach my $group (sort(keys(%grouphash))) {
        $output .= '    <option value="'.$group.'"';
        if ((@{$selectedgroups}) && (grep(/^\Q$group\E$/,\@{$selectedgroups}))) {
            $output .=  ' selected="selected"';
        }
        $output .= '>'."$group</option>\n";
    }
    $output .= "</select>\n";
    return $output;
}

# Returns an array with the given parameter split by comma.
# Used by assessparms (table mode).
#
# @param {string} $keyp - the string to split
# @returns {Array<string>}
sub keysplit {
    my $keyp=shift;
    return (split(/\,/,$keyp));
}

# Returns the keys in $name, sorted using $keyorder.
# Parameters are sorted by key, which means they are sorted by part first, then by name.
# Used by assessparms (table mode) for resource level.
#
# @param {hash reference} $name - parameter key -> parameter name
# @param {hash reference} $keyorder - hash parameter key -> appearance rank
# @returns {Array<string>}
sub keysinorder {
    my ($name,$keyorder)=@_;
    return sort {
        $$keyorder{$a} <=> $$keyorder{$b};
    } (keys(%{$name}));
}

# Returns the keys in $name, sorted using $keyorder to sort parameters by name first, then by part.
# Used by assessparms (table mode) for map and general levels.
#
# @param {hash reference} $name - parameter key -> parameter name
# @param {hash reference} $keyorder - hash parameter key -> appearance rank
# @returns {Array<string>}
sub keysinorder_bytype {
    my ($name,$keyorder)=@_;
    return sort {
        my $ta=(split('_',$a))[-1]; # parameter name
        my $tb=(split('_',$b))[-1];
        if ($$keyorder{'parameter_0_'.$ta} == $$keyorder{'parameter_0_'.$tb}) {
            return ($a cmp $b);
        }
        $$keyorder{'parameter_0_'.$ta} <=> $$keyorder{'parameter_0_'.$tb};
    } (keys(%{$name}));
}

# Returns the keys in $name, sorted using $keyorder to sort parameters by name.
# Used by defaultsetter (parameter settings default actions).
#
# @param {hash reference} $name - hash parameter name -> parameter title
# @param {hash reference} $keyorder - hash parameter key -> appearance rank
# @returns {Array<string>}
sub keysindisplayorder {
    my ($name,$keyorder)=@_;
    return sort {
        $$keyorder{'parameter_0_'.$a} <=> $$keyorder{'parameter_0_'.$b};
    } (keys(%{$name}));
}

# Prints HTML with a choice to sort results by realm or student first.
# Used by overview mode.
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {string} $sortorder - realmstudent|studentrealm
sub sortmenu {
    my ($r,$sortorder)=@_;
    $r->print('<br /><label><input type="radio" name="sortorder" value="realmstudent"');
    if ($sortorder eq 'realmstudent') {
       $r->print(' checked="checked"');
    }
    $r->print(' />'.&mt('Sort by realm first, then student (group/section)'));
    $r->print('</label><br /><label><input type="radio" name="sortorder" value="studentrealm"');
    if ($sortorder eq 'studentrealm') {
       $r->print(' checked="checked"');
    }
    $r->print(' />'.&mt('Sort by student (group/section) first, then realm').
          '</label>');
}

# Returns a hash parameter key -> order (integer) giving the order for some parameters.
#
# @returns {hash}
sub standardkeyorder {
    return ('parameter_0_opendate' => 1,
        'parameter_0_duedate' => 2,
        'parameter_0_answerdate' => 3,
        'parameter_0_interval' => 4,
        'parameter_0_weight' => 5,
        'parameter_0_maxtries' => 6,
        'parameter_0_hinttries' => 7,
        'parameter_0_contentopen' => 8,
        'parameter_0_contentclose' => 9,
        'parameter_0_type' => 10,
        'parameter_0_problemstatus' => 11,
        'parameter_0_hiddenresource' => 12,
        'parameter_0_hiddenparts' => 13,
        'parameter_0_display' => 14,
        'parameter_0_ordered' => 15,
        'parameter_0_tol' => 16,
        'parameter_0_sig' => 17,
        'parameter_0_turnoffunit' => 18,
        'parameter_0_discussend' => 19,
        'parameter_0_discusshide' => 20,
        'parameter_0_discussvote' => 21,
        'parameter_0_printstartdate'  =>  22,
        'parameter_0_printenddate' =>  23);
}


# Table mode UI.
# If nothing is selected, prints HTML forms to select resources, parts, parameters, user, group and section.
# Otherwise, prints the parameter table, with a link to change the selection unless a single resource is selected.
#
# Parameters used from the request:
# action - handler action (see handler), usermenu is checking for value 'settable'
# cgroup - selected group
# command - 'set': direct access to table mode for a resource
# csec - selected section
# dis - set when the "Update Display" button was used, used only to discard command 'set'
# hideparmsel - can be 'hidden' to hide the parameter selection div initially and display the "Change Parameter Selection" link instead (which displays the div)
# id - student/employee ID
# parmlev - selected level (full|map|general)
# part - selected part (unused ?)
# pres_marker - &&&-separated parameter identifiers, "resource id&part_parameter name&level"
# pres_type - &&&-separated parameter types
# pres_value - &&&-separated parameter values
# prevvisit - '1' if the user has submitted the form before
# pscat (multiple values) - selected parameter names
# pschp - selected map pc, or 'all'
# psprt (multiple values) - list of selected parameter parts
# filter - part of or whole parameter name, to be filtered out when parameters are displayed (unused ?)
# recent_* (* = parameter type) - recent values entered by the user for parameter types
# symb - resource symb (when a single resource is selected)
# udom - selected user domain
# uname - selected user name
# url - used only with command 'set', the resource url
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param $parm_permission - ref to hash of permissions
#                           if $parm_permission->{'edit'} is true, editing is allowed.
sub assessparms {

    my ($r,$parm_permission) = @_;


# -------------------------------------------------------- Variable declaration
    my @ids=(); # resource and map ids
    my %symbp=(); # hash map pc or resource/map id -> map src.'___(all)' or resource symb
    my %mapp=(); # hash map pc or resource/map id -> enclosing map src
    my %typep=(); # hash resource/map id -> resource type (file extension)
    my %keyp=(); # hash resource/map id -> comma-separated list of parameter keys
    my %uris=(); # hash resource/map id -> resource src
    my %maptitles=(); # hash map pc or src -> map title
    my %allmaps=(); # hash map pc -> map src
    my %allmaps_inverted=(); # hash map src -> map pc
    my %alllevs=(); # hash English level title -> value

    my $uname; # selected user name
    my $udom; # selected user domain
    my $uhome; # server with the user's files, or 'no_host'
    my $csec; # selected section name
    my $cgroup; # selected group name
    my @usersgroups = (); # list of the user groups
    my $numreclinks = 0;

    my $coursename=$env{'course.'.$env{'request.course.id'}.'.description'};

    $alllevs{'Resource Level'}='full';
    $alllevs{'Map/Folder Level'}='map';
    $alllevs{'Course Level'}='general';

    my %allparms; # hash parameter name -> parameter title
    my %allparts; # hash parameter part -> part title
# ------------------------------------------------------------------------------

#
# Order in which these parameters will be displayed
#
    my %keyorder=&standardkeyorder();

#    @ids=();
#    %symbp=();       # These seem defined above already.
#    %typep=();

    my $message='';

    $csec=$env{'form.csec'};
    if ($env{'request.course.sec'} ne '') {
        $csec = $env{'request.course.sec'};    
    }

# Check group privs.
    $cgroup=$env{'form.cgroup'};
    my $noeditgrp; 
    if ($cgroup ne '') {
        unless (&Apache::lonnet::allowed('mdg',$env{'request.course.id'})) {
            if (($env{'request.course.groups'} eq '') || 
                (!grep(/^\Q$cgroup\E$/,split(/:/,$env{'request.course.groups'})))) {
                $noeditgrp = 1;
            }
        }
    }

    if      ($udom=$env{'form.udom'}) {
    } elsif ($udom=$env{'request.role.domain'}) {
    } elsif ($udom=$env{'user.domain'}) {
    } else {
        $udom=$r->dir_config('lonDefDomain');
    }
    

    my @pscat=&Apache::loncommon::get_env_multiple('form.pscat');
    my $pschp=$env{'form.pschp'};


    my @psprt=&Apache::loncommon::get_env_multiple('form.psprt');
    if (!@psprt) { $psprt[0]='all'; }
    if (($env{'form.part'}) && ($psprt[0] ne 'all')) { $psprt[0]=$env{'form.part'}; }

    my $pssymb='';
    my $parmlev='';

    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],'ids'))[1];
        if ($uname) {
            $id='';
        } else {
            $message=
                '<p class="LC_warning">'.
                &mt('Unknown ID [_1] at domain [_2]',
                    "'".$id."'","'".$udom."'").
                '</p>';
        }
    } else {
        $uname=$env{'form.uname'};
    }
    unless ($udom) { $uname=''; }
    $uhome='';
    if ($uname) {
        $uhome=&Apache::lonnet::homeserver($uname,$udom);
        if ($uhome eq 'no_host') {
            $message=
                '<p class="LC_warning">'.
                &mt('Unknown user [_1] at domain [_2]',
                    "'".$uname."'","'".$udom."'").
                '</p>';
            $uname='';
        } else {
            $csec=&Apache::lonnet::getsection($udom,$uname,
                          $env{'request.course.id'});
            if ($csec eq '-1') {
                my $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
                if ($env{'form.userroles'} eq 'any') {
                    if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                        $csec = $env{'request.course.sec'};
                        $message = '<span class="LC_info">';
                        if ($crstype eq 'Community') {
                            $message .= &mt('User [_1] at domain [_2] has a non-member role in this community',
                                            $uname,$udom);
                        } else {
                            $message .= &mt('User [_1] at domain [_2] has a non-student role in this course',
                                            $uname,$udom);
                        }
                        $message .= '</span>';
                    } else {
                        my @possroles = ('in','ep','ta','cr');
                        if ($crstype eq 'Community') {
                            unshift(@possroles,'co');
                        } else {
                            unshift(@possroles,'cc');
                        }
                        my %not_student_roles =
                            &Apache::lonnet::get_my_roles($uname,$udom,'userroles',['active'],
                                                          \@possroles,[$udom],1,1);
                        my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                        my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                        my %sections_by_role;
                        foreach my $role (keys(%not_student_roles)) {
                            if ($role =~ /^\Q$cnum:$cdom:\E([^:]+):(|[^:]+)$/) {
                                my ($rolename,$sec) = ($1,$2);
                                if ($rolename =~ m{^cr/}) {
                                    $rolename = 'cr';
                                }
                                push(@{$sections_by_role{$rolename}},$sec);
                            }
                        }
                        my $numroles = scalar(keys(%sections_by_role));
                        if ($numroles) {
                            foreach my $role (@possroles) {
                                if (ref($sections_by_role{$role}) eq 'ARRAY') {
                                    my @secs = sort { $a <=> $b } @{$sections_by_role{$role}};
                                    $csec = $secs[0];
                                    last;
                                }
                            }
                        }
                        if ($csec eq '-1') {
                            $message = '<span class="LC_warning">';
                            if ($crstype eq 'Community') {
                                $message .= &mt('User [_1] at domain [_2] does not have a role in this community',
                                                $uname,$udom);
                            } else {
                                $message .= &mt('User [_1] at domain [_2] does not have a role in this course',
                                                $uname,$udom);
                            }
                            $message .= '</span>';
                            $uname='';
                            if ($env{'request.course.sec'} ne '') {
                                $csec=$env{'request.course.sec'};
                            } else {
                                $csec=$env{'form.csec'};
                            }
                            $cgroup=$env{'form.cgroup'};
                        } else {
                            $message = '<span class="LC_info">';
                            if ($crstype eq 'Community') {
                                $message .= &mt('User [_1] at domain [_2] has a non-member role in this community',
                                         $uname,$udom);
                            } else {
                                $message .= &mt('User [_1] at domain [_2] has a non-student role in this course',
                                                $uname,$udom);
                            }
                            $message .= '</span>';
                        }
                    }
                } else {
                    $message = '<span class="LC_warning">';
                    if ($crstype eq 'Community') {
                        $message .= &mt('User [_1] at domain [_2] does not have a member role in this community',
                                         $uname,$udom);
                    } else {
                         $message .= &mt('User [_1] at domain [_2] does not have a student role in this course',
                                         $uname,$udom);
                    }
                    $message .= '</span>';
                    $uname='';
                    if ($env{'request.course.sec'} ne '') {
                        $csec=$env{'request.course.sec'};
                    } else {
                        $csec=$env{'form.csec'};
                    }
                    $cgroup=$env{'form.cgroup'};
                }
            } elsif ($env{'request.course.sec'} ne '') {
                if ($csec ne $env{'request.course.sec'}) {
                    $message='<span class="LC_warning">'.
                              &mt("User '[_1]' at domain '[_2]' not in section '[_3]'",
                                  $uname,$udom,$env{'request.course.sec'}).
                              '</span>';
                    $uname='';
                    $csec=$env{'request.course.sec'};
                }
                $cgroup=$env{'form.cgroup'};
            }
            if ($uname ne '') {
                my %name=&Apache::lonnet::userenvironment($udom,$uname,
                  ('firstname','middlename','lastname','generation','id'));
                $message .= "\n<p>\n".&mt('Full Name').': '
                            .$name{'firstname'}.' '.$name{'middlename'}.' '
                            .$name{'lastname'}.' '.$name{'generation'}
                            ."<br />\n".&mt('Student/Employee ID').': '.$name{'id'}.'</p>';
                @usersgroups = &Apache::lonnet::get_users_groups(
                                   $udom,$uname,$env{'request.course.id'});
                if (@usersgroups > 0) {
                    unless (grep(/^\Q$cgroup\E$/,@usersgroups)) {
                        $cgroup = $usersgroups[0];
                    }
                } else {
                    $cgroup = '';
                }
            }
        }
    }

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

# --------------------------------------------------------- Get all assessments
    &extractResourceInformation(\@ids, \%typep,\%keyp, \%allparms, \%allparts, \%allmaps,
                \%mapp, \%symbp,\%maptitles,\%uris,
                \%keyorder,undef,$pssymb);

    %allmaps_inverted = reverse(%allmaps);

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

# ---------------------------------------------------------- Anything to store?
    if ($env{'form.pres_marker'} && $parm_permission->{'edit'}) {
        my @markers=split(/\&\&\&/,$env{'form.pres_marker'});
        my @values=split(/\&\&\&/,$env{'form.pres_value'});
        my @types=split(/\&\&\&/,$env{'form.pres_type'});
        my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        my $chome = $env{'course.'.$env{'request.course.id'}.'.home'};
        my ($got_chostname,$chostname,$cmajor,$cminor);
        my $totalstored = 0;
        my $now = time;
        for (my $i=0;$i<=$#markers;$i++) {
            my ($needsrelease,$needsnewer,$name,$namematch);
            if (($env{'request.course.sec'} ne '') && ($markers[$i] =~ /\&(9|10|11|12)$/)) {
                next if ($csec ne $env{'request.course.sec'});
            }
            if ($markers[$i] =~ /\&(8|7|6|5)$/) {
                next if ($noeditgrp);
            }
            if ($markers[$i] =~ /\&(17|11|7|3)$/) {
                $namematch = 'maplevelrecurse';
            }
            if ($markers[$i] =~ /^[\d.]+\&0_availablestudent\&(1|2|3|4)$/) {
                my (@ok_slots,@fail_slots,@del_slots);
                my $courseopt=&Apache::lonnet::get_courseresdata($cnum,$cdom);
                my ($level,@all) =
                    &parmval_by_symb('0.availablestudent',$pssymb,'',$uname,$udom,
                                     $csec,$cgroup,$courseopt);
                foreach my $slot_name (split(/:/,$values[$i])) {
                    next if ($slot_name eq '');
                    if (&update_slots($slot_name,$cdom,$cnum,$pssymb,$uname,$udom) eq 'ok') {
                        push(@ok_slots,$slot_name);

                    } else {
                        push(@fail_slots,$slot_name);
                    }
                }
                if (@ok_slots) {
                    $values[$i] = join(':',@ok_slots);
                } else {
                    $values[$i] = '';
                }
                if ($all[$level] ne '') {
                    my @existing = split(/:/,$all[$level]);
                    foreach my $slot_name (@existing) {
                        if (!grep(/^\Q$slot_name\E$/,split(/:/,$values[$i]))) {
                            if (&delete_slots($slot_name,$cdom,$cnum,$uname,$udom,$pssymb) eq 'ok') {
                                push(@del_slots,$slot_name);
                            }
                        }
                    }
                }
            } elsif ($markers[$i] =~ /_(type|lenient|retrypartial|discussvote|examcode|printstartdate|printenddate|acc|interval)\&\d+$/) {
                $name = $1;
                my $val = $values[$i];
                my $valmatch = '';
                if ($name eq 'examcode') {
                    if (&Apache::lonnet::validCODE($values[$i])) {
                        $val = 'valid';
                    }
                } elsif ($name eq 'printstartdate') {
                    if ($val =~ /^\d+$/) {
                        if ($val > $now) {
                            $val = 'future';
                        }
                    } 
                } elsif ($name eq 'printenddate') {
                    if ($val =~ /^\d+$/) {
                        if ($val < $now) {
                            $val = 'past';
                        }
                    }
                } elsif (($name eq 'lenient') || ($name eq 'acc')) {
                    my $stringtype = &get_stringtype($name);
                    my $stringmatch = &standard_string_matches($stringtype);
                    if (ref($stringmatch) eq 'ARRAY') {
                        foreach my $item (@{$stringmatch}) {
                            if (ref($item) eq 'ARRAY') {
                                my ($regexpname,$pattern) = @{$item};
                                if ($pattern ne '') {
                                    if ($val =~ /$pattern/) {
                                        $valmatch = $regexpname;
                                        $val = '';
                                        last;
                                    }
                                }
                            }
                        }
                    }
                } elsif ($name eq 'interval') {
                    my $intervaltype = &get_intervaltype($name);
                    my $intervalmatch = &standard_interval_matches($intervaltype);
                    if (ref($intervalmatch) eq 'ARRAY') {
                        foreach my $item (@{$intervalmatch}) {
                            if (ref($item) eq 'ARRAY') {
                                my ($regexpname,$pattern) = @{$item};
                                if ($pattern ne '') {
                                    if ($val =~ /$pattern/) {
                                        $valmatch = $regexpname;
                                        $val = '';
                                        last;
                                    }
                                }
                            }
                        }
                    }
                }
                $needsrelease =
                    $Apache::lonnet::needsrelease{"parameter:$name:$val:$valmatch:"};
                if ($needsrelease) {
                    unless ($got_chostname) {
                        ($chostname,$cmajor,$cminor) = &parameter_release_vars();
                        $got_chostname = 1;
                    } 
                    $needsnewer = &parameter_releasecheck($name,$val,$valmatch,undef,
                                                          $needsrelease,
                                                          $cmajor,$cminor);
                }
            }
            if ($needsnewer) {
                undef($namematch);
            } else {
                my $currneeded;
                if ($needsrelease) {
                    $currneeded = $needsrelease;
                }
                if ($namematch) {
                    $needsrelease =
                        $Apache::lonnet::needsrelease{"parameter::::$namematch"};
                    if (($needsrelease) && (($currneeded eq '') || ($needsrelease < $currneeded))) {
                        unless ($got_chostname) {
                            ($chostname,$cmajor,$cminor) = &parameter_release_vars();
                            $got_chostname = 1;
                        }
                        $needsnewer = &parameter_releasecheck(undef,undef,undef,$namematch,
                                                              $needsrelease,
                                                              $cmajor,$cminor);
                    } else {
                        undef($namematch);
                    }
                }
            }
            if ($needsnewer) {
                $message .= &oldversion_warning($name,$namematch,$values[$i],$chostname,$cmajor,
                                                $cminor,$needsrelease);
            } else {
                $message.=&storeparm(split(/\&/,$markers[$i]),
                                     $values[$i],
                                     $types[$i],
                                     $uname,$udom,$csec,$cgroup);
                $totalstored ++;
            }
        }
# ---------------------------------------------------------------- Done storing
        if ($totalstored) {
            $message.='<p class="LC_warning">'
                     .&mt('Changes can take up to 10 minutes before being active for all students.')
                     .&Apache::loncommon::help_open_topic('Caching')
                     .'</p>';
        }
    }

#----------------------------------------------- if all selected, fill in array
    if ($pscat[0] eq "all") {
        @pscat = (keys(%allparms));
    }
    if (!@pscat) {
        @pscat=('duedate','opendate','answerdate','weight','maxtries','type','problemstatus')
    };
    if ($psprt[0] eq "all" || !@psprt) {
        @psprt = (keys(%allparts));
    }
# ------------------------------------------------------------------ Start page

    my $crstype = &Apache::loncommon::course_type();
    &startpage($r,$pssymb,$crstype);

    foreach my $item ('tolerance','date_default','date_start','date_end',
            'date_interval','int','float','string','string_lenient',
            'string_examcode','string_deeplink','string_discussvote',
            'string_useslots','string_problemstatus','string_ip',
            'string_questiontype') {
        $r->print('<input type="hidden" value="'.
            &HTML::Entities::encode($env{'form.recent_'.$item},'"&<>').
            '" name="recent_'.$item.'" />');
    }

    # ----- Start Parameter Selection

    # Hide parm selection?
    $r->print(<<ENDPARMSELSCRIPT);
<script type="text/javascript">
// <![CDATA[
function parmsel_show() {
    document.getElementById('parmsel').style.display = "";
    document.getElementById('parmsellink').style.display = "none";
}
// ]]>
</script>
ENDPARMSELSCRIPT
    
    if (!$pssymb) {
        # No single resource selected, print forms to select things (hidden after first selection)
        my $parmselhiddenstyle=' style="display:none"';
        if($env{'form.hideparmsel'} eq 'hidden') {
           $r->print('<div id="parmsel"'.$parmselhiddenstyle.'>');
        } else  {
           $r->print('<div id="parmsel">');
        }

        # Step 1
        $r->print(&Apache::lonhtmlcommon::topic_bar(1,&mt('Resource Specification'),'parmstep1'));
        $r->print('
<script type="text/javascript">
// <![CDATA['.
                 &showhide_js().'
// ]]>
</script>
');
        $r->print(&Apache::lonhtmlcommon::start_pick_box(undef,'parmlevel'));
        &levelmenu($r,\%alllevs,$parmlev);
        $r->print(&Apache::lonhtmlcommon::row_closure());
        &mapmenu($r,\%allmaps,$pschp,\%maptitles, \%symbp);
        $r->print(&Apache::lonhtmlcommon::row_closure());
        $r->print(&Apache::lonhtmlcommon::row_title(&mt('Select Parts to View')));
        &partmenu($r,\%allparts,\@psprt);
        $r->print(&Apache::lonhtmlcommon::row_closure(1));
        $r->print(&Apache::lonhtmlcommon::end_pick_box());

        # Step 2
        $r->print(&Apache::lonhtmlcommon::topic_bar(2,&mt('Parameter Specification'),'parmstep2'));
        &displaymenu($r,\%allparms,\@pscat,\%keyorder,'parmmenuscroll');

        # Step 3
        $r->print(&Apache::lonhtmlcommon::topic_bar(3,&mt('User Specification (optional)'),'parmstep3'));
        $r->print(&Apache::lonhtmlcommon::start_pick_box());
        &usermenu($r,$uname,$id,$udom,$csec,$cgroup,$parmlev,\@usersgroups,$pssymb);
        $r->print(&Apache::lonhtmlcommon::row_closure(1));
        $r->print(&Apache::lonhtmlcommon::end_pick_box());

        # Update Display Button
        $r->print('<p>'
             .'<input type="submit" name="dis"'
             .' value="'.&mt('Update Display').'" />'
             .'<input type="hidden" name="hideparmsel" value="hidden" />'
             .'</p>');
        $r->print('</div>');

        # Offer link to display parameter selection again
        $r->print('<p id="parmsellink"');
        if ($env{'form.hideparmsel'} ne 'hidden') {
           $r->print($parmselhiddenstyle);
        }
        $r->print('>'
             .'<a href="javascript:parmsel_show()">'
             .&mt('Change Parameter Selection')
             .'</a>'
             .'</p>');
    } else {
        # parameter screen for a single resource. 
        my ($map,$iid,$resource)=&Apache::lonnet::decode_symb($pssymb);
        my $title = &Apache::lonnet::gettitle($pssymb);
        $r->print(&mt('Specific Resource: [_1] ([_2])',
                         $title,'<span class="LC_filename">'.$resource.'</span>').
                '<input type="hidden" value="'.$pssymb.'" name="symb" />'.
                  '<br />');
        $r->print(&Apache::lonhtmlcommon::topic_bar('',&mt('Additional Display Specification (optional)')));
        $r->print(&Apache::lonhtmlcommon::start_pick_box());
        &usermenu($r,$uname,$id,$udom,$csec,$cgroup,$parmlev,\@usersgroups,$pssymb);
        $r->print(&Apache::lonhtmlcommon::row_closure(1));
        $r->print(&Apache::lonhtmlcommon::end_pick_box());
        $r->print('<p>'
             .'<input type="submit" name="dis"'
             .' value="'.&mt('Update Display').'" />'
             .'<input type="hidden" name="hideparmsel" value="hidden" />'
             .'</p>');
    }
    
    # ----- End Parameter Selection

    # Display Messages
    $r->print('<div>'.$message.'</div>');


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

    @pscat = @temp_pscat;


    if (($env{'form.prevvisit'}) || ($pschp) || ($pssymb)) {
# ----------------------------------------------------------------- Start Table
        my @catmarker=map { tr|.|_|; 'parameter_'.$_; } @pscat;
        my $csuname=$env{'user.name'};
        my $csudom=$env{'user.domain'};
        my $readonly = 1;
        if ($parm_permission->{'edit'}) {
            undef($readonly); 
        }

        if ($parmlev eq 'full') {
#
# This produces the cascading table output of parameters
#
            my $coursespan=$csec?8:5;
            my $userspan=3;
            if ($cgroup ne '') {
                $coursespan += 3;
            }

            $r->print(&Apache::loncommon::start_data_table());
            #
            # This produces the headers
            #
            $r->print('<tr><td colspan="5"></td>');
            $r->print('<th colspan="'.($coursespan).'">'.&mt('Any User').'</th>');
            if ($uname) {
                if (@usersgroups > 1) {
                    $userspan ++;
                }
                $r->print('<th colspan="'.$userspan.'" rowspan="2">');
                $r->print(&mt('User [_1] at Domain [_2]',"'".$uname."'","'".$udom."'").'</th>');
            }
            my %lt=&Apache::lonlocal::texthash(
                'pie'    => "Parameter in Effect",
                'csv'    => "Current Session Value",
                'rl'     => "Resource Level",
                'ic'     => 'in Course',
                'aut'    => "Assessment URL and Title",
                'type'   => 'Type',
                'emof'   => "Enclosing Map or Folder",
                'part'   => 'Part',
                'pn'     => 'Parameter Name',
                'def'    => 'default',
                'femof'  => 'from Enclosing Map or Folder',
                'gen'    => 'general',
                'foremf' => 'for Enclosing Map or Folder',
                'fr'     => 'for Resource'
            );
            $r->print(<<ENDTABLETWO);
<th rowspan="3">$lt{'pie'}</th>
<th rowspan="3">$lt{'csv'}<br />($csuname:$csudom)</th>
</tr><tr><td colspan="5"></td><th colspan="2">$lt{'ic'}</th><th colspan="2">$lt{'rl'}</th>
<th colspan="1">$lt{'ic'}</th>

ENDTABLETWO
            if ($csec) {
                $r->print('<th colspan="3">'.
                &mt("in Section")." $csec</th>");
            }
            if ($cgroup) {
                $r->print('<th colspan="3">'.
                &mt("in Group")." $cgroup</th>");
            }
            $r->print(<<ENDTABLEHEADFOUR);
</tr><tr><th>$lt{'aut'}</th><th>$lt{'type'}</th>
<th>$lt{'emof'}</th><th>$lt{'part'}</th><th>$lt{'pn'}</th>
<th>$lt{'gen'}</th><th>$lt{'foremf'}</th>
<th>$lt{'def'}</th><th>$lt{'femof'}</th><th>$lt{'fr'}</th>
ENDTABLEHEADFOUR

            if ($csec) {
                $r->print('<th>'.$lt{'gen'}.'</th><th>'.$lt{'foremf'}.'</th><th>'.$lt{'fr'}.'</th>');
            }

            if ($cgroup) {
                $r->print('<th>'.$lt{'gen'}.'</th><th>'.$lt{'foremf'}.'</th><th>'.$lt{'fr'}.'</th>');
            }

            if ($uname) {
                if (@usersgroups > 1) {
                    $r->print('<th>'.&mt('Control by other group?').'</th>');
                }
                $r->print('<th>'.$lt{'gen'}.'</th><th>'.$lt{'foremf'}.'</th><th>'.$lt{'fr'}.'</th>');
            }

            $r->print('</tr>');
#
# Done with the headers
# 
            my $defbgone='';
            my $defbgtwo='';
            my $defbgthree = '';

            foreach my $rid (@ids) {

                my ($inmapid)=($rid=~/\.(\d+)$/);
                if ((!$pssymb &&
                        (($pschp eq 'all') || ($allmaps{$pschp} eq $mapp{$rid})))
                        ||
                        ($pssymb && $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';
                    }
                    if ($defbgthree eq '#FFBB99') {
                        $defbgthree='#FFBBDD';
                    } else {
                        $defbgthree='#FFBB99';
                    }

                    my $thistitle='';
                    my %name=   ();
                    undef %name;
                    my %part=   ();
                    my %display=();
                    my %type=   ();
                    my %default=();
                    my $uri=&Apache::lonnet::declutter($uris{$rid});
                    my $toolsymb;
                    if ($uri =~ /ext\.tool$/) {
                        $toolsymb = $symbp{$rid};
                    }

                    my $filter=$env{'form.filter'};
                    foreach my $tempkeyp (&keysplit($keyp{$rid})) {
                        if (grep $_ eq $tempkeyp, @catmarker) {
                            my $parmname=&Apache::lonnet::metadata($uri,$tempkeyp.'.name',$toolsymb);
    # We may only want certain parameters listed
                            if ($filter) {
                                unless ($filter=~/\Q$parmname\E/) { next; }
                            }
                            $name{$tempkeyp}=$parmname;
                            $part{$tempkeyp}=&Apache::lonnet::metadata($uri,$tempkeyp.'.part',$toolsymb);

                            my $parmdis=&Apache::lonnet::metadata($uri,$tempkeyp.'.display',$toolsymb);
                            if ($allparms{$name{$tempkeyp}} ne '') {
                                my $identifier;
                                if ($parmdis =~ /(\s*\[Part.*)$/) {
                                    $identifier = $1;
                                }
                                $display{$tempkeyp} = $allparms{$name{$tempkeyp}}.$identifier;
                            } else {
                                $display{$tempkeyp} = $parmdis;
                            }
                            unless ($display{$tempkeyp}) { $display{$tempkeyp}=''; }
                            $display{$tempkeyp}.=' ('.$name{$tempkeyp}.')';
                            $default{$tempkeyp}=&Apache::lonnet::metadata($uri,$tempkeyp,$toolsymb);
                            $type{$tempkeyp}=&Apache::lonnet::metadata($uri,$tempkeyp.'.type',$toolsymb);
                            $thistitle=&Apache::lonnet::metadata($uri,$tempkeyp.'.title',$toolsymb);
                        }
                    }
                    my $totalparms=scalar(keys(%name));
                    if ($totalparms>0) {
                        my $firstrow=1;
                        my $title=&Apache::lonnet::gettitle($symbp{$rid});
                        my $navmap = Apache::lonnavmaps::navmap->new();
                        my @recurseup;
                        if (ref($navmap) && $mapp{$rid}) {
                            @recurseup = $navmap->recurseup_maps($mapp{$rid});
                        }
                        $r->print('<tr><td style="background-color:'.$defbgone.';"'.
                             ' rowspan='.$totalparms.
                             '><tt><font size="-1">'.
                             join(' / ',split(/\//,$uri)).
                             '</font></tt><p><b>'.
                             "<a href=\"javascript:openWindow('".
                          &Apache::lonnet::clutter($uri).'?symb='.
                          &escape($symbp{$rid}).
                             "', 'metadatafile', '450', '500', 'no', 'yes');\"".
                             " target=\"_self\">$title");

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

                        $r->print('<td style="background-color:'.$defbgone.';"'.
                                      ' rowspan='.$totalparms.
                                      '>'.$maptitles{$mapp{$rid}}.'</td>');
                        foreach my $item (&keysinorder_bytype(\%name,\%keyorder)) {
                            unless ($firstrow) {
                                $r->print('<tr>');
                            } else {
                                undef $firstrow;
                            }
                            &print_row($r,$item,\%part,\%name,\%symbp,$rid,\%default,
                                       \%type,\%display,$defbgone,$defbgtwo,
                                       $defbgthree,$parmlev,$uname,$udom,$csec,
                                       $cgroup,\@usersgroups,$noeditgrp,$readonly,
                                       \@recurseup,\%maptitles,\%allmaps_inverted,
                                       \$numreclinks);
                        }
                    }
                }
            } # end foreach ids
# -------------------------------------------------- End entry for one resource
            $r->print(&Apache::loncommon::end_data_table);
        } # end of  full
#--------------------------------------------------- Entry for parm level map
        if ($parmlev eq 'map') {
            my $defbgone = '#E0E099';
            my $defbgtwo = '#FFFF99';
            my $defbgthree = '#FFBB99';

            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 my $id (@ids) {
                    ($map)=($id =~ /([\d]*?)\./);
                    my $rid = $id;

#                  $r->print("$mapid:$map:   $rid <br /> \n");

                    if ($map eq $mapid) {
                        my $uri=&Apache::lonnet::declutter($uris{$rid});
                        my $toolsymb;
                        if ($uri =~ /ext\.tool$/) {
                            $toolsymb = $symbp{$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 my $fullkeyp (&keysplit($keyp{$rid})) {
                            my $tempkeyp = $fullkeyp;
                            $tempkeyp =~ s/_\w+_/_0_/;

                            if ((grep $_ eq $fullkeyp, @catmarker) &&(!$name{$tempkeyp})) {
                                $part{$tempkeyp}="0";
                                $name{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp.'.name',$toolsymb);
                                my $parmdis=&Apache::lonnet::metadata($uri,$fullkeyp.'.display',$toolsymb);
                                if ($allparms{$name{$tempkeyp}} ne '') {
                                    my $identifier;
                                    if ($parmdis =~ /(\s*\[Part.*)$/) {
                                        $identifier = $1;
                                    }
                                    $display{$tempkeyp} = $allparms{$name{$tempkeyp}}.$identifier;
                                } else {
                                    $display{$tempkeyp} = $parmdis;
                                }
                                unless ($display{$tempkeyp}) { $display{$tempkeyp}=''; }
                                $display{$tempkeyp}.=' ('.$name{$tempkeyp}.')';
                                $display{$tempkeyp} =~ s/_\w+_/_0_/;
                                $default{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp,$toolsymb);
                                $type{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp.'.type',$toolsymb);
                              }
                        } # end loop through keys
                    }
                } # end loop through ids

#---------------------------------------------------- print header information
                my $foldermap=&mt($maptitle=~/^uploaded/?'Folder':'Map');
                my $showtitle=$maptitles{$maptitle}.($maptitle!~/^uploaded/?' ['.$maptitle.']':'');
                my $tmp="";
                if ($uname) {
                    my $person=&Apache::loncommon::plainname($uname,$udom);
                    $tmp.=&mt("User")." <font color=\"red\"><i>$uname \($person\) </i></font> ".
                        &mt('in')." \n";
                } else {
                    $tmp.="<font color=\"red\"><i>".&mt('all').'</i></font> '.&mt('users in')." \n";
                }
                if ($cgroup) {
                    $tmp.=&mt("Group")." <font color=\"red\"><i>$cgroup".
                              "</i></font> ".&mt('of')." \n";
                    $csec = '';
                } elsif ($csec) {
                    $tmp.=&mt("Section")." <font color=\"red\"><i>$csec".
                              "</i></font> ".&mt('of')." \n";
                }
                $r->print('<div align="center"><h4>'
                         .&mt('Set Defaults for All Resources in [_1]Specifically for [_2][_3]'
                             ,$foldermap.'<br /><font color="red"><i>'.$showtitle.'</i></font><br />'
                             ,$tmp
                             ,'<font color="red"><i>'.$coursename.'</i></font>'
                             )
                         ."<br /></h4>\n"
                );
#---------------------------------------------------------------- print table
                $r->print('<p>'.&Apache::loncommon::start_data_table()
                         .&Apache::loncommon::start_data_table_header_row()
                         .'<th>'.&mt('Parameter Name').'</th>'
                         .'<th>'.&mt('Value').'</th>'
                         .'<th>'.&mt('Parameter in Effect').'</th>'
                         .&Apache::loncommon::end_data_table_header_row()
                );

                my $navmap = Apache::lonnavmaps::navmap->new();
                my @recurseup;
                if (ref($navmap)) {
                     my $mapres = $navmap->getByMapPc($mapid);
                     if (ref($mapres)) {
                         @recurseup = $navmap->recurseup_maps($mapres->src());
                     }
                }


                foreach my $item (&keysinorder(\%name,\%keyorder)) {
                    $r->print(&Apache::loncommon::start_data_table_row());
                    &print_row($r,$item,\%part,\%name,\%symbp,$mapid,\%default,
                           \%type,\%display,$defbgone,$defbgtwo,$defbgthree,
                           $parmlev,$uname,$udom,$csec,$cgroup,'',$noeditgrp,
                           $readonly,\@recurseup,\%maptitles,\%allmaps_inverted,
                           \$numreclinks);
                }
                $r->print(&Apache::loncommon::end_data_table().'</p>'
                         .'</div>'
                );
            } # 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';
            my $defbgthree = '#FFBB99';

#-------------------------------------------- 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 $id (@ids) {
                my $rid = $id;

                my $uri=&Apache::lonnet::declutter($uris{$rid});
                my $toolsymb;
                if ($uri =~ /ext\.tool$/) {
                    $toolsymb = $symbp{$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 my $fullkeyp (&keysplit($keyp{$rid})) {
                    my $tempkeyp = $fullkeyp;
                    $tempkeyp =~ s/_\w+_/_0_/;
                    if ((grep $_ eq $fullkeyp, @catmarker) &&(!$name{$tempkeyp})) {
                        $part{$tempkeyp}="0";
                        $name{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp.'.name',$toolsymb);
                        my $parmdis=&Apache::lonnet::metadata($uri,$fullkeyp.'.display',$toolsymb);
                        if ($allparms{$name{$tempkeyp}} ne '') {
                            my $identifier;
                            if ($parmdis =~ /(\s*\[Part.*)$/) {
                                $identifier = $1;
                            }
                            $display{$tempkeyp} = $allparms{$name{$tempkeyp}}.$identifier;
                        } else {
                            $display{$tempkeyp} = $parmdis;
                        }
                        unless ($display{$tempkeyp}) { $display{$tempkeyp}=''; }
                        $display{$tempkeyp}.=' ('.$name{$tempkeyp}.')';
                        $display{$tempkeyp} =~ s/_\w+_/_0_/;
                        $default{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp,$toolsymb);
                        $type{$tempkeyp}=&Apache::lonnet::metadata($uri,$fullkeyp.'.type',$toolsymb);
                    }
                } # end loop through keys
            } # end loop through ids

#---------------------------------------------------- print header information
            my $setdef=&mt("Set Defaults for All Resources in Course");
            $r->print(<<ENDMAPONE);
<center>
<h4>$setdef
<font color="red"><i>$coursename</i></font><br />
ENDMAPONE
            if ($uname) {
                my $person=&Apache::loncommon::plainname($uname,$udom);
                $r->print(" ".&mt("User")."<font color=\"red\"> <i>$uname \($person\) </i></font> \n");
            } else {
                $r->print("<i><font color=\"red\"> ".&mt("ALL")."</i> ".&mt("USERS")."</font> \n");
            }

            if ($csec) {$r->print(&mt("Section")."<font color=\"red\"> <i>$csec</i></font>\n")};
            if ($cgroup) {$r->print(&mt("Group")."<font color=\"red\"> <i>$cgroup</i></font>\n")};
            $r->print("</h4>\n");
#---------------------------------------------------------------- print table
            $r->print('<p>'.&Apache::loncommon::start_data_table()
                     .&Apache::loncommon::start_data_table_header_row()
                     .'<th>'.&mt('Parameter Name').'</th>'
                     .'<th>'.&mt('Default Value').'</th>'
                     .'<th>'.&mt('Parameter in Effect').'</th>'
                     .&Apache::loncommon::end_data_table_header_row()
            );

            foreach my $item (&keysinorder(\%name,\%keyorder)) {
                $r->print(&Apache::loncommon::start_data_table_row());
                &print_row($r,$item,\%part,\%name,\%symbp,$mapid,\%default,
                           \%type,\%display,$defbgone,$defbgtwo,$defbgthree,
                           $parmlev,$uname,$udom,$csec,$cgroup,'',$noeditgrp,
                           $readonly);
            }
            $r->print(&Apache::loncommon::end_data_table()
                     .'</p>'
                     .'</center>'
            );
        } # end of $parmlev eq general
    }
    $r->print('</form>');
    if ($numreclinks) {
        $r->print(<<"END");
<form name="recurseform" action="/adm/parmset?action=settable" method="post">
<input type="hidden" name="pschp" />
<input type="hidden" name="pscat" />
<input type="hidden" name="psprt" />
<input type="hidden" name="hideparmsel" value="hidden" />
</form>
<script type="text/javascript">
function pjumprec(rid,name,part) {
    document.forms.recurseform.pschp.value = rid;
    document.forms.recurseform.pscat.value = name;
    document.forms.recurseform.psprt.value = part;
    document.forms.recurseform.submit();
    return false;
}
</script>
END
    }
    &endSettingsScreen($r);
    $r->print(&Apache::loncommon::end_page());
} # end sub assessparms



##################################################
# OVERVIEW MODE
##################################################

my $tableopen; # boolean, true if HTML table is already opened

# Returns HTML with the HTML table start tag and header, unless the table is already opened.
# @param {boolean} $readonly - true if values cannot be edited (otherwise more columns are added)
# @returns {string}
sub tablestart {
    my ($readonly,$is_map) = @_;
    if ($tableopen) {
        return '';
    } else {
        $tableopen=1;
        my $output = &Apache::loncommon::start_data_table().'<tr><th>'.&mt('Parameter').'</th>';
        if ($readonly) {
            $output .= '<th>'.&mt('Current value').'</th>';
        } else {
            $output .= '<th>'.&mt('Delete').'</th>'.
                       '<th>'.&mt('Set to ...').'</th>';
            if ($is_map) {
                $output .= '<th>'.&mt('Recursive?').'</th>';
            }
        }
        $output .= '</tr>';
        return $output;
    }
}

# Returns HTML with the HTML table end tag, unless the table is not opened.
# @returns {string}
sub tableend {
    if ($tableopen) {
        $tableopen=0;
        return &Apache::loncommon::end_data_table();
    } else {
        return'';
    }
}

# Reads course and user information.
# If the context is looking for a scalar, returns the course parameters hash (result of lonnet::get_courseresdata, dump of course's resourcedata.db) with added student data from lonnet::get_userresdata (which reads the user's resourcedata.db).
# The key for student data is modified with '[useropt:'.username.':'.userdomain.'].'.
# If the context is looking for a list, returns a list with the scalar data and the class list.
# @param {string} $crs - course number
# @param {string} $dom - course domain
# @returns {hash reference|Array}
sub readdata {
    my ($crs,$dom)=@_;
# Read coursedata
    my $resourcedata=&Apache::lonnet::get_courseresdata($crs,$dom);
# Read userdata

    my $classlist=&Apache::loncoursedata::get_classlist();
    foreach my $user (keys(%$classlist)) {
        if ($user=~/^($match_username)\:($match_domain)$/) {
            my ($tuname,$tudom)=($1,$2);
            my $useropt=&Apache::lonnet::get_userresdata($tuname,$tudom);
            foreach my $userkey (keys(%{$useropt})) {
                if ($userkey=~/^\Q$env{'request.course.id'}\E/) {
                    my $newkey=$userkey;
                    $newkey=~s/^($env{'request.course.id'}\.)/$1\[useropt\:$tuname\:$tudom\]\./;
                    $$resourcedata{$newkey}=$$useropt{$userkey};
                }
            }
        }
    }
    if (wantarray) {
        return ($resourcedata,$classlist);
    } else {
        return $resourcedata;
    }
}


# Stores parameter data, using form parameters directly.
#
# Uses the following form parameters. The variable part in the names is a resourcedata key (except for a modification for user data).
# set_* (except settext, setipallow, setipdeny, setdeeplink) - set a parameter value
# del_* - remove a parameter
# datepointer_* - set a date parameter (value is key_* refering to a set of other form parameters)
# dateinterval_* - set a date interval parameter (value refers to more form parameters)
# key_* - date values
# days_* - for date intervals
# hours_* - for date intervals
# minutes_* - for date intervals
# seconds_* - for date intervals
# done_* - for date intervals
# typeof_* - parameter type
# 
# @param {Apache2::RequestRec} $r - the Apache request
# @param {string} $crs - course number
# @param {string} $dom - course domain
sub storedata {
    my ($r,$crs,$dom)=@_;
# Set userlevel immediately
# Do an intermediate store of course level
    my $olddata=&readdata($crs,$dom);
    my %newdata=();
    undef %newdata;
    my @deldata=();
    my @delrec=();
    my @delnonrec=();
    undef @deldata;
    my ($got_chostname,$chostname,$cmajor,$cminor);
    my $now = time;
    foreach my $key (keys(%env)) {
        if ($key =~ /^form\.([a-z]+)\_(.+)$/) {
            my $cmd=$1;
            my $thiskey=$2;
            my ($altkey,$recursive,$tkey,$tkeyrec,$tkeynonrec);
            next if ($cmd eq 'rec' || $cmd eq 'settext' || $cmd eq 'setipallow' || $cmd eq 'setipdeny' || $cmd eq 'setdeeplink');
            if ((($cmd eq 'set') || ($cmd eq 'datepointer') || ($cmd eq 'dateinterval') || ($cmd eq 'del')) && 
                 ($thiskey =~ /(?:sequence|page)\Q___(all)\E/)) {
                unless ($thiskey =~ /(encrypturl|hiddenresource)$/) {
                    $altkey = $thiskey;
                    $altkey =~ s/\Q___(all)\E/___(rec)/;
                    if ($env{'form.rec_'.$thiskey}) {
                        $recursive = 1;
                    }
                }
            }
            my ($tuname,$tudom)=&extractuser($thiskey);
            if ($tuname) {
                $tkey=$thiskey;
                $tkey=~s/\.\[useropt\:$tuname\:$tudom\]\./\./;
                if ($altkey) {
                    $tkeynonrec = $tkey; 
                    $tkeyrec = $altkey;
                    $tkeyrec=~s/\.\[useropt\:$tuname\:$tudom\]\./\./;
                }
            }
            if ($cmd eq 'set' || $cmd eq 'datepointer' || $cmd eq 'dateinterval') {
                my ($data, $typeof, $text, $name, $valchk, $valmatch, $namematch);
                if ($cmd eq 'set') {
                    $data=$env{$key};
                    $valmatch = '';
                    $valchk = $data;
                    $typeof=$env{'form.typeof_'.$thiskey};
                    $text = &mt('Saved modified parameter for');
                    if ($typeof eq 'string_questiontype') {
                        $name = 'type';
                    } elsif (($typeof eq 'string_lenient') || ($typeof eq 'string_deeplink')) {
                        ($name) = ($typeof =~ /^string_(lenient|deeplink)$/);
                        my $stringmatch = &standard_string_matches($typeof);
                        if (ref($stringmatch) eq 'ARRAY') {
                            foreach my $item (@{$stringmatch}) {
                                if (ref($item) eq 'ARRAY') {
                                    my ($regexpname,$pattern) = @{$item};
                                    if ($pattern ne '') {
                                        if ($data =~ /$pattern/) {
                                            $valmatch = $regexpname;
                                            $valchk = '';
                                            last;
                                        }
                                    }
                                }
                            }
                        }
                    } elsif ($typeof eq 'string_discussvote') {
                        $name = 'discussvote';
                    } elsif ($typeof eq 'string_examcode') {
                        $name = 'examcode';
                        if (&Apache::lonnet::validCODE($data)) {
                            $valchk = 'valid';
                        }
                    } elsif ($typeof eq 'string_yesno') {
                        if ($thiskey =~ /\.retrypartial$/) {
                            $name = 'retrypartial';
                        }
                    }
                } elsif ($cmd eq 'datepointer') {
                    $data=&Apache::lonhtmlcommon::get_date_from_form($env{$key});
                    $typeof=$env{'form.typeof_'.$thiskey};
                    $text = &mt('Saved modified date for');
                    if ($typeof eq 'date_start') {
                        if ($thiskey =~ /\.printstartdate$/) {
                            $name = 'printstartdate';
                            if (($data) && ($data > $now)) {
                                $valchk = 'future';
                            }
                        }
                    } elsif ($typeof eq 'date_end') {
                        if ($thiskey =~ /\.printenddate$/) {
                            $name = 'printenddate';
                            if (($data) && ($data < $now)) {
                                $valchk = 'past';
                            }
                        }
                    }
                } elsif ($cmd eq 'dateinterval') {
                    $data=&get_date_interval_from_form($thiskey);
                    if ($thiskey =~ /\.interval$/) {
                        $name = 'interval';
                        my $intervaltype = &get_intervaltype($name);
                        my $intervalmatch = &standard_interval_matches($intervaltype);
                        if (ref($intervalmatch) eq 'ARRAY') {
                            foreach my $item (@{$intervalmatch}) {
                                if (ref($item) eq 'ARRAY') {
                                    my ($regexpname,$pattern) = @{$item};
                                    if ($pattern ne '') {
                                        if ($data =~ /$pattern/) {
                                            $valmatch = $regexpname;
                                            $valchk = '';
                                            last;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $typeof=$env{'form.typeof_'.$thiskey};
                    $text = &mt('Saved modified date for');
                }
                if ($recursive) {
                    $namematch = 'maplevelrecurse';
                }
                if (($name ne '') || ($namematch ne '')) {
                    my ($needsrelease,$needsnewer);
                    if ($name ne '') {
                        $needsrelease = $Apache::lonnet::needsrelease{"parameter:$name:$valchk:$valmatch:"};
                        if ($needsrelease) {
                            unless ($got_chostname) {
                                ($chostname,$cmajor,$cminor)=&parameter_release_vars();
                                $got_chostname = 1;
                            }
                            $needsnewer = &parameter_releasecheck($name,$valchk,$valmatch,undef,
                                                                $needsrelease,
                                                                $cmajor,$cminor);
                        }
                    }
                    if ($namematch ne '') {
                        if ($needsnewer) {
                            undef($namematch);
                        } else {
                            my $currneeded;
                            if ($needsrelease) {
                                $currneeded = $needsrelease;
                            }
                            $needsrelease =
                                $Apache::lonnet::needsrelease{"parameter::::$namematch"};
                            if (($needsrelease) &&
                                    (($currneeded eq '') || ($needsrelease < $currneeded))) {
                                unless ($got_chostname) {
                                    ($chostname,$cmajor,$cminor) = &parameter_release_vars();
                                    $got_chostname = 1;
                                }
                                $needsnewer = &parameter_releasecheck(undef,$valchk,$valmatch,
                                    $namematch, $needsrelease,$cmajor,$cminor);
                            } else {
                                undef($namematch);
                            }
                        }
                    }
                    if ($needsnewer) {
                        $r->print('<br />'.&oldversion_warning($name,$namematch,$data,
                                                            $chostname,$cmajor,
                                                            $cminor,$needsrelease));
                        next;
                    }
                }
                my ($reconlychg,$haschange,$storekey);
                if ($tuname) {
                    my $ustorekey;
                    if ($altkey) {
                        if ($recursive) {
                            if (exists($$olddata{$thiskey})) {
                                if ($$olddata{$thiskey} eq $data) {
                                    $reconlychg = 1;
                                }
                                &Apache::lonnet::del('resourcedata',[$tkeynonrec,$tkeynonrec.'.type'],$tudom,$tuname);
                            }
                            if (exists($$olddata{$altkey})) {
                                if (defined($data) && $$olddata{$altkey} ne $data) {
                                    $haschange = 1;
                                }
                            } elsif ((!$reconlychg) && ($data ne '')) {
                                $haschange = 1;
                            }
                            $ustorekey = $tkeyrec;
                        } else {
                            if (exists($$olddata{$altkey})) {
                                if ($$olddata{$altkey} eq $data) {
                                    $reconlychg = 1;
                                }
                                &Apache::lonnet::del('resourcedata',[$tkeyrec,$tkeyrec.'.type'],$tudom,$tuname);
                            }
                            if (exists($$olddata{$thiskey})) {
                                if (defined($data) && $$olddata{$thiskey} ne $data) {
                                    $haschange = 1;
                                }
                            } elsif ((!$reconlychg) && ($data ne '')) {
                                $haschange = 1;
                            }
                            $ustorekey = $tkeynonrec;
                        }
                    } else {
                        if (exists($$olddata{$tkey})) {
                            if (defined($data) && $$olddata{$tkey} ne $data) {
                                $haschange = 1;
                            }
                            $ustorekey = $tkey;
                        }
                    }
                    if ($haschange || $reconlychg)  {
                        unless ($env{'form.del_'.$thiskey}) {
                            if (&Apache::lonnet::put('resourcedata',{$ustorekey=>$data,
                                                                     $ustorekey.'.type' => $typeof},
                                                                     $tudom,$tuname) eq 'ok') {
                                &log_parmset({$ustorekey=>$data,$ustorekey.'.type' => $typeof},0,$tuname,$tudom);
                                $r->print('<br />'.$text.' '.
                                          &Apache::loncommon::plainname($tuname,$tudom));
                            } else {
                                $r->print('<div class="LC_error">'.
                                          &mt('Error saving parameters').'</div>');
                            }
                            &Apache::lonnet::devalidateuserresdata($tuname,$tudom);
                        }
                    }
                } else {
                    if ($altkey) {
                        if ($recursive) {
                            if (exists($$olddata{$thiskey})) {
                                if ($$olddata{$thiskey} eq $data) {
                                    $reconlychg = 1;
                                }
                                push(@delnonrec,($thiskey,$thiskey.'.type'));
                            }
                            if (exists($$olddata{$altkey})) {
                                if (defined($data) && $$olddata{$altkey} ne $data) {
                                    $haschange = 1;
                                }
                            } elsif (($data ne '') && (!$reconlychg)) {
                                $haschange = 1;
                            }
                            $storekey = $altkey;
                        } else {
                            if (exists($$olddata{$altkey})) {
                                if ($$olddata{$altkey} eq $data) {
                                    $reconlychg = 1;
                                }
                                push(@delrec,($altkey,$altkey.'.type'));
                            } 
                            if (exists($$olddata{$thiskey})) {
                                if (defined($data) && $$olddata{$thiskey} ne $data) {
                                    $haschange = 1;
                                }
                            } elsif (($data ne '') && (!$reconlychg)) {
                                $haschange = 1;
                            }
                            $storekey = $thiskey;
                        }
                    } else {
                        if (defined($data) && $$olddata{$thiskey} ne $data) {
                            $haschange = 1;
                            $storekey = $thiskey;
                        }
                    }
                }
                if ($reconlychg || $haschange) {
                    unless ($env{'form.del_'.$thiskey}) {
                        $newdata{$storekey}=$data;
                        $newdata{$storekey.'.type'}=$typeof;
                    }
                }
            } elsif ($cmd eq 'del') {
                if ($tuname) {
                    my $error;
                    if ($altkey) {  
                        if (exists($$olddata{$altkey})) {
                            if (&Apache::lonnet::del('resourcedata',[$tkeyrec,$tkeyrec.'.type'],$tudom,$tuname) eq 'ok') {
                                &log_parmset({$tkeyrec=>''},1,$tuname,$tudom);
                                if ($recursive) {
                                    $r->print('<br />'.&mt('Deleted parameter for').' '.&Apache::loncommon::plainname($tuname,$tudom));
                                }
                            } elsif ($recursive) {
                                $error = 1;
                            }
                        }
                        if (exists($$olddata{$thiskey})) {
                            if (&Apache::lonnet::del('resourcedata',[$tkeynonrec,$tkeynonrec.'.type'],$tudom,$tuname) eq 'ok') {
                                &log_parmset({$tkeynonrec=>''},1,$tuname,$tudom);
                                unless ($recursive) {
                                    $r->print('<br />'.&mt('Deleted parameter for').' '.&Apache::loncommon::plainname($tuname,$tudom));
                                }
                            } elsif (!$recursive) {
                                $error = 1;
                            }
                        }
                    } else {
                        if (exists($$olddata{$thiskey})) {
                            if (&Apache::lonnet::del('resourcedata',[$tkey,$tkey.'.type'],$tudom,$tuname) eq 'ok') {
                                &log_parmset({$tkey=>''},1,$tuname,$tudom);
                                $r->print('<br />'.&mt('Deleted parameter for').' '.&Apache::loncommon::plainname($tuname,$tudom));
                            } else {
                                $error = 1;
                            }
                        }
                    }
                    if ($error) { 
                        $r->print('<div class="LC_error">'.
                            &mt('Error deleting parameters').'</div>');
                    }
                    &Apache::lonnet::devalidateuserresdata($tuname,$tudom);
                } else {
                    if ($altkey) {
                        if (exists($$olddata{$altkey})) {
                            unless (grep(/^\Q$altkey\E$/,@delrec)) {
                                push(@deldata,($altkey,$altkey.'.type'));
                            }
                        }
                        if (exists($$olddata{$thiskey})) {
                            unless (grep(/^\Q$thiskey\E$/,@delnonrec)) {
                                push(@deldata,($thiskey,$thiskey.'.type'));
                            }
                        }
                    } elsif (exists($$olddata{$thiskey})) {
                        push(@deldata,($thiskey,$thiskey.'.type'));
                    }
                }
            }
        }
    }
# Store all course level
    my $delentries=$#deldata+1;
    my @alldels;
    if (@delrec) {
        push(@alldels,@delrec);
    }
    if (@delnonrec) {
        push(@alldels,@delnonrec);
    }
    if (@deldata) {
        push(@alldels,@deldata);
    }
    my @newdatakeys=keys(%newdata);
    my $putentries=$#newdatakeys+1;
    my ($delresult,$devalidate);
    if (@alldels) {
        if (&Apache::lonnet::del('resourcedata',\@alldels,$dom,$crs) eq 'ok') {
            my %loghash=map { $_ => '' } @alldels;
            &log_parmset(\%loghash,1);
            if ($delentries) {
                $r->print('<h2>'.&mt('Deleted [quant,_1,parameter]',$delentries/2).'</h2>');
            }
        } elsif ($delentries) {
            $r->print('<div class="LC_error">'.
                &mt('Error deleting parameters').'</div>');
        }
        $devalidate = 1; 
    }
    if ($putentries) {
        if (&Apache::lonnet::put('resourcedata',\%newdata,$dom,$crs) eq 'ok') {
                    &log_parmset(\%newdata,0);
            $r->print('<h3>'.&mt('Saved [quant,_1,parameter]',$putentries/2).'</h3>');
        } else {
            $r->print('<div class="LC_error">'.
                &mt('Error saving parameters').'</div>');
        }
        $devalidate = 1; 
    }
    if ($devalidate) {
        &Apache::lonnet::devalidatecourseresdata($crs,$dom);
    }
}

# Returns the username and domain from a key created in readdata from a resourcedata key.
#
# @param {string} $key - the key
# @returns {Array}
sub extractuser {
    my $key=shift;
    return ($key=~/^$env{'request.course.id'}.\[useropt\:($match_username)\:($match_domain)\]\./);
}

# Parses a parameter key and returns the components.
#
# @param {string} $key - 
# @param {hash reference} $listdata - 
# @return {Array} - (student, resource, part, parameter)
sub parse_listdata_key {
    my ($key,$listdata) = @_;
    # split into student/section affected, and
    # the realm (folder/resource part and parameter
    my ($student,$realm) =
    ($key=~/^\Q$env{'request.course.id'}\E\.\[([^\.]+)\]\.(.+)$/);
    # if course wide student would be undefined
    if (!defined($student)) {
        ($realm)=($key=~/^\Q$env{'request.course.id'}\E\.(.+)$/);
    }
    # strip off the .type if it's not the Question type parameter
    if ($realm=~/\.type$/ && !exists($listdata->{$key.'.type'})) {
        $realm=~s/\.type//;
    }
    # split into resource+part and parameter name
    my ($res,    $parm) = ($realm=~/^(.*)\.(.*)$/);
       ($res, my $part) = ($res  =~/^(.*)\.(.*)$/);
    return ($student,$res,$part,$parm);
}

# Prints HTML with forms for the given parameter data in overview mode (newoverview or overview).
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {hash reference} $resourcedata - parameter data returned by readdata
# @param {hash reference} $listdata - data created in secgroup_lister, course id.[section id].part.name -> 1 or course id.[section id].part.name.type -> parameter type
# @param {string} $sortorder - realmstudent|studentrealm
# @param {string} $caller - name of the calling sub (overview|newoverview)
# @param {hash reference} $classlist - from loncoursedata::get_classlist
# @param {boolean} $readonly - true if editing not allowed
# @returns{integer} - number of $listdata parameters processed
sub listdata {
    my ($r,$resourcedata,$listdata,$sortorder,$caller,$classlist,$readonly)=@_;
    
# Start list output

    my $oldsection='';
    my $oldrealm='';
    my $oldpart='';
    my $pointer=0;
    $tableopen=0;
    my $foundkeys=0;
    my %keyorder=&standardkeyorder();
    my $readonlyall = $readonly;

    my ($secidx,%grouphash);
    if (($env{'request.course.sec'} ne '') && ($caller eq 'overview')) {
        $secidx = &Apache::loncoursedata::CL_SECTION();
        if (&Apache::lonnet::allowed('mdg',$env{'request.course.id'})) {
            %grouphash = &Apache::longroup::coursegroups();
        } elsif ($env{'request.course.groups'} ne '') {
            map { $grouphash{$_} = 1; } split(/:/,$env{'request.course.groups'});
        }
    }

    foreach my $key (sort {
        my ($astudent,$ares,$apart,$aparm) = &parse_listdata_key($a,$listdata);
        my ($bstudent,$bres,$bpart,$bparm) = &parse_listdata_key($b,$listdata);

        # get the numerical order for the param
        $aparm=$keyorder{'parameter_0_'.$aparm};
        $bparm=$keyorder{'parameter_0_'.$bparm};

        my $result=0;

        if ($sortorder eq 'realmstudent') {
            if ($ares     ne $bres    ) {
                $result = ($ares     cmp $bres);
            } elsif ($astudent ne $bstudent) {
                $result = ($astudent cmp $bstudent);
            } elsif ($apart    ne $bpart   ) {
                $result = ($apart    cmp $bpart);
            }
        } else {
            if      ($astudent ne $bstudent) {
                $result = ($astudent cmp $bstudent);
            } elsif ($ares     ne $bres    ) {
                $result = ($ares     cmp $bres);
            } elsif ($apart    ne $bpart   ) {
                $result = ($apart    cmp $bpart);
            }
        }

        if (!$result) {
            if (defined($aparm) && defined($bparm)) {
                $result = ($aparm <=> $bparm);
            } elsif (defined($aparm)) {
                $result = -1;
            } elsif (defined($bparm)) {
                $result = 1;
            }
        }

        $result;
        
    } keys(%{$listdata})) { # foreach my $key
        my $thiskey = $key;
        if ($$listdata{$thiskey.'.type'}) {
            my $thistype=$$listdata{$thiskey.'.type'};
            if ($$resourcedata{$thiskey.'.type'}) {
                $thistype=$$resourcedata{$thiskey.'.type'};
            }
            my ($middle,$part,$name)=
                ($thiskey=~/^$env{'request.course.id'}\.(?:(.+)\.)*([\w\s\-]+)\.(\w+)$/);
            my $section=&mt('All Students');
            $readonly = $readonlyall;
            my $userscope;
            my $showval = $$resourcedata{$thiskey}; 
            if ($middle=~/^\[(.*)\]/) {
                my $issection=$1;
                if ($issection=~/^useropt\:($match_username)\:($match_domain)/) {
                    my ($stuname,$studom) = ($1,$2);
                    if (($env{'request.course.sec'} ne '') && ($caller eq 'overview')) {
                        if (ref($classlist) eq 'HASH') {
                            if (ref($classlist->{$stuname.':'.$studom}) eq 'ARRAY') {
                                next unless ($classlist->{$stuname.':'.$studom}->[$secidx] eq $env{'request.course.sec'}); 
                            }
                        }
                    }
                    $section=&mt('User').": ".&Apache::loncommon::plainname($stuname,$studom);
                    $userscope = 1;
                } else {
                    if (($env{'request.course.sec'} ne '') && ($caller eq 'overview')) {
                        if (exists($grouphash{$issection})) {
                            $section=&mt('Group').': '.$issection;
                        } elsif ($issection eq $env{'request.course.sec'}) {
                            $section = &mt('Section').': '.$issection;
                        } else {
                            next; 
                        }
                    } else {
                        $section=&mt('Group/Section').': '.$issection;
                    }
                }
                $middle=~s/^\[(.*)\]//;
            } elsif (($env{'request.course.sec'} ne '') && ($caller eq 'overview')) {
                $readonly = 1;
            }
            $middle=~s/\.+$//;
            $middle=~s/^\.+//;
            my $realm='<span class="LC_parm_scope_all">'.&mt('All Resources').'</span>';
            my ($is_map,$is_recursive,$mapurl,$maplevel);
            if ($caller eq 'overview') {
                if ($middle=~/^(.+)\_\_\_\((all|rec)\)$/) {
                    $mapurl = $1;
                    $maplevel = $2;
                    $is_map = 1;
                }
            } elsif ($caller eq 'newoverview') {
                if ($middle=~/^(.+)\_\_\_\((all)\)$/) {
                    $mapurl = $1;
                    $maplevel = $2;
                    $is_map = 1;
                }
            }
            if ($is_map) {
                my $leveltitle = &mt('Folder/Map');
                unless (($name eq 'hiddenresource') || ($name eq 'encrypturl')) {   
                    if ($caller eq 'newoverview') {
                        my $altkey = $thiskey;
                        $altkey =~ s/\Q___(all)\E/___(rec)/;
                        if ((exists($$resourcedata{$altkey})) & (!exists($$resourcedata{$thiskey}))) {
                            $is_recursive = 1;
                            if ($$resourcedata{$altkey.'.type'}) {
                                $thistype=$$resourcedata{$altkey.'.type'};
                            }
                            $showval = $$resourcedata{$altkey};
                        }
                    } elsif (($caller eq 'overview') && ($maplevel eq 'rec')) {
                        $thiskey =~ s/\Q___(rec)\E/___(all)/;
                        $is_recursive = 1;
                    }
                }
                $realm='<span class="LC_parm_scope_folder">'.$leveltitle.': '.&Apache::lonnet::gettitle($mapurl).' <br /><span class="LC_parm_folder">('.$mapurl.')</span></span>';
            } elsif ($middle) {
                my ($map,$id,$url)=&Apache::lonnet::decode_symb($middle);
                $realm='<span class="LC_parm_scope_resource">'.&mt('Resource').
                    ': '.&Apache::lonnet::gettitle($middle).
                    ' <br /><span class="LC_parm_symb">('.$url.' in '.$map.' id: '.
                    $id.')</span></span>';
            }
            if ($sortorder eq 'realmstudent') {
                if ($realm ne $oldrealm) {
                    $r->print(&tableend()."\n<hr /><h1>$realm</h1>");
                    $oldrealm=$realm;
                    $oldsection='';
                }
                if ($section ne $oldsection) {
                    $r->print(&tableend()."\n<h2>$section</h2>");
                    $oldsection=$section;
                    $oldpart='';
                }
            } else {
                if ($section ne $oldsection) {
                    $r->print(&tableend()."\n<hr /><h1>$section</h1>");
                    $oldsection=$section;
                    $oldrealm='';
                }
                if ($realm ne $oldrealm) {
                    $r->print(&tableend()."\n<h2>$realm</h2>");
                    $oldrealm=$realm;
                    $oldpart='';
                }
            }
            if ($part ne $oldpart) {
                $r->print(&tableend().
                    "\n".'<span class="LC_parm_part">'.&mt('Part').": $part</span>");
                $oldpart=$part;
            }
    #
    # Ready to print
    #
            my $parmitem = &standard_parameter_names($name);
            $r->print(&tablestart($readonly,$is_map).
                &Apache::loncommon::start_data_table_row().
                '<td><b>'.&mt($parmitem).
                '</b></td>');
            unless ($readonly) {
                my $disabled;
                if (($name eq 'availablestudent') &&
                    (($showval eq '') || ($userscope))) {
                    $disabled = ' disabled="disabled"';
                }
                $r->print('<td><input type="checkbox" name="del_'.
                        $thiskey.'"'.$disabled.' /></td>');
            }
            $r->print('<td>');
            $foundkeys++;
            if (&isdateparm($thistype)) {
                my $jskey='key_'.$pointer;
                my $state;
                $pointer++;
                if ($readonly) {
                    $state = 'disabled';
                }
                $r->print(
                    &Apache::lonhtmlcommon::date_setter('parmform',
                                                        $jskey,
                                                        $showval,
                                                        '',1,$state));
                unless  ($readonly) {
                    $r->print(
    '<input type="hidden" name="datepointer_'.$thiskey.'" value="'.$jskey.'" />'.
    (($showval!=0)?'<span class="LC_nobreak"><a href="/adm/parmset?&action=dateshift1&timebase='.$showval.'">'.
    &mt('Shift all dates based on this date').'</a></span>':'').
    &date_sanity_info($showval)
                    );
                }
            } elsif ($thistype eq 'date_interval') {
                $r->print(&date_interval_selector($thiskey,$name,
                          $showval,$readonly));
            } elsif ($thistype =~ m/^string/) {
                if ($name eq 'availablestudent') {
                    $readonly = 1;
                }
                $r->print(&string_selector($thistype,$thiskey,
                          $showval,$name,$readonly));
            } else {
                $r->print(&default_selector($thiskey,$showval,$readonly));
            }
            unless ($readonly) {
                $r->print('<input type="hidden" name="typeof_'.$thiskey.'" value="'.
                        $thistype.'" />');
            }
            $r->print('</td>');
            if ($is_map) {
                if (($name eq 'encrypturl') || ($name eq 'hiddenresource')) {
                    $r->print('<td><table><tr><td>'.&mt('Yes').'</td></tr></table></td>');
                } else {
                    my ($disabled,$recon,$recoff);
                    if ($readonly) {
                        $disabled = ' disabled="disabled"';
                    }
                    if ($is_recursive) {
                        $recon = ' checked="checked"';
                    } else {
                        $recoff = ' checked="checked"';
                    }
                    $r->print('<td><table><tr><td><label><input type="radio" name="rec_'.$thiskey.'" value="1"'.$recon.$disabled.' />'.&mt('Yes').'</label>'.
                              '</td><td><label><input type="radio" name="rec_'.$thiskey.'" value="0"'.$recoff.$disabled.' />'.&mt('No').'</label></td></tr></table></td>');
                }
            }
            $r->print(&Apache::loncommon::end_data_table_row());
        }
    }
    return $foundkeys;
}

# Returns a string representing the interval, directly using form data matching the given key.
# The returned string may also include information related to proctored exams.
# Format: seconds['_done'[':'done button title':']['_proctor'['_'proctor key]]]
#
# @param {string} $key - suffix for form fields related to the interval
# @returns {string}
sub get_date_interval_from_form {
    my ($key) = @_;
    my $seconds = 0;
    foreach my $which (['days', 86400],
               ['hours', 3600],
               ['minutes', 60],
               ['seconds',  1]) {
        my ($name, $factor) = @{ $which };
        if (defined($env{'form.'.$name.'_'.$key})) {
            $seconds += $env{'form.'.$name.'_'.$key} * $factor;
        }
    }
    if (($key =~ /\.interval$/) &&
            (($env{'form.done_'.$key} eq '_done') || ($env{'form.done_'.$key} eq '_done_proctor'))) {
        if ($env{'form.done_'.$key.'_buttontext'}) {
            $env{'form.done_'.$key.'_buttontext'} =~ s/\://g;
            $seconds .= '_done:'.$env{'form.done_'.$key.'_buttontext'}.':';
            if ($env{'form.done_'.$key} eq '_done_proctor') {
                $seconds .= '_proctor';
            }
        } else {
            $seconds .= $env{'form.done_'.$key}; 
        }
        if (($env{'form.done_'.$key} eq '_done_proctor') && 
                ($env{'form.done_'.$key.'_proctorkey'})) {
            $seconds .= '_'.$env{'form.done_'.$key.'_proctorkey'};
        }
    }
    return $seconds;
}


# Returns HTML to enter a text value for a parameter.
#
# @param {string} $thiskey - parameter key
# @param {string} $showval - the current value
# @param {boolean} $readonly - true if the field should not be made editable
# @returns {string}
sub default_selector {
    my ($thiskey, $showval, $readonly) = @_;
    my $disabled;
    if ($readonly) {
        $disabled = ' disabled="disabled"';
    }
    return '<input type="text" name="set_'.$thiskey.'" value="'.$showval.'"'.$disabled.' />';
}

# Returns HTML to enter allow/deny rules related to IP addresses.
#
# @param {string} $thiskey - parameter key
# @param {string} $showval - the current value
# @param {boolean} $readonly - true if the fields should not be made editable
# @returns {string}
sub string_ip_selector {
    my ($thiskey, $showval, $readonly) = @_;
    my %access = (
                   allow => [],
                   deny  => [],
                 );
    if ($showval ne '') {
        my @current;
        if ($showval =~ /,/) {
            @current = split(/,/,$showval);
        } else {
            @current = ($showval);
        }
        foreach my $item (@current) {
            if ($item =~ /^\!([\[\]a-zA-Z\.\d\*\-]+)$/) {
                push(@{$access{'deny'}},$1);
            } elsif ($item =~ /^([\[\]a-zA-Z\.\d\*\-]+)$/) {
                push(@{$access{'allow'}},$item);
            }
        }
    }
    if (!@{$access{'allow'}}) {
        @{$access{'allow'}} = ('');
    }
    if (!@{$access{'deny'}}) {
        @{$access{'deny'}} = ('');
    }
    my ($disabled,$addmore);
    if ($readonly) {
        $disabled=' disabled="disabled"';
    } else {
        $addmore = "\n".'<button class="LC_add_ipacc_button">'.&mt('Add more').'</button>';
    }
    my $output = '<input type="hidden" name="set_'.$thiskey.'" />
<table><tr><th>'.&mt('Allow from').'</th><th>'.&mt('Deny from').'</th></tr><tr>';
    foreach my $acctype ('allow','deny') {
        $output .= '
<td valign="top">
<div class="LC_string_ipacc_wrap" id="LC_string_ipacc_'.$acctype.'_'.$thiskey.'">
  <div class="LC_string_ipacc_inner">'."\n";
        my $num = 0;
        foreach my $curr (@{$access{$acctype}}) {
            $output .= '<div><input type="text" name="setip'.$acctype.'_'.$thiskey.'" value="'.$curr.'"'.$disabled.' />';
            if ($num > 0) {
                $output .= '<a href="#" class="LC_remove_ipacc">'.&mt('Remove').'</a>'; 
            }
            $output .= '</div>'."\n";
            $num ++;
        }
        $output .= '
  </div>'.$addmore.'
</div>
</td>';
   }
   $output .= '
</tr>
</table>'."\n";
    return $output;
}

sub string_deeplink_selector {
    my ($thiskey, $showval, $readonly) = @_;
    my (@components,%values,@current,%titles,%options,%optiontext,%defaults,
        %selectnull,%domlti,%crslti,@possmenus);
    @components = ('state','others','listing','scope','protect','menus');
    %titles = &Apache::lonlocal::texthash (
                  state   => 'Access status',
                  others  => 'Hide other resources',
                  listing => 'In Contents and/or Gradebook',
                  scope   => 'Access scope for link',
                  protect => 'Link protection',
                  menus   => 'Menu Items Displayed',
              );
    %options = (
                   state   => ['only','off','both'],
                   others  => ['hide','unhide'],
                   listing => ['full','absent','grades','details','datestatus'],
                   scope   => ['res','map','rec'],
                   protect => ['none','key','ltid','ltic'],
                   menus   => ['std','colls'],
               );
    %optiontext = &Apache::lonlocal::texthash (
                    only       => 'deep only',
                    off        => 'deeplink off',
                    both       => 'regular + deep',
                    hide       => 'Hidden',
                    unhide     => 'Unhidden',
                    full       => 'Listed (linked) in both',
                    absent     => 'Not listed',
                    grades     => 'Listed in grades only',
                    details    => 'Listed (unlinked) in both',
                    datestatus => 'Listed (unlinked) inc. status in both',
                    res        => 'resource only',
                    map        => 'enclosing map/folder',
                    rec        => 'recursive map/folder',
                    none       => 'not in use',
                    key        => 'key access',
                    ltic       => 'LTI access (course)',
                    ltid       => 'LTI access (domain)' ,
                    std        => 'Standard (all menus)',
                    colls      => 'Numbered collection',
                  );
    %selectnull = &Apache::lonlocal::texthash (
                    ltic => 'Select Launcher',
                    ltid => 'Select Launcher', 
                    colls => 'Select',
                  );
    if ($showval =~ /,/) {
        %values=();
        @current = split(/,/,$showval);
        ($values{'state'}) = ($current[0] =~ /^(only|off|both)$/);
        ($values{'others'}) = ($current[1] =~ /^(hide|unhide)$/);
        ($values{'listing'}) = ($current[2] =~ /^(full|absent|grades|details|datestatus)$/);
        ($values{'scope'}) = ($current[3] =~ /^(res|map|rec)$/);
        ($values{'protect'}) = ($current[4] =~ /^(key:[a-zA-Z\d_.!\@#\$%^&*()+=-]+|ltic:\d+|ltid:\d+)$/);
        ($values{'menus'}) = ($current[5] =~ /^(\d+)$/);
    } else {
        $defaults{'state'} = 'off',
        $defaults{'others'} = 'unhide',
        $defaults{'listing'} = 'full';
        $defaults{'scope'} = 'res';
        $defaults{'protect'} = 'none';
        $defaults{'menus'} = '0';
    }
    my $disabled;
    if ($readonly) {
        $disabled=' disabled="disabled"';
    }
    my %courselti =
        &Apache::lonnet::get_course_lti($env{'course.'.$env{'request.course.id'}.'.num'},
                                        $env{'course.'.$env{'request.course.id'}.'.domain'});
    foreach my $item (keys(%courselti)) {
        if (ref($courselti{$item}) eq 'HASH') {
            $crslti{$item} = $courselti{$item}{'name'};
        }
    }
    my %lti =
        &Apache::lonnet::get_domain_lti($env{'course.'.$env{'request.course.id'}.'.domain'},
                                        'provider');
    foreach my $item (keys(%lti)) {
        if (ref($lti{$item}) eq 'HASH') {
            unless ($lti{$item}{'requser'}) {
                $domlti{$item} = $lti{$item}{'consumer'};
            }
        }
    }
    if ($env{'course.'.$env{'request.course.id'}.'.menucollections'}) {
        foreach my $item (split(/;/,$env{'course.'.$env{'request.course.id'}.'.menucollections'})) {
            my ($num,$value) = split(/\%/,$item);
            if ($num =~ /^\d+$/) {
                push(@possmenus,$num);
            }
        }
    }

    my $output = '<input type="hidden" name="set_'.$thiskey.'" /><table><tr>';
    foreach my $item (@components) {
        $output .= '<th>'.$titles{$item}.'</th>';
    }
    $output .= '</tr><tr>';
    foreach my $item (@components) {
        $output .= '<td>';
        if (($item eq 'protect') || ($item eq 'menus')) {
            my $selected = $values{$item};
            foreach my $option (@{$options{$item}}) {
                if ($item eq 'protect') { 
                    if ($option eq 'ltid') {
                        next unless (keys(%domlti));
                    } elsif ($option eq 'ltic') {
                        next unless (keys(%crslti));
                    }
                } elsif (($item eq 'menus') && ($option eq 'colls')) {
                    next unless (@possmenus);
                }
                my $checked;
                if ($item eq 'menus') {
                    if (($selected =~ /^\d+$/) && (@possmenus) &&
                        (grep(/^\Q$selected\E$/,@possmenus))) {
                        if ($option eq 'colls') {
                            $checked = ' checked="checked"';
                        }
                    } elsif (($option eq 'std') && ($selected == 0) && ($selected ne '')) {
                        $checked = ' checked="checked"';
                    }
                } elsif ($selected =~ /^\Q$option\E/) {
                    $checked = ' checked="checked"';
                }
                my $onclick;
                unless ($readonly) {
                    my $esc_key = &js_escape($thiskey);
                    $onclick = ' onclick="toggleDeepLink(this.form,'."'$item','$esc_key'".');"';
                }
                $output .= '<span class="LC_nobreak"><label>'.
                           '<input type="radio" name="deeplink_'.$item.'_'.$thiskey.'" value="'.$option.'"'.$onclick.$disabled.$checked.' />'."\n".
                           $optiontext{$option}.'</label>';
                if (($item eq 'protect') && ($option eq 'key')) {
                    my $visibility="hidden";
                    my $currkey;
                    if ($checked) {
                        $visibility = "text";
                        $currkey = (split(/\:/,$values{$item}))[1];
                    }
                    $output .= '&nbsp;'.
                        '<input type="'.$visibility.'" name="deeplink_'.$option.'_'.$thiskey.'" id="deeplink_'.$option.'_'.$item.'_'.$thiskey.'" value="'.$currkey.'" size="10"'.$disabled.' />';
                } elsif (($option eq 'ltic') || ($option eq 'ltid') || ($option eq 'colls')) {
                    my $display="none";
                    my ($current,$blankcheck,@possibles);
                    if ($checked) {
                        $display = 'inline-block';
                        if (($option eq 'ltic') || ($option eq 'ltid'))  {
                            $current = (split(/\:/,$selected))[1];
                        } else {
                            $current = $selected;
                        }
                    } else {
                        $blankcheck = ' selected="selected"';
                    }
                    if ($option eq 'ltid') {
                        @possibles = keys(%domlti);
                    } elsif ($option eq 'ltic') {
                        @possibles = keys(%crslti); 
                    } else {
                        @possibles = @possmenus;
                    }
                    $output .= '<div id="deeplinkdiv_'.$option.'_'.$item.'_'.$thiskey.'"'.
                               ' style="display: '.$display.'">&nbsp;<select name="'.
                               'deeplink_'.$option.'_'.$thiskey.'"'.$disabled.'>';
                    if (@possibles > 1) {
                        $output .= '<option value=""'.$blankcheck.'>'.$selectnull{$option}.
                                   '</option>'."\n";
                    }
                    foreach my $poss (sort { $a <=> $b } @possibles) {
                        my $selected;
                        if (($poss == $current) || (scalar(@possibles) ==1)) {
                            $selected = ' selected="selected"';
                        }
                        my $shown = $poss;
                        if ($option eq 'ltid') {
                            $shown = $domlti{$poss};
                        } elsif ($option eq 'ltic') {
                            $shown = $crslti{$poss};
                        }
                        $output .= '<option value="'.$poss.'"'.$selected.'>'.$shown.'</option>';
                    }
                    $output .= '</select></div>';
                }
                $output .= '</span> ';
            }
        } else {
            my $selected = $values{$item};
            my $defsel;
            if ($selected eq '') {
                $defsel = ' selected="selected"';
            }
            $output .= '<select name="deeplink_'.$item.'_'.$thiskey.'"'.$disabled.'>'."\n".
                       '<option value=""'.$defsel.'>'.&mt('Please select').'</option>'."\n";
            foreach my $option (@{$options{$item}}) {
                $output .= '<option value="'.$option.'"';
                if ($option eq $selected) {
                    $output .= ' selected="selected"';
                }
                $output .= '>'.$optiontext{$option}.'</option>';
            }
            $output .= '</select>';
        }
        $output .= '</td>';
    }
    $output .= '</tr></table>'."\n";
    return $output;
}


{ # block using some constants related to parameter types (overview mode)

my %strings =
    (
     'string_yesno'
             => [[ 'yes', 'Yes' ],
                 [ 'no', 'No' ]],
     'string_problemstatus'
             => [[ 'yes', 'Yes' ],
         [ 'answer', 'Yes, and show correct answer if they exceed the maximum number of tries.' ],
         [ 'no', 'No, don\'t show correct/incorrect feedback.' ],
         [ 'no_feedback_ever', 'No, show no feedback at all.' ]],
     'string_questiontype'
             => [[ 'problem', 'Standard Problem'],
                 [ 'survey', 'Survey'],
                 [ 'anonsurveycred', 'Anonymous Survey (credit for submission)'],
                 [ 'exam', 'Bubblesheet Exam'],
                 [ 'anonsurvey', 'Anonymous Survey'],
                 [ 'randomizetry', 'New Randomization Each N Tries (default N=1)'],
                 [ 'practice', 'Practice'],
                 [ 'surveycred', 'Survey (credit for submission)']],
     'string_lenient'
             => [['yes', 'Yes' ],
                 [ 'no', 'No' ],
                 [ 'default', 'Default - only bubblesheet grading is lenient' ],
                 [ 'weighted', 'Yes, weighted (optionresponse in checkbox mode)' ]],
     'string_discussvote'
             => [['yes','Yes'],
                 ['notended','Yes, unless discussion ended'],
                 ['no','No']],
     'string_ip'
             => [['_allowfrom_','Hostname(s), or IP(s) from which access is allowed'],
                 ['_denyfrom_','Hostname(s) or IP(s) from which access is disallowed']], 
     'string_deeplink'
             => [['on','Set choices for link protection, resource listing, access scope, and shown menu items']],
    );
   

my %stringmatches = (
         'string_lenient'
              => [['weighted','^\-?[.\d]+,\-?[.\d]+,\-?[.\d]+,\-?[.\d]+$'],],
         'string_ip'
              => [['_allowfrom_','[^\!]+'],
                  ['_denyfrom_','\!']],
         'string_deeplink'
              => [['on','^(only|off|both)\,(hide|unhide)\,(full|absent|grades|details|datestatus)\,(res|map|rec)\,(none|key\:\w+|ltic\:\d+|ltid\:\d+)\,(\d+|)$']],
    );

my %stringtypes = (
                    type         => 'string_questiontype',
                    lenient      => 'string_lenient',
                    retrypartial => 'string_yesno',
                    discussvote  => 'string_discussvote',
                    examcode     => 'string_examcode',
                    acc          => 'string_ip',
                    deeplink     => 'string_deeplink',
                  );

# Returns the possible values and titles for a given string type, or undef if there are none.
# Used by courseprefs.
#
# @param {string} $string_type - a parameter type for strings
# @returns {array reference} - 2D array, containing values and English titles
sub standard_string_options {
    my ($string_type) = @_;
    if (ref($strings{$string_type}) eq 'ARRAY') {
        return $strings{$string_type};
    }
    return;
}

# Returns regular expressions to match kinds of string types, or undef if there are none.
#
# @param {string} $string_type - a parameter type for strings
# @returns {array reference}  - 2D array, containing regular expression names and regular expressions
sub standard_string_matches {
    my ($string_type) = @_;
    if (ref($stringmatches{$string_type}) eq 'ARRAY') {
        return $stringmatches{$string_type};
    }
    return;
}

# Returns a parameter type for a given parameter with a string type, or undef if not known.
#
# @param {string} $name - parameter name
# @returns {string}
sub get_stringtype {
    my ($name) = @_;
    if (exists($stringtypes{$name})) {
        return $stringtypes{$name};
    }
    return;
}

# Returns HTML to edit a string parameter.
#
# @param {string} $thistype - parameter type
# @param {string} $thiskey - parameter key
# @param {string} $showval - parameter current value
# @param {string} $name - parameter name
# @param {boolean} $readonly - true if the values should not be made editable
# @returns {string}
sub string_selector {
    my ($thistype, $thiskey, $showval, $name, $readonly) = @_;

    if (!exists($strings{$thistype})) {
        return &default_selector($thiskey,$showval,$readonly);
    }

    my %skiptype;
    if (($thistype eq 'string_questiontype') || 
            ($thistype eq 'string_lenient') ||
            ($thistype eq 'string_discussvote') ||
            ($thistype eq 'string_ip') ||
            ($thistype eq 'string_deeplink') ||
            ($name eq 'retrypartial')) {
        my ($got_chostname,$chostname,$cmajor,$cminor); 
        foreach my $possibilities (@{ $strings{$thistype} }) {
            next unless (ref($possibilities) eq 'ARRAY');
            my ($parmval, $description) = @{ $possibilities };
            my $parmmatch;
            if (ref($stringmatches{$thistype}) eq 'ARRAY') {
                foreach my $item (@{$stringmatches{$thistype}}) {
                    if (ref($item) eq 'ARRAY') {
                        if ($parmval eq $item->[0]) {
                            $parmmatch = $parmval;
                            $parmval = '';
                            last;
                        }
                    }
                }
            }
            my $needsrelease=$Apache::lonnet::needsrelease{"parameter:$name:$parmval:$parmmatch"}; 
            if ($needsrelease) {
                unless ($got_chostname) {
                    ($chostname,$cmajor,$cminor)=&parameter_release_vars();
                    $got_chostname = 1;
                }
                my $needsnewer=&parameter_releasecheck($name,$parmval,$parmmatch,undef,
                                                       $needsrelease,$cmajor,$cminor);
                if ($needsnewer) {
                    if ($parmmatch ne '') {
                        $skiptype{$parmmatch} = 1;
                    } elsif ($parmval ne '') {
                        $skiptype{$parmval} = 1;
                    }
                }
            }
        }
    }

    if ($thistype eq 'string_ip') {
        return &string_ip_selector($thiskey,$showval,$readonly); 
    } elsif ($thistype eq 'string_deeplink') {
        return &string_deeplink_selector($thiskey,$showval,$readonly);
    }

    my ($result,$disabled);

    if ($readonly) {
        $disabled = ' disabled="disabled"';
    }
    my $numinrow = 3;
    if ($thistype eq 'string_problemstatus') {
        $numinrow = 2;
    } elsif ($thistype eq 'string_questiontype') {
        if (keys(%skiptype) > 0) {
             $numinrow = 4;
        }
    }
    my $rem;
    if (ref($strings{$thistype}) eq 'ARRAY') {
        my $i=0;
        foreach my $possibilities (@{ $strings{$thistype} }) {
            next unless (ref($possibilities) eq 'ARRAY');
            my ($name, $description) = @{ $possibilities };
            next if ($skiptype{$name});
            $rem = $i%($numinrow);
            if ($rem == 0) {
                if ($i > 0) {
                    $result .= '</tr>';
                }
                $result .= '<tr>';
            }
            my $colspan;
            if ($i == @{ $strings{$thistype} }-1) {
                $rem = @{ $strings{$thistype} }%($numinrow);
                if ($rem) {
                    my $colsleft = $numinrow - $rem;
                    if ($colsleft) {
                        $colspan = $colsleft+1;
                        $colspan = ' colspan="'.$colspan.'"';
                    }
                }
            }
            my ($add,$onchange,$css_class);
            if ($thistype eq 'string_lenient') {
                if ($name eq 'weighted') {
                    my $display;
                    my %relatives = &Apache::lonlocal::texthash(
                                        corrchkd     => 'Correct (checked)',
                                        corrunchkd   => 'Correct (unchecked)',
                                        incorrchkd   => 'Incorrect (checked)',
                                        incorrunchkd => 'Incorrect (unchecked)',
                    );
                    my %textval = (
                                    corrchkd     => '1.0',
                                    corrunchkd   => '1.0',
                                    incorrchkd   => '0.0',
                                    incorrunchkd => '0.0',
                    );
                    if ($showval =~ /^([\-\d\.]+)\,([\-\d\.]+)\,([\-\d\.]+)\,([\-\d\.]+)$/) {
                        $textval{'corrchkd'} = $1;
                        $textval{'corrunchkd'} = $2;
                        $textval{'incorrchkd'} = $3;
                        $textval{'incorrunchkd'} = $4;
                        $display = 'inline';
                        $showval = $name;
                    } else {
                        $display = 'none';
                    }
                    $add = ' <div id="LC_parmtext_'.$thiskey.'" style="display:'.$display.'"><table>'.
                           '<tr><th colspan="2">'.&mt("Foil's submission status").'</th><th>'.&mt('Points').'</th></tr>';  
                    foreach my $reltype ('corrchkd','corrunchkd','incorrchkd','incorrunchkd') {
                        $add .= '<tr><td>&nbsp;</td><td>'.$relatives{$reltype}.'</td>'."\n".
                                '<td><input type="text" name="settext_'.$thiskey.'"'.
                                ' value="'.$textval{$reltype}.'" size="3"'.$disabled.' />'.
                                '</td></tr>';
                    }
                    $add .= '</table></div>'."\n";
                }
                $onchange = ' onclick="javascript:toggleParmTextbox(this.form,'."'$thiskey'".');"';
                $css_class = ' class="LC_lenient_radio"';
            }
            $result .= '<td class="LC_left_item"'.$colspan.'>'.
                       '<span class="LC_nobreak"><label>'.
                       '<input type="radio" name="set_'.$thiskey.
                       '" value="'.$name.'"'.$onchange.$css_class.$disabled;
            if ($showval eq $name) {
                $result .= ' checked="checked"';
            }
            $result .= ' />'.&mt($description).'</label>'.$add.'</span></td>';
            $i++;
        }
        $result .= '</tr>';
    }
    if ($result) {
        $result = '<table border="0">'.$result.'</table>';
    }
    return $result;
}

my %intervals =
    (
     'date_interval'
             => [[ 'done', 'Yes' ],
                 [ 'done_proctor', 'Yes, with proctor key'],                  
                 [ '', 'No' ]],
    );

my %intervalmatches = (
         'date_interval'
              => [['done','\d+_done(|\:[^\:]+\:)$'],
                  ['done_proctor','\d+_done(|\:[^\:]+\:)_proctor_']],
    );

my %intervaltypes = (
                      interval => 'date_interval',
    );

# Returns regular expressions to match kinds of interval type, or undef if there are none.
#
# @param {string} $interval_type - a parameter type for intervals
# @returns {array reference}  - 2D array, containing regular expression names and regular expressions
sub standard_interval_matches {
    my ($interval_type) = @_;
    if (ref($intervalmatches{$interval_type}) eq 'ARRAY') {
        return $intervalmatches{$interval_type};
    }
    return;
}

# Returns a parameter type for a given parameter with an interval type, or undef if not known.
#
# @param {string} $name - parameter name
# @returns {string}
sub get_intervaltype {
    my ($name) = @_;
    if (exists($intervaltypes{$name})) {
        return $intervaltypes{$name};
    }
    return;
}

# Returns the possible values and titles for a given interval type, or undef if there are none.
# Used by courseprefs.
#
# @param {string} $interval_type - a parameter type for intervals
# @returns {array reference} - 2D array, containing values and English titles
sub standard_interval_options {
    my ($interval_type) = @_;
    if (ref($intervals{$interval_type}) eq 'ARRAY') {
        return $intervals{$interval_type};
    }
    return;
}

# Returns HTML to edit a date interval parameter.
#
# @param {string} $thiskey - parameter key
# @param {string} $name - parameter name
# @param {string} $showval - parameter current value
# @param {boolean} $readonly - true if the values should not be made editable
# @returns {string}
sub date_interval_selector {
    my ($thiskey, $name, $showval, $readonly) = @_;
    my ($result,%skipval);
    if ($name eq 'interval') {
        my $intervaltype = &get_intervaltype($name);
        my ($got_chostname,$chostname,$cmajor,$cminor);
        foreach my $possibilities (@{ $intervals{$intervaltype} }) {
            next unless (ref($possibilities) eq 'ARRAY');
            my ($parmval, $description) = @{ $possibilities };
            my $parmmatch;
            if (ref($intervalmatches{$intervaltype}) eq 'ARRAY') {
                foreach my $item (@{$intervalmatches{$intervaltype}}) {
                    if (ref($item) eq 'ARRAY') {
                        if ($parmval eq $item->[0]) {
                            $parmmatch = $parmval;
                            $parmval = '';
                            last;
                        }
                    }
                }
            }
            my $needsrelease=$Apache::lonnet::needsrelease{"parameter:$name:$parmval:$parmmatch"};
            if ($needsrelease) {
                unless ($got_chostname) {
                    ($chostname,$cmajor,$cminor)=&parameter_release_vars();
                    $got_chostname = 1;
                }
                my $needsnewer=&parameter_releasecheck($name,$parmval,$parmmatch,undef,
                                                       $needsrelease,$cmajor,$cminor);
                if ($needsnewer) {
                    if ($parmmatch ne '') {
                        $skipval{$parmmatch} = 1;
                    } elsif ($parmval ne '') {
                        $skipval{$parmval} = 1;
                    }
                }
            }
        }
    }

    my $currval = $showval;
    foreach my $which (['days', 86400, 31],
               ['hours', 3600, 23],
               ['minutes', 60, 59],
               ['seconds',  1, 59]) {
        my ($name, $factor, $max) = @{ $which };
        my $amount = int($showval/$factor);
        $showval  %= $factor;
        my %select = ((map {$_ => $_} (0..$max)),
                'select_form_order' => [0..$max]);
        $result .= &Apache::loncommon::select_form($amount,$name.'_'.$thiskey,
                            \%select,'',$readonly);
        $result .= ' '.&mt($name);
    }
    if ($name eq 'interval') {
        unless ($skipval{'done'}) {
            my $checkedon = '';
            my $checkedproc = '';
            my $currproctorkey = '';
            my $currprocdisplay = 'hidden';
            my $currdonetext = &mt('Done');
            my $checkedoff = ' checked="checked"';
            if ($currval =~ /^(?:\d+)_done$/) {
                $checkedon = ' checked="checked"';
                $checkedoff = '';
            } elsif ($currval =~ /^(?:\d+)_done\:([^\:]+)\:$/) {
                $currdonetext = $1;
                $checkedon = ' checked="checked"';
                $checkedoff = '';
            } elsif ($currval =~ /^(?:\d+)_done_proctor_(.+)$/) {
                $currproctorkey = $1;
                $checkedproc = ' checked="checked"';
                $checkedoff = '';
                $currprocdisplay = 'text';
            } elsif ($currval =~ /^(?:\d+)_done\:([^\:]+)\:_proctor_(.+)$/) {
                $currdonetext = $1;
                $currproctorkey = $2;
                $checkedproc = ' checked="checked"';
                $checkedoff = '';
                $currprocdisplay = 'text';
            }
            my $onclick = ' onclick="toggleSecret(this.form,'."'done_','$thiskey'".');"';
            my $disabled;
            if ($readonly) {
                $disabled = ' disabled="disabled"';
            }
            $result .= '<br /><span class="LC_nobreak">'.&mt('Include "done" button').
                       '<label><input type="radio" value="" name="done_'.$thiskey.'"'.$checkedoff.$onclick.$disabled.' />'.
                       &mt('No').'</label>'.('&nbsp;'x2).
                       '<label><input type="radio" value="_done" name="done_'.$thiskey.'"'.$checkedon.$onclick.$disabled.' />'.
                       &mt('Yes').'</label>'.('&nbsp;'x2).
                       '<label><input type="radio" value="_done_proctor" name="done_'.$thiskey.'"'.$checkedproc.$onclick.$disabled.' />'.
                       &mt('Yes, with proctor key').'</label>'.
                       '<input type="'.$currprocdisplay.'" id="done_'.$thiskey.'_proctorkey" '.
                       'name="done_'.$thiskey.'_proctorkey" value="'.&HTML::Entities::encode($currproctorkey,'"<>&').'"'.$disabled.' /></span><br />'.
                       '<span class="LC_nobreak">'.&mt('Button text').': '.
                       '<input type="text" name="done_'.$thiskey.'_buttontext" value="'.&HTML::Entities::encode($currdonetext,'"<>&').'"'.$disabled.' /></span>';
        }
    }
    unless ($readonly) {
        $result .= '<input type="hidden" name="dateinterval_'.$thiskey.'" />';
    }
    return $result;
}

# Returns HTML with a warning if a parameter requires a more recent version of LON-CAPA.
#
# @param {string} $name - parameter name
# @param {string} $namematch - parameter level name (recognized: resourcelevel|maplevel|maplevelrecurse|courselevel)
# @param {string} $value - parameter value
# @param {string} $chostname - course server name
# @param {integer} $cmajor - major version number
# @param {integer} $cminor - minor version number
# @param {string} $needsrelease - release version needed (major.minor)
# @returns {string}
sub oldversion_warning {
    my ($name,$namematch,$value,$chostname,$cmajor,$cminor,$needsrelease) = @_;
    my $standard_name = &standard_parameter_names($name);
    if ($namematch) {
        my $level = &standard_parameter_levels($namematch);
        my $msg = '';
        if ($level) {
            $msg = &mt('[_1] was [_2]not[_3] set at the level of: [_4].',
                       $standard_name,'<b>','</b>','"'.$level.'"');
        } else {
            $msg = &mt('[_1] was [_2]not[_3] set.',
                      $standard_name,'<b>','</b>');
        }
        return '<p class="LC_warning">'.$msg.'<br />'.
               &mt('LON-CAPA version ([_1]) installed on home server ([_2]) does not meet version requirements ([_3] or newer).',
                   $cmajor.'.'.$cminor,$chostname,
                   $needsrelease).
                   '</p>';
    }
    my $desc;
    my $stringtype = &get_stringtype($name);
    if ($stringtype ne '') {
        if ($name eq 'examcode') {
            $desc = $value;
        } elsif (ref($strings{$stringtypes{$name}}) eq 'ARRAY') {
            foreach my $possibilities (@{ $strings{$stringtypes{$name}} }) {
                next unless (ref($possibilities) eq 'ARRAY');
                my ($parmval, $description) = @{ $possibilities };
                my $parmmatch;
                if (ref($stringmatches{$stringtypes{$name}}) eq 'ARRAY') {
                    foreach my $item (@{$stringmatches{$stringtypes{$name}}}) {
                        if (ref($item) eq 'ARRAY') {
                            my ($regexpname,$pattern) = @{$item};
                            if ($parmval eq $regexpname) {
                                if ($value =~ /$pattern/) {
                                    $desc = $description; 
                                    $parmmatch = 1;
                                    last;
                                }
                            }
                        }
                    }
                    last if ($parmmatch);
                } elsif ($parmval eq $value) {
                    $desc = $description;
                    last;
                }
            }
        }
    } elsif (($name eq 'printstartdate') || ($name eq 'printenddate')) {
        my $now = time;
        if ($value =~ /^\d+$/) {
            if ($name eq 'printstartdate') {
                if ($value > $now) {
                    $desc = &Apache::lonlocal::locallocaltime($value);
                }
            } elsif ($name eq 'printenddate') {
                if ($value < $now) {
                    $desc = &Apache::lonlocal::locallocaltime($value);
                }
            }
        }
    }
    return '<p class="LC_warning">'.
       &mt('[_1] was [_2]not[_3] set to [_4].',
           $standard_name,'<b>','</b>','"'.$desc.'"').'<br />'.
       &mt('LON-CAPA version ([_1]) installed on home server ([_2]) does not meet version requirements ([_3] or newer).',
       $cmajor.'.'.$cminor,$chostname,
       $needsrelease).
       '</p>';
}

} # end of block using some constants related to parameter types



# Shifts all start and end dates in the current course by $shift.
#
# @param {integer} $shift - time to shift, in seconds
# @returns {string} - error name or 'ok'
sub dateshift {
    my ($shift,$numchanges)=@_;
    my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $sec = $env{'request.course.sec'};
    my $secgrpregex;
    if ($sec ne '') {
        my @groups;
        if ($env{'request.course.groups'} ne '') {
            @groups = split(/:/,$env{'request.course.groups'});
        }
        if (@groups) {
            $secgrpregex = '(?:'.join('|',($sec,@groups)).')';
        } else {
            $secgrpregex = $sec;
        }
    }
    my %data=&Apache::lonnet::dump('resourcedata',$dom,$crs);
# ugly retro fix for broken version of types
    foreach my $key (keys(%data)) {
        if ($key=~/\wtype$/) {
            my $newkey=$key;
            $newkey=~s/type$/\.type/;
            $data{$newkey}=$data{$key};
            delete $data{$key};
        }
    }
    my %storecontent=();
# go through all parameters and look for dates
    foreach my $key (keys(%data)) {
       if ($data{$key.'.type'}=~/^date_(start|end)$/) {
          if ($sec ne '') {
              next unless ($key =~ /^$env{'request.course.id'}\.\[$secgrpregex\]\./);
          }
          my $newdate=$data{$key}+$shift;
          $$numchanges ++;
          $storecontent{$key}=$newdate;
       }
    }
    my $reply=&Apache::lonnet::cput
                ('resourcedata',\%storecontent,$dom,$crs);
    if ($reply eq 'ok') {
       &log_parmset(\%storecontent);
    }
    &Apache::lonnet::devalidatecourseresdata($crs,$dom);
    return $reply;
}

# Overview mode UI to edit course parameters.
#
# @param {Apache2::RequestRec} $r - the Apache request
sub newoverview {
    my ($r,$parm_permission) = @_;

    my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $crstype =  $env{'course.'.$env{'request.course.id'}.'.type'};
    my $readonly = 1;
    if ($parm_permission->{'edit'}) {
        undef($readonly);
    }
    &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/parmset?action=setoverview',
        text=>"Overview Mode"});

    my %loaditems = (
                      'onload'   => "showHide_courseContent(); resize_scrollbox('mapmenuscroll','1','1'); showHideLenient();",
                    );
    my $js = '
<script type="text/javascript">
// <![CDATA[
'.
            &Apache::lonhtmlcommon::resize_scrollbox_js('params')."\n".
            &showhide_js()."\n".
            &toggleparmtextbox_js()."\n".
            &validateparms_js()."\n".
            &ipacc_boxes_js()."\n".
            &done_proctor_js()."\n".
            &deeplink_js()."\n".
'// ]]>
</script>
';

    my $start_page = &Apache::loncommon::start_page('Set Parameters',$js,
                                                    {'add_entries' => \%loaditems,});
    my $breadcrumbs = &Apache::lonhtmlcommon::breadcrumbs('Overview');
    $r->print($start_page.$breadcrumbs);
    &startSettingsScreen($r,'parmset',$crstype);
    $r->print(<<ENDOVER);
<form method="post" action="/adm/parmset?action=newoverview" name="parmform" onsubmit="return validateParms();">
ENDOVER
    my @ids=();
    my %typep=();
    my %keyp=();
    my %allparms=();
    my %allparts=();
    my %allmaps=();
    my %mapp=();
    my %symbp=();
    my %maptitles=();
    my %uris=();
    my %keyorder=&standardkeyorder();
    my %defkeytype=();

    my %alllevs=();
    $alllevs{'Resource Level'}='full';
    $alllevs{'Map/Folder Level'}='map';
    $alllevs{'Course Level'}='general';

    my $csec=$env{'form.csec'};
    my $cgroup=$env{'form.cgroup'};

    my @pscat=&Apache::loncommon::get_env_multiple('form.pscat');
    my $pschp=$env{'form.pschp'};

    my @psprt=&Apache::loncommon::get_env_multiple('form.psprt');
    if (!@psprt) { $psprt[0]='all'; }

    my @selected_sections =
    &Apache::loncommon::get_env_multiple('form.Section');
    @selected_sections = ('all') if (! @selected_sections);
    foreach my $sec (@selected_sections) {
        if ($sec eq 'all') {
            @selected_sections = ('all');
        }
    }
    if ($env{'request.course.sec'} ne '') {
        @selected_sections = ($env{'request.course.sec'});
    }
    my @selected_groups =
        &Apache::loncommon::get_env_multiple('form.Group');

    my $pssymb='';
    my $parmlev='';

    unless ($env{'form.parmlev'}) {
        $parmlev = 'map';
    } else {
        $parmlev = $env{'form.parmlev'};
    }

    &extractResourceInformation(\@ids, \%typep,\%keyp, \%allparms, \%allparts, \%allmaps,
                \%mapp, \%symbp,\%maptitles,\%uris,
                \%keyorder,\%defkeytype,$pssymb);

    if (grep {$_ eq 'all'} (@psprt)) {
        @psprt = keys(%allparts);
    }
# Menu to select levels, etc

    $r->print('<div class="LC_Box">');
    #$r->print('<h2 class="LC_hcell">Step 1</h2>');
    $r->print('<div>');
    $r->print(&Apache::lonhtmlcommon::start_pick_box(undef,'parmlevel'));
    &levelmenu($r,\%alllevs,$parmlev);
    if ($parmlev ne 'general') {
        $r->print(&Apache::lonhtmlcommon::row_closure());
        &mapmenu($r,\%allmaps,$pschp,\%maptitles,\%symbp);
    }
    $r->print(&Apache::lonhtmlcommon::row_closure(1));
    $r->print(&Apache::lonhtmlcommon::end_pick_box());
    $r->print('</div></div>');

    $r->print('<div class="LC_Box">');
    $r->print('<div>');
    &displaymenu($r,\%allparms,\@pscat,\%keyorder);
    $r->print(&Apache::lonhtmlcommon::start_pick_box());
    $r->print(&Apache::lonhtmlcommon::row_title(&mt('Select Parts to View')));
    my $sectionselector = &sectionmenu(\@selected_sections);
    my $groupselector = &groupmenu(\@selected_groups);
    $r->print('<table>'.
              '<tr><th>'.&mt('Parts').'</th>');
    if ($sectionselector) {
        $r->print('<th>'.&mt('Section(s)').'</th>');
    }
    if ($groupselector) {
        $r->print('<th>'.&mt('Group(s)').'</th>');
    }
    $r->print('</tr><tr><td>');
    &partmenu($r,\%allparts,\@psprt);
    $r->print('</td>');
    if ($sectionselector) { 
        $r->print('<td>'.$sectionselector.'</td>');
    }
    if ($groupselector) {
        $r->print('<td>'.$groupselector.'</td>');
    }
    $r->print('</tr></table>');
    $r->print(&Apache::lonhtmlcommon::row_closure(1));
    $r->print(&Apache::lonhtmlcommon::end_pick_box());
    $r->print('</div></div>');

    $r->print('<div class="LC_Box">');
    $r->print('<div>');
    my $sortorder=$env{'form.sortorder'};
    unless ($sortorder) { $sortorder='realmstudent'; }
    &sortmenu($r,$sortorder);
    $r->print('</div></div>');

    $r->print('<p><input type="submit" name="dis" value="'.&mt('Display').'" /></p>');

# Build the list data hash from the specified parms

    my $listdata;
    %{$listdata}=();

    foreach my $cat (@pscat) {
        &secgroup_lister($cat,$pschp,$parmlev,$listdata,\@psprt,\@selected_sections,\%defkeytype,\%allmaps,\@ids,\%symbp);
        &secgroup_lister($cat,$pschp,$parmlev,$listdata,\@psprt,\@selected_groups,\%defkeytype,\%allmaps,\@ids,\%symbp);
    }

    if (($env{'form.store'}) || ($env{'form.dis'})) {

        if ($env{'form.store'}) { &storedata($r,$crs,$dom); }

# Read modified data

        my $resourcedata=&readdata($crs,$dom);

# List data

        &listdata($r,$resourcedata,$listdata,$sortorder,'newoverview',undef,$readonly);
    }
    $r->print(&tableend());
    unless ($readonly) {
        $r->print( ((($env{'form.store'}) || ($env{'form.dis'}))?'<p><input type="submit" name="store" value="'.&mt('Save').'" /></p>':'') );
    }
    $r->print('</form>');
    &endSettingsScreen($r);
    $r->print(&Apache::loncommon::end_page());
}

# Fills $listdata with parameter information.
# Keys use the format course id.[section id].part.name and course id.[section id].part.name.type.
# The non-type value is always 1.
#
# @param {string} $cat - parameter name
# @param {string} $pschp - selected map pc, or 'all'
# @param {string} $parmlev - selected level value (full|map|general), or ''
# @param {hash reference} $listdata - the parameter data that will be modified
# @param {array reference} $psprt - selected parts
# @param {array reference} $selections - selected sections
# @param {hash reference} $defkeytype - hash parameter name -> parameter type
# @param {hash reference} $allmaps - hash map pc -> map src
# @param {array reference} $ids - resource and map ids
# @param {hash reference} $symbp - hash map pc or resource/map id -> map src.'___(all)' or resource symb
sub secgroup_lister {
    my ($cat,$pschp,$parmlev,$listdata,$psprt,$selections,$defkeytype,$allmaps,$ids,$symbp) = @_;
    foreach my $item (@{$selections}) {
        foreach my $part (@{$psprt}) {
            my $rootparmkey=$env{'request.course.id'};
            if (($item ne 'all') && ($item ne 'none') && ($item)) {
                $rootparmkey.='.['.$item.']';
            }
            if ($parmlev eq 'general') {
# course-level parameter
                my $newparmkey=$rootparmkey.'.'.$part.'.'.$cat;
                $$listdata{$newparmkey}=1;
                $$listdata{$newparmkey.'.type'}=$$defkeytype{$cat};
            } elsif ($parmlev eq 'map') {
# map-level parameter
                foreach my $mapid (keys(%{$allmaps})) {
                    if (($pschp ne 'all') && ($pschp ne $mapid)) { next; }
                    my $newparmkey=$rootparmkey.'.'.$$allmaps{$mapid}.'___(all).'.$part.'.'.$cat;
                    $$listdata{$newparmkey}=1;
                    $$listdata{$newparmkey.'.type'}=$$defkeytype{$cat};
                }
            } else {
# resource-level parameter
                foreach my $rid (@{$ids}) {
                    my ($map,$resid,$url)=&Apache::lonnet::decode_symb($$symbp{$rid});
                    if (($pschp ne 'all') && ($$allmaps{$pschp} ne $map)) { next; }
                    my $newparmkey=$rootparmkey.'.'.$$symbp{$rid}.'.'.$part.'.'.$cat;
                    $$listdata{$newparmkey}=1;
                    $$listdata{$newparmkey.'.type'}=$$defkeytype{$cat};
                }
            }
        }
    }
}

# UI to edit parameter settings starting with a list of all existing parameters.
# (called by setoverview action)
#
# @param {Apache2::RequestRec} $r - the Apache request
sub overview {
    my ($r,$parm_permission) = @_;
    my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
    my $readonly = 1;
    if ($parm_permission->{'edit'}) {
        undef($readonly);
    }
    my $js = '<script type="text/javascript">'."\n".
             '// <![CDATA['."\n".
             &toggleparmtextbox_js()."\n".
             &validateparms_js()."\n".
             &ipacc_boxes_js()."\n".
             &done_proctor_js()."\n".
             &deeplink_js()."\n".
             '// ]]>'."\n".
             '</script>'."\n";
    &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/parmset?action=setoverview',
    text=>"Overview Mode"});
    my %loaditems = (
                      'onload'   => "showHideLenient();",
                    );

    my $start_page=&Apache::loncommon::start_page('Modify Parameters',$js,{'add_entries' => \%loaditems,});
    my $breadcrumbs = &Apache::lonhtmlcommon::breadcrumbs('Overview');
    $r->print($start_page.$breadcrumbs);
    &startSettingsScreen($r,'parmset',$crstype);
    $r->print('<form method="post" action="/adm/parmset?action=setoverview" name="parmform" onsubmit="return validateParms();">');

# Store modified

    unless ($readonly) {
        &storedata($r,$crs,$dom);
    }

# Read modified data

    my ($resourcedata,$classlist)=&readdata($crs,$dom);


    my $sortorder=$env{'form.sortorder'};
    unless ($sortorder) { $sortorder='realmstudent'; }
    &sortmenu($r,$sortorder);

    my $submitbutton = '<input type="submit" value="'.&mt('Save').'" />';

    if ($readonly) {
        $r->print('<p>'.$submitbutton.'</p>');
    }

# List data

    my $foundkeys=&listdata($r,$resourcedata,$resourcedata,$sortorder,'overview',$classlist,$readonly);
    $r->print(&tableend().'<p>');
    if ($foundkeys) {
        unless ($readonly) {
            $r->print('<p>'.$submitbutton.'</p>');
        }
    } else {
        $r->print('<p class="LC_info">'.&mt('There are no parameters.').'</p>');
    }
    $r->print('</form>'.&Apache::loncommon::end_page());
}

# Unused sub.
#
# @param {Apache2::RequestRec} $r - the Apache request
sub clean_parameters {
    my ($r) = @_;
    my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};

    &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/parmset?action=cleanparameters',
        text=>"Clean Parameters"});
    my $start_page=&Apache::loncommon::start_page('Clean Parameters');
    my $breadcrumbs = &Apache::lonhtmlcommon::breadcrumbs('Clean');
    $r->print(<<ENDOVER);
$start_page
$breadcrumbs
<form method="post" action="/adm/parmset?action=cleanparameters" name="parmform">
ENDOVER
# Store modified

    &storedata($r,$crs,$dom);

# Read modified data

    my $resourcedata=&readdata($crs,$dom);

# List data

    $r->print('<h3>'.
          &mt('These parameters refer to resources that do not exist.').
          '</h3>'.
          '<input type="submit" value="'.&mt('Delete Selected').'" />'.'<br />'.
          '<br />');
    $r->print(&Apache::loncommon::start_data_table().
          '<tr>'.
          '<th>'.&mt('Delete').'</th>'.
          '<th>'.&mt('Parameter').'</th>'.
          '</tr>');
    foreach my $thiskey (sort(keys(%{$resourcedata}))) {
        next if (!exists($resourcedata->{$thiskey.'.type'})
            && $thiskey=~/\.type$/);
        my %data = &parse_key($thiskey);
        if (1) { #exists($data{'realm_exists'})
            #&& !$data{'realm_exists'}) {
            $r->print(&Apache::loncommon::start_data_table_row().
                '<tr>'.
                '<td><input type="checkbox" name="del_'.$thiskey.'" /></td>'              );

            $r->print('<td>');
            my $display_value = $resourcedata->{$thiskey};
            if (&isdateparm($resourcedata->{$thiskey.'.type'})) {
            $display_value =
                &Apache::lonlocal::locallocaltime($display_value);
            }
            my $parmitem = &standard_parameter_names($data{'parameter_name'});
            $parmitem = &mt($parmitem);
            $r->print(&mt('Parameter: "[_1]" with value: "[_2]"',
                $parmitem,$resourcedata->{$thiskey}));
            $r->print('<br />');
            if ($data{'scope_type'} eq 'all') {
                $r->print(&mt('All users'));
            } elsif ($data{'scope_type'} eq 'user') {
                $r->print(&mt('User: [_1]',join(':',@{$data{'scope'}})));
            } elsif ($data{'scope_type'} eq 'secgroup') {
                $r->print(&mt('Group/Section: [_1]',$data{'scope'}));
            }
            $r->print('<br />');
            if ($data{'realm_type'} eq 'all') {
                $r->print(&mt('All Resources'));
            } elsif ($data{'realm_type'} eq 'folder') {
                $r->print(&mt('Folder: [_1]'),$data{'realm'});
            } elsif ($data{'realm_type'} eq 'symb') {
            my ($map,$resid,$url) =
                &Apache::lonnet::decode_symb($data{'realm'});
            $r->print(&mt('Resource: [_1]with ID: [_2]in folder [_3]',
                        $url.' <br />&nbsp;&nbsp;&nbsp;',
                        $resid.' <br />&nbsp;&nbsp;&nbsp;',$map));
            }
            $r->print(' <br />&nbsp;&nbsp;&nbsp;'.&mt('Part: [_1]',$data{'parameter_part'}));
            $r->print('</td></tr>');

        }
    }
    $r->print(&Apache::loncommon::end_data_table().'<p>'.
          '<input type="submit" value="'.&mt('Delete Selected').'" />'.
          '</p></form>');
    &endSettingsScreen($r);
    $r->print(&Apache::loncommon::end_page());
}

# UI to shift all dates (called by dateshift1 action).
# Used by overview mode.
#
# @param {Apache2::RequestRec} $r - the Apache request
sub date_shift_one {
    my ($r) = @_;
    my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
    my $sec = $env{'request.course.sec'};
    &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/parmset?action=dateshift1&timebase='.$env{'form.timebase'},
        text=>"Shifting Dates"});
    my $submit_text = &mt('Shift all dates accordingly');
    if ($sec ne '') {
        my @groups;
        if ($env{'request.course.groups'} ne '') {
            @groups = split(/:/,$env{'request.course.groups'});
        }
        if (@groups) {
            $submit_text = &mt("Shift dates set just for your section/group(s), accordingly");
        } else {
            $submit_text = &mt("Shift dates set just for your section, accordingly");
        }
    }
    my $start_page=&Apache::loncommon::start_page('Shift Dates');
    my $breadcrumbs = &Apache::lonhtmlcommon::breadcrumbs('Shift');
    $r->print($start_page.$breadcrumbs);
    &startSettingsScreen($r,'parmset',$crstype);
    $r->print('<form name="shiftform" method="post" action="">'.
              '<table><tr><td>'.&mt('Currently set date:').'</td><td>'.
              &Apache::lonlocal::locallocaltime($env{'form.timebase'}).'</td></tr>'.
              '<tr><td>'.&mt('Shifted date:').'</td><td>'.
                    &Apache::lonhtmlcommon::date_setter('shiftform',
                                                        'timeshifted',
                                                        $env{'form.timebase'},,
                                                        '').
              '</td></tr></table>'.
              '<input type="hidden" name="action" value="dateshift2" />'.
              '<input type="hidden" name="timebase" value="'.$env{'form.timebase'}.'" />'.
              '<input type="submit" value="'.$submit_text.'" /></form>');
    &endSettingsScreen($r);
    $r->print(&Apache::loncommon::end_page());
}

# UI to shift all dates (second form).
#
# @param {Apache2::RequestRec} $r - the Apache request
sub date_shift_two {
    my ($r) = @_;
    my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $sec = $env{'request.course.sec'};
    my $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
    &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/parmset?action=dateshift1&timebase='.$env{'form.timebase'},
        text=>"Shifting Dates"});
    my $start_page=&Apache::loncommon::start_page('Shift Dates');
    my $breadcrumbs = &Apache::lonhtmlcommon::breadcrumbs('Shift');
    $r->print($start_page.$breadcrumbs);
    &startSettingsScreen($r,'parmset',$crstype);
    my $timeshifted=&Apache::lonhtmlcommon::get_date_from_form('timeshifted');
    $r->print('<h2>'.&mt('Shift Dates').'</h2>');
    if ($sec ne '') {
        my @groups;
        if ($env{'request.course.groups'} ne '') {
            @groups = split(/:/,$env{'request.course.groups'});
        }
        if (@groups) {
            $r->print('<p>'.
                      &mt("Shift dates set just for your section/group(s), such that [_1] becomes [_2]",
                          &Apache::lonlocal::locallocaltime($env{'form.timebase'}),
                          &Apache::lonlocal::locallocaltime($timeshifted)).
                      '</p>');
        } else {
            $r->print('<p>'.
                      &mt("Shift dates set just for your section, such that [_1] becomes [_2]",
                          &Apache::lonlocal::locallocaltime($env{'form.timebase'}),
                          &Apache::lonlocal::locallocaltime($timeshifted)).
                      '</p>');
        }
    } else {
        $r->print('<p>'.&mt('Shifting all dates such that [_1] becomes [_2]',
                            &Apache::lonlocal::locallocaltime($env{'form.timebase'}),
                            &Apache::lonlocal::locallocaltime($timeshifted)).
                  '</p>');
    }
    my $delta=$timeshifted-$env{'form.timebase'};
    my $numchanges = 0;
    my $result = &dateshift($delta,\$numchanges);
    if ($result eq 'ok') {
        $r->print(
            &Apache::lonhtmlcommon::confirm_success(&mt('Completed shifting of [quant,_1,date setting]',
                                                    $numchanges)));
    } elsif ($result eq 'con_delayed') {
        $r->print(
            &Apache::lonhtmlcommon::confirm_success(&mt('Queued shifting of [quant,_1,date setting]',
                                                        $numchanges)));
    } else {
        $r->print(
            &Apache::lonhtmlcommon::confirm_success(&mt('An error occurred attempting to shift dates'),1));
    }
    $r->print(
        '<br /><br />'.
        &Apache::lonhtmlcommon::actionbox(
            ['<a href="/adm/parmset">'.&mt('Content and Problem Settings').'</a>']));
    &endSettingsScreen($r);
    $r->print(&Apache::loncommon::end_page());
}

# Returns the different components of a resourcedata key.
# Keys: scope_type, scope, realm_type, realm, realm_title,
#       realm_exists, parameter_part, parameter_name.
# Was used by clean_parameters (which is unused).
#
# @param {string} $key - the parameter key
# @returns {hash}
sub parse_key {
    my ($key) = @_;
    my %data;
    my ($middle,$part,$name)=
    ($key=~/^$env{'request.course.id'}\.(?:(.+)\.)*([\w\s\-]+)\.(\w+)$/);
    $data{'scope_type'} = 'all';
    if ($middle=~/^\[(.*)\]/) {
        $data{'scope'} = $1;
        if ($data{'scope'}=~/^useropt\:($match_username)\:($match_domain)/) {
            $data{'scope_type'} = 'user';
            $data{'scope'} = [$1,$2];
        } else {
            $data{'scope_type'} = 'secgroup';
        }
        $middle=~s/^\[(.*)\]//;
    }
    $middle=~s/\.+$//;
    $middle=~s/^\.+//;
    $data{'realm_type'}='all';
    if ($middle=~/^(.+)\_\_\_\(all\)$/) {
        $data{'realm'} = $1;
        $data{'realm_type'} = 'folder';
        $data{'realm_title'} = &Apache::lonnet::gettitle($data{'realm'});
        ($data{'realm_exists'}) = &Apache::lonnet::is_on_map($data{'realm'});
    } elsif ($middle) {
        $data{'realm'} = $middle;
        $data{'realm_type'} = 'symb';
        $data{'realm_title'} = &Apache::lonnet::gettitle($data{'realm'});
        my ($map,$resid,$url) = &Apache::lonnet::decode_symb($data{'realm'});
        $data{'realm_exists'} = &Apache::lonnet::symbverify($data{'realm'},$url);
    }

    $data{'parameter_part'} = $part;
    $data{'parameter_name'} = $name;

    return %data;
}


# Calls loncommon::start_page with the "Settings" title.
sub header {
    return &Apache::loncommon::start_page('Settings');
}



##################################################
# MAIN MENU
##################################################

# Content and problem settings main menu.
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {boolean} $parm_permission - true if the user has permission to edit the current course or section
sub print_main_menu {
    my ($r,$parm_permission)=@_;
    #
    $r->print(&header());
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Content and Problem Settings'));
    my $crstype = &Apache::loncommon::course_type();
    my $lc_crstype = lc($crstype);

    &startSettingsScreen($r,'parmset',$crstype);
    $r->print(<<ENDMAINFORMHEAD);
<form method="post" enctype="multipart/form-data"
      action="/adm/parmset" name="studentform">
ENDMAINFORMHEAD
#
    my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $vgr  = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
    my $mgr  = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
    my $dcm = &Apache::lonnet::allowed('dcm',$env{'request.course.id'});
    my $vcb = &Apache::lonnet::allowed('vcb',$env{'request.course.id'});
    my $vpa = &Apache::lonnet::allowed('vpa',$env{'request.course.id'});
    if ((!$dcm) && ($env{'request.course.sec'} ne '')) {
        $dcm = &Apache::lonnet::allowed('dcm',$env{'request.course.id'}.
                                        '/'.$env{'request.course.sec'});
    }
    if ((!$vcb) && ($env{'request.course.sec'} ne '')) {
        $vcb = &Apache::lonnet::allowed('vcb',$env{'request.course.id'}.
                                        '/'.$env{'request.course.sec'});
    }
    my (%linktext,%linktitle,%url);
    if ($parm_permission->{'edit'}) {
        %linktext = (
                     newoverview     => 'Edit Resource Parameters - Overview Mode',
                     settable        => 'Edit Resource Parameters - Table Mode',
                     setoverview     => 'Modify Resource Parameters - Overview Mode',
                    );
        %linktitle = (
                     newoverview     => 'Set/Modify resource parameters in overview mode.',
                     settable        => 'Set/Modify resource parameters in table mode.',
                     setoverview     => 'Set/Modify existing resource parameters in overview mode.',
                     );
    } else {
        %linktext = (
                     newoverview     => 'View Resource Parameters - Overview Mode',
                     settable        => 'View Resource Parameters - Table Mode',
                     setoverview     => 'View Resource Parameters - Overview Mode',
                   );
        %linktitle = (
                     newoverview     => 'Display resource parameters in overview mode.',
                     settable        => 'Display resource parameters in table mode.',
                     setoverview     => 'Display existing resource parameters in overview mode.',
                     );
    }
    if ($mgr) {
        $linktext{'resettimes'} = 'Reset Student Access Times';
        $linktitle{'resettimes'} = "Reset access times for folders/maps, resources or the $lc_crstype.";
        $url{'resettimes'} = '/adm/helper/resettimes.helper';
    } elsif ($vgr) {
        $linktext{'resettimes'} = 'Display Student Access Times',
        $linktitle{'resettimes'} = "Display access times for folders/maps, resources or the $lc_crstype.",
        $url{'resettimes'} = '/adm/accesstimes';
    }
    my @menu =
        ( { categorytitle=>"Content Settings for this $crstype",
        items => [
          { linktext => 'Portfolio Metadata',
            url => '/adm/parmset?action=setrestrictmeta',
            permission => $parm_permission->{'setrestrictmeta'},
            linktitle => "Restrict metadata for this $lc_crstype." ,
            icon =>'contact-new.png'   ,
            },
          { linktext => $linktext{'resettimes'},
            url => $url{'resettimes'},
            permission => ($vgr || $mgr),
            linktitle => $linktitle{'resettimes'},
            icon => 'start-here.png',
            },
          { linktext => 'Blocking Communication/Resource Access',
            url => '/adm/setblock',
            permission => ($vcb || $dcm),
            linktitle => 'Configure blocking of communication/collaboration and access to resources during an exam',
            icon => 'comblock.png',
            },
          { linktext => 'Set Parameter Setting Default Actions',
            url => '/adm/parmset?action=setdefaults',
            permission => $parm_permission->{'setdefaults'},
            linktitle =>'Set default actions for parameters.'  ,
            icon => 'folder-new.png'  ,
            }]},
      { categorytitle => 'New and Existing Parameter Settings for Resources',
        items => [
          { linktext => 'Edit Resource Parameters - Helper Mode',
            url => '/adm/helper/parameter.helper',
            permission => $parm_permission->{'helper'},
            linktitle =>'Set/Modify resource parameters in helper mode.'  ,
            icon => 'dialog-information.png'  ,
            #help => 'Parameter_Helper',
            },
          { linktext => $linktext{'newoverview'},
            url => '/adm/parmset?action=newoverview',
            permission => $parm_permission->{'newoverview'},
            linktitle => $linktitle{'newoverview'},
            icon => 'edit-find.png',
            #help => 'Parameter_Overview',
            },
          { linktext => $linktext{'settable'},
            url => '/adm/parmset?action=settable',
            permission => $parm_permission->{'settable'},
            linktitle => $linktitle{'settable'},
            icon => 'edit-copy.png',
            #help => 'Table_Mode',
            }]},
           { categorytitle => 'Existing Parameter Settings for Resources',
         items => [
          { linktext => $linktext{'setoverview'},
            url => '/adm/parmset?action=setoverview',
            permission => $parm_permission->{'setoverview'},
            linktitle => $linktitle{'setoverview'},
            icon => 'preferences-desktop-wallpaper.png',
            #help => 'Parameter_Overview',
            },
          { linktext => 'Change Log',
            url => '/adm/parmset?action=parameterchangelog',
            permission => $parm_permission->{'parameterchangelog'},
            linktitle =>"View parameter and $lc_crstype blog posting/user notification change log."  ,
            icon => 'document-properties.png',
            }]}
          );
    $r->print(&Apache::lonhtmlcommon::generate_menu(@menu));
    $r->print('</form>');
    &endSettingsScreen($r);
    $r->print(&Apache::loncommon::end_page());
    return;
}



##################################################
# PORTFOLIO METADATA
##################################################

# Prints HTML to edit an item of portfolio metadata. The HTML contains several td elements (no tr).
# It looks like field titles are not localized.
#
# @param {Apache2::RequestRec} $r - the Apache request
# @param {string} $field_name - metadata field name
# @param {string} $field_text - metadata field title, in English unless manually added
# @param {boolean} $added_flag - true if the field was manually added
sub output_row {
    my ($r, $field_name, $field_text, $added_flag) = @_;
    my $output;
    my $options=$env{'course.'.$env{'request.course.id'}.'.metadata.'.$field_name.'.options'};
    my $values=$env{'course.'.$env{'request.course.id'}.'.metadata.'.$field_name.'.values'};
    if (!defined($options)) {
        $options = 'active,stuadd';
        $values = '';
    }
    if (!($options =~ /deleted/)) {
        my @options= ( ['active', 'Show to student'],
                    ['stuadd', 'Provide text area for students to type metadata'],
                    ['choices','Provide choices for students to select from']);
#           ['onlyone','Student may select only one choice']);
        if ($added_flag) {
            push @options,['deleted', 'Delete Metadata Field'];
        }
       $output = &Apache::loncommon::start_data_table_row();
        $output .= '<td><strong>'.$field_text.':</strong></td>';
        $output .= &Apache::loncommon::end_data_table_row();
        foreach my $opt (@options) {
            my $checked = ($options =~ m/$opt->[0]/) ? ' checked="checked" ' : '' ;
            $output .= &Apache::loncommon::continue_data_table_row();
            $output .= '<td>'.('&nbsp;' x 5).'<label>
                    <input type="checkbox" name="'.
                    $field_name.'_'.$opt->[0].'" value="yes"'.$checked.' />'.
                    &mt($opt->[1]).'</label></td>';
            $output .= &Apache::loncommon::end_data_table_row();
        }
        $output .= &Apache::loncommon::continue_data_table_row();
        $output .= '<td>'.('&nbsp;' x 10).'<input name="'.$field_name.'_values" type="text" value="'.$values.'" size="80" /></td>';
        $output .= &Apache::loncommon::end_data_table_row();
        my $multiple_checked;
        my $single_checked;
        if ($options =~ m/onlyone/) {
            $multiple_checked = '';
            $single_checked = ' checked="checked"';
        } else {
            $multiple_checked = ' checked="checked"';
            $single_checked = '';
        }
        $output .= &Apache::loncommon::continue_data_table_row();
        $output .= '<td>'.('&nbsp;' x 10).'
                    <input type="radio" name="'.$field_name.'_onlyone" value="multiple"'.$multiple_checked .' />
                    '.&mt('Student may select multiple choices from list').'</td>';
        $output .= &Apache::loncommon::end_data_table_row();
        $output .= &Apache::loncommon::continue_data_table_row();
        $output .= '<td>'.('&nbsp;' x 10).'
                    <input type="radio" name="'.$field_name.'_onlyone"  value="single"'.$single_checked.' />
                    '.&mt('Student may select only one choice from list').'</td>';
        $output .= &Apache::loncommon::end_data_table_row();
    }
    return ($output);
}


# UI to order portfolio metadata fields.
# Currently useless because addmetafield does not work.
#
# @param {Apache2::RequestRec} $r - the Apache request
sub order_meta_fields {
    my ($r)=@_;
    my $idx = 1;
    my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};;
    $r->print(&Apache::loncommon::start_page('Order Metadata Fields'));
    &Apache::lonhtmlcommon::add_breadcrumb(
        {href=>'/adm/parmset?action=addmetadata',
        text=>"Add Metadata Field"});
    &Apache::lonhtmlcommon::add_breadcrumb(
        {href=>"/adm/parmset?action=setrestrictmeta",
        text=>"Restrict Metadata"},
        {text=>"Order Metadata"});
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Order Metadata'));
    &startSettingsScreen($r,'parmset',$crstype);
    if ($env{'form.storeorder'}) {
        my $newpos = $env{'form.newpos'} - 1;
        my $currentpos = $env{'form.currentpos'} - 1;
        my @neworder = ();
        my @oldorder = split(/,/,$env{'course.'.$env{'request.course.id'}.'.metadata.addedorder'});
        my $i;
        if ($newpos > $currentpos) {
        # moving stuff up
            for ($i=0;$i<$currentpos;$i++) {
                $neworder[$i]=$oldorder[$i];
            }
            for ($i=$currentpos;$i<$newpos;$i++) {
                $neworder[$i]=$oldorder[$i+1];
            }
            $neworder[$newpos]=$oldorder[$currentpos];
            for ($i=$newpos+1;$i<=$#oldorder;$i++) {
                $neworder[$i]=$oldorder[$i];
            }
        } else {
        # moving stuff down
            for ($i=0;$i<$newpos;$i++) {
                $neworder[$i]=$oldorder[$i];
            }
            $neworder[$newpos]=$oldorder[$currentpos];
            for ($i=$newpos+1;$i<$currentpos+1;$i++) {
                $neworder[$i]=$oldorder[$i-1];
            }
            for ($i=$currentpos+1;$i<=$#oldorder;$i++) {
                $neworder[$i]=$oldorder[$i];
            }
        }
        my $ordered_fields = join ",", @neworder;
        my $put_result = &Apache::lonnet::put('environment',
                        {'metadata.addedorder'=>$ordered_fields},$dom,$crs);
        &Apache::lonnet::appenv({'course.'.$env{'request.course.id'}.'.metadata.addedorder' => $ordered_fields});
    }
    my $fields = &get_added_meta_fieldnames($env{'request.course.id'});
    my $ordered_fields;
    my @fields_in_order = split(/,/,$env{'course.'.$env{'request.course.id'}.'.metadata.addedorder'});
    if (!@fields_in_order) {
        # no order found, pick sorted order then create metadata.addedorder key.
        foreach my $key (sort(keys(%$fields))) {
            push @fields_in_order, $key;
            $ordered_fields = join ",", @fields_in_order;
        }
        my $put_result = &Apache::lonnet::put('environment',
                            {'metadata.addedorder'=>$ordered_fields},$dom,$crs);
    }
    $r->print('<table>');
    my $num_fields = scalar(@fields_in_order);
    foreach my $key (@fields_in_order) {
        $r->print('<tr><td>');
        $r->print('<form method="post" action="">');
        $r->print('<select name="newpos" onchange="this.form.submit()">');
        for (my $i = 1;$i le $num_fields;$i ++) {
            if ($i eq $idx) {
                $r->print('<option value="'.$i.'"  SELECTED>('.$i.')</option>');
            } else {
                $r->print('<option value="'.$i.'">'.$i.'</option>');
            }
        }
        $r->print('</select></td><td>');
        $r->print('<input type="hidden" name="currentpos" value="'.$idx.'" />');
        $r->print('<input type="hidden" name="storeorder" value="true" />');
        $r->print('</form>');
        $r->print($$fields{$key}.'</td></tr>');
        $idx ++;
    }
    $r->print('</table>');
    &endSettingsScreen($r);
    return 'ok';
}


# Returns HTML with a Continue button redirecting to the initial portfolio metadata screen.
# @returns {string}
sub continue {
    my $output;
    $output .= '<form action="" method="post">';
    $output .= '<input type="hidden" name="action" value="setrestrictmeta" />';
    $output .= '<input type="submit" value="'.&mt('Continue').'" />';
    return ($output);
}


# UI to add a metadata field.
# Currenly does not work because of an HTML error (the field is not visible).
#
# @param {Apache2::RequestRec} $r - the Apache request
sub addmetafield {
    my ($r)=@_;
    &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/parmset?action=addmetadata',
        text=>"Add Metadata Field"});
    $r->print(&Apache::loncommon::start_page('Add Metadata Field'));
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Add Metadata Field'));
    my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
    &startSettingsScreen($r,'parmset',$crstype);
    if (exists($env{'form.undelete'})) {
        my @meta_fields = &Apache::loncommon::get_env_multiple('form.undeletefield');
        foreach my $meta_field(@meta_fields) {
            my $options = $env{'course.'.$env{'request.course.id'}.'.metadata.'.$meta_field.'.options'};
            $options =~ s/deleted//;
            $options =~ s/,,/,/;
            my $put_result = &Apache::lonnet::put('environment',
                                        {'metadata.'.$meta_field.'.options'=>$options},$dom,$crs);

            $r->print(&mt('Undeleted Metadata Field [_1] with result [_2]',
                          '<strong>'.$env{'course.'.$env{'request.course.id'}.'.metadata.'.$meta_field.'.added'}.
                          '</strong>',$put_result).
                      '<br />');
        }
        $r->print(&continue());
    } elsif (exists($env{'form.fieldname'})) {
        my $meta_field = $env{'form.fieldname'};
        my $display_field = $env{'form.fieldname'};
        $meta_field =~ s/\W/_/g;
        $meta_field =~ tr/A-Z/a-z/;
        my $put_result = &Apache::lonnet::put('environment',
                            {'metadata.'.$meta_field.'.values'=>"",
                             'metadata.'.$meta_field.'.added'=>"$display_field",
                             'metadata.'.$meta_field.'.options'=>""},$dom,$crs);
        $r->print(&mt('Added new Metadata Field [_1] with result [_2]',
                      '<strong>'.$env{'form.fieldname'}.'</strong>',$put_result).
                  '<br />');
        $r->print(&continue());
    } else {
        my $fields = &get_deleted_meta_fieldnames($env{'request.course.id'});
        if ($fields) {
            $r->print(&mt('You may undelete previously deleted fields.').
                      '<br />'.
                      &mt('Check those you wish to undelete and click Undelete.').
                      '<br />');
            $r->print('<form method="post" action="">');
            foreach my $key(keys(%$fields)) {
                $r->print('<label><input type="checkbox" name="undeletefield" value="'.$key.'" />'.$$fields{$key}.'</label><br /');
            }
            $r->print('<input type="submit" name="undelete" value="'.&mt('Undelete').'" />');
            $r->print('</form>');
        }
        $r->print('<hr />'.
                  &mt('[_1]Or[_2] you may enter a new metadata field name.',
                      '<strong>','</strong>').
                  '<form method="post" action="/adm/parmset?action=addmetadata">');
        $r->print('<input type="text" name="fieldname" /><br />');
        $r->print('<input type="submit" value="'.&mt('Add Metadata Field').'" />');
        $r->print('</form>');
    }
    &endSettingsScreen($r);
}



# Display or save portfolio metadata.
#
# @param {Apache2::RequestRec} $r - the Apache request
sub setrestrictmeta {
    my ($r)=@_;
    my $next_meta;
    my $output;
    my $item_num;
    my $put_result;
    &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/parmset?action=setrestrictmeta',
        text=>"Restrict Metadata"});
    $r->print(&Apache::loncommon::start_page('Restrict Metadata'));
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Restrict Metadata'));
    my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
    &startSettingsScreen($r,'parmset',$crstype);
    my $key_base = $env{'course.'.$env{'request.course.id'}.'.'};
    my $save_field = '';
    my %lt = &Apache::lonlocal::texthash(
                                           addm => 'Add Metadata Field',
                                           ordm => 'Order Metadata Fields',
                                           save => 'Save',
                                        );
    if ($env{'form.restrictmeta'}) {
        foreach my $field (sort(keys(%env))) {
            if ($field=~m/^form.(.+)_(.+)$/) {
                my $options;
                my $meta_field = $1;
                my $meta_key = $2;
                if ($save_field ne $meta_field) {
                    $save_field = $meta_field;
                    if ($env{'form.'.$meta_field.'_stuadd'}) {
                        $options.='stuadd,';
                    }
                    if ($env{'form.'.$meta_field.'_choices'}) {
                        $options.='choices,';
                    }
                    if ($env{'form.'.$meta_field.'_onlyone'} eq 'single') {
                        $options.='onlyone,';
                    }
                    if ($env{'form.'.$meta_field.'_active'}) {
                        $options.='active,';
                    }
                    if ($env{'form.'.$meta_field.'_deleted'}) {
                        $options.='deleted,';
                    }
                    my $name = $save_field;
                    $put_result = &Apache::lonnet::put('environment',
                        {'metadata.'.$meta_field.'.options'=>$options,
                        'metadata.'.$meta_field.'.values'=>$env{'form.'.$meta_field.'_values'},
                        },$dom,$crs);
                }
            }
        }
    }
    &Apache::lonnet::coursedescription($env{'request.course.id'},
                       {'freshen_cache' => 1});
    # Get the default metadata fields
    my %metadata_fields = &Apache::lonmeta::fieldnames('portfolio');
    # Now get possible added metadata fields
    my $added_metadata_fields = &get_added_meta_fieldnames($env{'request.course.id'});
    $output .= &Apache::loncommon::start_data_table();
    foreach my $field (sort(keys(%metadata_fields))) {
        if ($field ne 'courserestricted') {
            $output.= &output_row($r,$field,$metadata_fields{$field});
        }
    }
    my $buttons = (<<ENDButtons);
        <input type="submit" name="restrictmeta" value="$lt{'save'}" />
        </form><br />
        <form method="post" action="/adm/parmset?action=addmetadata" name="form1">
        <input type="submit" name="restrictmeta" value="$lt{'addm'}" />
        </form>
        <br />
        <form method="post" action="/adm/parmset?action=ordermetadata" name="form2">
        <input type="submit" name="restrictmeta" value="$lt{'ordm'}" />
ENDButtons
    my $added_flag = 1;
    foreach my $field (sort(keys(%$added_metadata_fields))) {
        $output.= &output_row($r,$field,$$added_metadata_fields{$field},$added_flag);
    }
    $output .= &Apache::loncommon::end_data_table();
    $r->print(<<ENDenv);
        <form method="post" action="/adm/parmset?action=setrestrictmeta" name="form">
        $output
        $buttons
        </form>
ENDenv
    &endSettingsScreen($r);
    $r->print(&Apache::loncommon::end_page());
    return 'ok';
}


# Returns metadata fields that have been manually added.
#
# @param {string} $cid - course id
# @returns {hash reference} - hash field name -> field title (not localized)
sub get_added_meta_fieldnames {
    my ($cid) = @_;
    my %fields;
    foreach my $key(%env) {
        if ($key =~ m/\Q$cid\E\.metadata\.(.+)\.added$/) {
            my $field_name = $1;
            my ($display_field_name) = $env{$key};
            $fields{$field_name} = $display_field_name;
        }
    }
    return \%fields;
}


# Returns metadata fields that have been manually added and deleted.
#
# @param {string} $cid - course id
# @returns {hash reference} - hash field name -> field title (not localized)
sub get_deleted_meta_fieldnames {
    my ($cid) = @_;
    my %fields;
    foreach my $key(%env) {
        if ($key =~ m/\Q$cid\E\.metadata\.(.+)\.added$/) {
            my $field_name = $1;
            if ($env{'course.'.$env{'request.course.id'}.'.metadata.'.$field_name.'.options'} =~ m/deleted/) {
                my ($display_field_name) = $env{$key};
                $fields{$field_name} = $display_field_name;
            }
        }
    }
    return \%fields;
}


##################################################
# PARAMETER SETTINGS DEFAULT ACTIONS
##################################################

# UI to change parameter setting default actions
#
# @param {Apache2::RequestRec} $r - the Apache request
sub defaultsetter {
    my ($r) = @_;

    &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/parmset?action=setdefaults',
        text=>"Set Defaults"});
    my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
    my $start_page =
        &Apache::loncommon::start_page('Parameter Setting Default Actions');
    my $breadcrumbs = &Apache::lonhtmlcommon::breadcrumbs('Defaults');
    $r->print($start_page.$breadcrumbs);
    &startSettingsScreen($r,'parmset',$crstype);
    $r->print('<form method="post" action="/adm/parmset?action=setdefaults" name="defaultform">');

    my @ids=();
    my %typep=();
    my %keyp=();
    my %allparms=();
    my %allparts=();
    my %allmaps=();
    my %mapp=();
    my %symbp=();
    my %maptitles=();
    my %uris=();
    my %keyorder=&standardkeyorder();
    my %defkeytype=();

    &extractResourceInformation(\@ids, \%typep,\%keyp, \%allparms, \%allparts, \%allmaps,
                \%mapp, \%symbp,\%maptitles,\%uris,
                \%keyorder,\%defkeytype);
    if ($env{'form.storerules'}) {
        my %newrules=();
        my @delrules=();
        my %triggers=();
        foreach my $key (keys(%env)) {
            if ($key=~/^form\.(\w+)\_action$/) {
                my $tempkey=$1;
                my $action=$env{$key};
                if ($action) {
                    $newrules{$tempkey.'_action'}=$action;
                    if ($action ne 'default') {
                        my ($whichaction,$whichparm)=($action=~/^(.*\_)([^\_]+)$/);
                        $triggers{$whichparm}.=$tempkey.':';
                    }
                    $newrules{$tempkey.'_type'}=$defkeytype{$tempkey};
                    if (&isdateparm($defkeytype{$tempkey})) {
                        $newrules{$tempkey.'_days'}=$env{'form.'.$tempkey.'_days'};
                        $newrules{$tempkey.'_hours'}=$env{'form.'.$tempkey.'_hours'};
                        $newrules{$tempkey.'_min'}=$env{'form.'.$tempkey.'_min'};
                        $newrules{$tempkey.'_sec'}=$env{'form.'.$tempkey.'_sec'};
                    } else {
                        $newrules{$tempkey.'_value'}=$env{'form.'.$tempkey.'_value'};
                        $newrules{$tempkey.'_triggervalue'}=$env{'form.'.$tempkey.'_triggervalue'};
                    }
                } else {
                    push(@delrules,$tempkey.'_action');
                    push(@delrules,$tempkey.'_type');
                    push(@delrules,$tempkey.'_hours');
                    push(@delrules,$tempkey.'_min');
                    push(@delrules,$tempkey.'_sec');
                    push(@delrules,$tempkey.'_value');
                }
            }
        }
        foreach my $key (keys(%allparms)) {
            $newrules{$key.'_triggers'}=$triggers{$key};
        }
        &Apache::lonnet::put('parmdefactions',\%newrules,$cdom,$cnum);
        &Apache::lonnet::del('parmdefactions',\@delrules,$cdom,$cnum);
        &resetrulescache();
    }
    my %lt=&Apache::lonlocal::texthash('days' => 'Days',
                       'hours' => 'Hours',
                       'min' => 'Minutes',
                       'sec' => 'Seconds',
                       'yes' => 'Yes',
                       'no' => 'No');
    my @standardoptions=('','default');
    my @standarddisplay=('',&mt('Default value when manually setting'));
    my @dateoptions=('','default');
    my @datedisplay=('',&mt('Default value when manually setting'));
    foreach my $tempkey (&keysindisplayorder(\%allparms,\%keyorder)) {
        unless ($tempkey) { next; }
        push @standardoptions,'when_setting_'.$tempkey;
        push @standarddisplay,&mt('Automatically set when setting ').$tempkey;
        if (&isdateparm($defkeytype{$tempkey})) {
            push @dateoptions,'later_than_'.$tempkey;
            push @datedisplay,&mt('Automatically set later than ').$tempkey;
            push @dateoptions,'earlier_than_'.$tempkey;
            push @datedisplay,&mt('Automatically set earlier than ').$tempkey;
        }
    }
    $r->print(&mt('Manual setting rules apply to all interfaces.').'<br />'.
        &mt('Automatic setting rules apply to table mode interfaces only.'));
    $r->print("\n".&Apache::loncommon::start_data_table().
          &Apache::loncommon::start_data_table_header_row().
          "<th>".&mt('Rule for parameter').'</th><th>'.
          &mt('Action').'</th><th>'.&mt('Value').'</th>'.
          &Apache::loncommon::end_data_table_header_row());
    foreach my $tempkey (&keysindisplayorder(\%allparms,\%keyorder)) {
        unless ($tempkey) { next; }
        $r->print("\n".&Apache::loncommon::start_data_table_row().
            "<td>".$allparms{$tempkey}."\n<br />(".$tempkey.')</td><td>');
        my $action=&rulescache($tempkey.'_action');
        $r->print('<select name="'.$tempkey.'_action">');
        if (&isdateparm($defkeytype{$tempkey})) {
            for (my $i=0;$i<=$#dateoptions;$i++) {
            if ($dateoptions[$i]=~/\_$tempkey$/) { next; }
            $r->print("\n<option value='$dateoptions[$i]'".
                ($dateoptions[$i] eq $action?' selected="selected"':'').
                ">$datedisplay[$i]</option>");
            }
        } else {
            for (my $i=0;$i<=$#standardoptions;$i++) {
            if ($standardoptions[$i]=~/\_$tempkey$/) { next; }
            $r->print("\n<option value='$standardoptions[$i]'".
                ($standardoptions[$i] eq $action?' selected="selected"':'').
                ">$standarddisplay[$i]</option>");
            }
        }
        $r->print('</select>');
        unless (&isdateparm($defkeytype{$tempkey})) {
            $r->print("\n<br />".&mt('Triggering value(s) of other parameter (optional, comma-separated):').
                '<input type="text" size="20" name="'.$tempkey.'_triggervalue" value="'.&rulescache($tempkey.'_triggervalue').'" />');
        }
        $r->print("\n</td><td>\n");

        if (&isdateparm($defkeytype{$tempkey})) {
            my $days=&rulescache($tempkey.'_days');
            my $hours=&rulescache($tempkey.'_hours');
            my $min=&rulescache($tempkey.'_min');
            my $sec=&rulescache($tempkey.'_sec');
            $r->print(<<ENDINPUTDATE);
    <input name="$tempkey\_days" type="text" size="4" value="$days" />$lt{'days'}<br />
    <input name="$tempkey\_hours" type="text" size="4" value="$hours" />$lt{'hours'}<br />
    <input name="$tempkey\_min" type="text" size="4" value="$min" />$lt{'min'}<br />
    <input name="$tempkey\_sec" type="text" size="4" value="$sec" />$lt{'sec'}
ENDINPUTDATE
        } elsif ($defkeytype{$tempkey} eq 'string_yesno') {
                my $yeschecked='';
                my $nochecked='';
                if (&rulescache($tempkey.'_value') eq 'yes') { $yeschecked=' checked="checked"'; }
                if (&rulescache($tempkey.'_value') eq 'no') { $nochecked=' checked="checked"'; }

            $r->print(<<ENDYESNO);
    <label><input type="radio" name="$tempkey\_value" value="yes"$yeschecked /> $lt{'yes'}</label><br />
    <label><input type="radio" name="$tempkey\_value" value="no"$nochecked /> $lt{'no'}</label>
ENDYESNO
        } else {
            $r->print('<input type="text" size="20" name="'.$tempkey.'_value" value="'.&rulescache($tempkey.'_value').'" />');
        }
        $r->print('</td>'.&Apache::loncommon::end_data_table_row());
    }
    $r->print(&Apache::loncommon::end_data_table().
          "\n".'<input type="submit" name="storerules" value="'.
          &mt('Save').'" /></form>'."\n");
    &endSettingsScreen($r);
    $r->print(&Apache::loncommon::end_page());
    return;
}

##################################################
# PARAMETER CHANGES LOG
##################################################

# Returns some info for a parameter log entry.
# Returned entries:
# $realm - HTML title for the parameter level and resource
# $section - parameter section
# $name - parameter name
# $part - parameter part
# $what - $part.'.'.$name
# $middle - resource symb ?
# $uname - user name (same as given)
# $udom - user domain (same as given)
# $issection - section or group name
# $realmdescription - title for the parameter level and resource (without using HTML)
#
# @param {string} $key - parameter log key
# @param {string} $uname - user name
# @param {string} $udom - user domain
# @param {boolean} $typeflag - .type log entry
# @returns {Array}
sub components {
    my ($key,$uname,$udom,$typeflag)=@_;

    if ($typeflag) {
        $key=~s/\.type$//;
    }

    my ($middle,$part,$name)=
        ($key=~/^$env{'request.course.id'}\.(?:(.+)\.)*([\w\s\-]+)\.(\w+)$/);
    my $issection;

    my $section=&mt('All Students');
    if ($middle=~/^\[(.*)\]/) {
        $issection=$1;
        $section=&mt('Group/Section').': '.$issection;
        $middle=~s/^\[(.*)\]//;
    }
    $middle=~s/\.+$//;
    $middle=~s/^\.+//;
    if ($uname) {
        $section=&mt('User').": ".&Apache::loncommon::plainname($uname,$udom);
        $issection='';
    }
    my $realm='<span class="LC_parm_scope_all">'.&mt('All Resources').'</span>';
    my $realmdescription=&mt('all resources');
    if ($middle=~/^(.+)\_\_\_\((all|rec)\)$/) {
        my $mapurl = $1;
        my $maplevel = $2;
        my $leveltitle = &mt('Folder/Map');
        if ($maplevel eq 'rec') {
            $leveltitle = &mt('Recursive');
        }
        $realm='<span class="LC_parm_scope_folder">'.$leveltitle.
            ': '.&Apache::lonnet::gettitle($mapurl).' <span class="LC_parm_folder"><br />('.
            $mapurl.')</span></span>';
        $realmdescription=&mt('folder').' '.&Apache::lonnet::gettitle($mapurl);
    } elsif ($middle) {
        my ($map,$id,$url)=&Apache::lonnet::decode_symb($middle);
        $realm='<span class="LC_parm_scope_resource">'.&mt('Resource').
            ': '.&Apache::lonnet::gettitle($middle).' <br /><span class="LC_parm_symb">('.$url.
            ' in '.$map.' id: '.$id.')</span></span>';
        $realmdescription=&mt('resource').' '.&Apache::lonnet::gettitle($middle);
    }
    my $what=$part.'.'.$name;
    return ($realm,$section,$name,$part,
        $what,$middle,$uname,$udom,$issection,$realmdescription);
}

my %standard_parms; # hash parameter name -> parameter title (not localized)
my %standard_parms_types; # hash parameter name -> parameter type

# Reads parameter info from packages.tab into %standard_parms.
sub load_parameter_names {
    open(my $config,"<","$Apache::lonnet::perlvar{'lonTabDir'}/packages.tab");
    while (my $configline=<$config>) {
        if ($configline !~ /\S/ || $configline=~/^\#/) { next; }
        chomp($configline);
        my ($short,$plain)=split(/:/,$configline);
        my (undef,$name,$type)=split(/\&/,$short,3);
        if ($type eq 'display') {
            $standard_parms{$name} = $plain;
        } elsif ($type eq 'type') {
                $standard_parms_types{$name} = $plain;
        }
    }
    close($config);
    $standard_parms{'int_pos'}      = 'Positive Integer';
    $standard_parms{'int_zero_pos'} = 'Positive Integer or Zero';
    $standard_parms{'scoreformat'}  = 'Format for display of score';
}

# Returns a parameter title for standard parameters, the name for others.
#
# @param {string} $name - parameter name
# @returns {string}
sub standard_parameter_names {
    my ($name)=@_;
    if (!%standard_parms) {
        &load_parameter_names();
    }
    if ($standard_parms{$name}) {
        return $standard_parms{$name};
    } else {
        return $name;
    }
}

# Returns a parameter type for standard parameters, undef for others.
#
# @param {string} $name - parameter name
# @returns {string}
sub standard_parameter_types {
    my ($name)=@_;
    if (!%standard_parms_types) {
        &load_parameter_names();
    }
    if ($standard_parms_types{$name}) {
        return $standard_parms_types{$name};
    }
    return;
}

# Returns a parameter level title (not localized) from the parameter level name.
#
# @param {string} $name - parameter level name (recognized: resourcelevel|maplevel|maplevelrecurse|courselevel)
# @returns {string}
sub standard_parameter_levels {
    my ($name)=@_;
    my %levels = (
                    'resourcelevel'   => 'a single resource',
                    'maplevel'        => 'the enclosing map/folder', 
                    'maplevelrecurse' => 'the enclosing map/folder (recursive into sub-folders)',
                    'courselevel'     => 'the general (course) level',
                 );
    if ($levels{$name}) {
        return $levels{$name};
    }
    return;
}

# Display log for parameter changes, blog postings, user notification changes.
#
# @param {Apache2::RequestRec} $r - the Apache request
sub parm_change_log {
    my ($r,$parm_permission)=@_;
    my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
    my $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
    &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/parmset?action=settable',
    text=>"Parameter Change Log"});
    my $js = '<script type="text/javascript">'."\n".
             '// <![CDATA['."\n".
             &Apache::loncommon::display_filter_js('parmslog')."\n".
             '// ]]>'."\n".
             '</script>'."\n";
    $r->print(&Apache::loncommon::start_page('Parameter Change Log',$js));
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Parameter Change Log'));
    &startSettingsScreen($r,'parmset',$crstype);
    my %parmlog=&Apache::lonnet::dump('nohist_parameterlog',$cdom,$cnum);

    if ((keys(%parmlog))[0]=~/^error\:/) { undef(%parmlog); }

    $r->print('<div class="LC_left_float">'.
              '<fieldset><legend>'.&mt('Display of Changes').'</legend>'.
              '<form action="/adm/parmset?action=parameterchangelog"
                     method="post" name="parameterlog">');

    my %saveable_parameters = ('show' => 'scalar',);
    &Apache::loncommon::store_course_settings('parameter_log',
                                              \%saveable_parameters);
    &Apache::loncommon::restore_course_settings('parameter_log',
                                                \%saveable_parameters);
    $r->print(&Apache::loncommon::display_filter('parmslog').'&nbsp;'."\n".
              '<input type="submit" value="'.&mt('Display').'" />'.
              '</form></fieldset></div><br clear="all" />');

    my $readonly = 1;
    if ($parm_permission->{'edit'}) {
        undef($readonly);
    }
    my $courseopt=&Apache::lonnet::get_courseresdata($cnum,$cdom);
    $r->print(&Apache::loncommon::start_data_table().&Apache::loncommon::start_data_table_header_row().
          '<th>'.&mt('Time').'</th><th>'.&mt('User').'</th><th>'.&mt('Extent').'</th><th>'.&mt('Users').'</th><th>'.
          &mt('Parameter').'</th><th>'.&mt('Part').'</th><th>'.&mt('New Value').'</th>');
    unless ($readonly) {
        $r->print('<th>'.&mt('Announce').'</th>');
    }
    $r->print(&Apache::loncommon::end_data_table_header_row());
    my $shown=0;
    my $folder='';
    if ($env{'form.displayfilter'} eq 'currentfolder') {
        my $last='';
        if (tie(my %hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                &GDBM_READER(),0640)) {
            $last=$hash{'last_known'};
            untie(%hash);
        }
        if ($last) { ($folder) = &Apache::lonnet::decode_symb($last); }
    }
    my $numgroups = 0;
    my @groups;
    if ($env{'request.course.groups'} ne '') {
        @groups = split(/:/,$env{'request.course.groups'});
        $numgroups = scalar(@groups);
    }
    foreach my $id (sort {
                if ($parmlog{$b}{'exe_time'} ne $parmlog{$a}{'exe_time'}) {
                    return $parmlog{$b}{'exe_time'} <=>$parmlog{$a}{'exe_time'}
                }
                my $aid = (split('00000',$a))[-1];
                my $bid = (split('00000',$b))[-1];
                return $bid<=>$aid;
            } (keys(%parmlog))) {
        my @changes=keys(%{$parmlog{$id}{'logentry'}});
        my $count = 0;
        my $time =
            &Apache::lonlocal::locallocaltime($parmlog{$id}{'exe_time'});
        my $plainname =
            &Apache::loncommon::plainname($parmlog{$id}{'exe_uname'},
                        $parmlog{$id}{'exe_udom'});
        my $about_me_link =
            &Apache::loncommon::aboutmewrapper($plainname,
                            $parmlog{$id}{'exe_uname'},
                            $parmlog{$id}{'exe_udom'});
        my $send_msg_link='';
        if ((!$readonly) && 
            (($parmlog{$id}{'exe_uname'} ne $env{'user.name'})
            || ($parmlog{$id}{'exe_udom'} ne $env{'user.domain'}))) {
            $send_msg_link ='<br />'.
            &Apache::loncommon::messagewrapper(&mt('Send message'),
                            $parmlog{$id}{'exe_uname'},
                            $parmlog{$id}{'exe_udom'});
        }
        my $row_start=&Apache::loncommon::start_data_table_row();
        my $makenewrow=0;
        my %istype=();
        my $output;
        foreach my $changed (reverse(sort(@changes))) {
                my $value=$parmlog{$id}{'logentry'}{$changed};
            my $typeflag = ($changed =~/\.type$/ &&
                    !exists($parmlog{$id}{'logentry'}{$changed.'.type'}));
            my ($realm,$section,$parmname,$part,$what,$middle,$uname,$udom,$issection,$realmdescription)=
                &components($changed,$parmlog{$id}{'uname'},$parmlog{$id}{'udom'},$typeflag);
            if ($env{'request.course.sec'} ne '') {
                next if (($issection ne '') && (!(($issection eq $env{'request.course.sec'}) ||
                                                  ($numgroups && (grep(/^\Q$issection\E$/,@groups))))));
                if ($uname ne '') {
                    my $stusection = &Apache::lonnet::getsection($uname,$udom,$env{'request.course.id'});
                    next if (($stusection ne '-1') && ($stusection ne $env{'request.course.sec'})); 
                }
            }
            if ($env{'form.displayfilter'} eq 'currentfolder') {
                if ($folder) {
                    if ($middle!~/^\Q$folder\E/) { next; }
                }
            }
            if ($typeflag) {
                $istype{$parmname}=$value;
                if (!$env{'form.includetypes'}) { next; }
            }
            $count++;
            if ($makenewrow) {
                $output .= $row_start;
            } else {
                $makenewrow=1;
            }
            my $parmitem = &standard_parameter_names($parmname);
            $output .='<td>'.$realm.'</td><td>'.$section.'</td><td>'.
                &mt($parmitem).'</td><td>'.
                ($part?&mt('Part: [_1]',$part):&mt('All Parts')).'</td><td>';
            my $stillactive=0;
            if ($parmlog{$id}{'delflag'}) {
                $output .= &mt('Deleted');
            } else {
                if ($typeflag) {
                    my $parmitem = &standard_parameter_names($value); 
                    $parmitem = &mt($parmitem);
                    $output .= &mt('Type: [_1]',$parmitem);
                } else {
                    my $toolsymb;
                    if ($middle =~ /ext\.tool$/) {
                        $toolsymb = $middle;
                    }
                    my ($level,@all)=&parmval_by_symb($what,$middle,
                        &Apache::lonnet::metadata($middle,$what,$toolsymb),
                        $uname,$udom,$issection,$issection,$courseopt);
                    my $showvalue = $value;
                    if ($istype{$parmname} eq '') {
                        my $type = &standard_parameter_types($parmname);
                        if ($type ne '') {
                            if (&isdateparm($type)) {
                                $showvalue =
                                    &Apache::lonlocal::locallocaltime($value);
                            }
                        }
                    } else {
                        if (&isdateparm($istype{$parmname})) {
                            $showvalue = &Apache::lonlocal::locallocaltime($value);
                        }
                    }
                    $output .= $showvalue;
                    if ($value ne $all[$level]) {
                        $output .= '<br /><span class="LC_warning">'.&mt('Not active anymore').'</span>';
                    } else {
                        $stillactive=1;
                    }
                }
            }
            $output .= '</td>';

            unless ($readonly) { 
                $output .= '<td>';
                if ($stillactive) {
                    my $parmitem = &standard_parameter_names($parmname);
                    $parmitem = &mt($parmitem);
                    my $title=&mt('Changed [_1]',$parmitem);
                    my $description=&mt('Changed [_1] for [_2] to [_3]',
                        $parmitem,$realmdescription,
                        (&isdateparm($istype{$parmname})?&Apache::lonlocal::locallocaltime($value):$value));
                    if (($uname) && ($udom)) {
                        $output .=
                        &Apache::loncommon::messagewrapper('Notify User',
                                                           $uname,$udom,$title,
                                                           $description);
                    } else {
                        $output .=
                            &Apache::lonrss::course_blog_link($id,$title,
                                                              $description);
                    }
                }
                $output .= '</td>';
            }
            $output .= &Apache::loncommon::end_data_table_row();
        }
        if ($env{'form.displayfilter'} eq 'containing') {
            my $wholeentry=$about_me_link.':'.
            $parmlog{$id}{'exe_uname'}.':'.$parmlog{$id}{'exe_udom'}.':'.
            $output;
            if ($wholeentry!~/\Q$env{'form.containingphrase'}\E/i) { next; }
        }
        if ($count) {
            $r->print($row_start.'<td rowspan="'.$count.'">'.$time.'</td>
                        <td rowspan="'.$count.'">'.$about_me_link.
            '<br /><tt>'.$parmlog{$id}{'exe_uname'}.
                        ':'.$parmlog{$id}{'exe_udom'}.'</tt>'.
            $send_msg_link.'</td>'.$output);
            $shown++;
        }
        if (!($env{'form.show'} eq &mt('all')
            || $shown<=$env{'form.show'})) { last; }
    }
    $r->print(&Apache::loncommon::end_data_table());
    &endSettingsScreen($r);
    $r->print(&Apache::loncommon::end_page());
}

##################################################
# MISC !
##################################################

# Stores slot information.
# Used by table UI
# FIXME: I don't understand how this can work when the symb is not defined (if only a map was selected)
#
# @param {string} $slot_name - slot name
# @param {string} $cdom - course domain
# @param {string} $cnum - course number
# @param {string} $symb - resource symb
# @param {string} $uname - user name
# @param {string} $udom - user domain
# @returns {string} - 'ok' or error name
sub update_slots {
    my ($slot_name,$cdom,$cnum,$symb,$uname,$udom) = @_;
    my %slot=&Apache::lonnet::get_slot($slot_name);
    if (!keys(%slot)) {
        return 'error: slot does not exist';
    }
    my $max=$slot{'maxspace'};
    if (!defined($max)) { $max=99999; }

    my %consumed=&Apache::lonnet::dump('slot_reservations',$cdom,$cnum,
                                       "^$slot_name\0");
    my ($tmp)=%consumed;
    if ($tmp=~/^error: 2 / ) {
        return 'error: unable to determine current slot status';
    }
    my $last=0;
    foreach my $key (keys(%consumed)) {
        my $num=(split('\0',$key))[1];
        if ($num > $last) { $last=$num; }
        if ($consumed{$key}->{'name'} eq $uname.':'.$udom) {
            return 'ok';
        }
    }

    if (scalar(keys(%consumed)) >= $max) {
        return 'error: no space left in slot';
    }
    my $wanted=$last+1;

    my %reservation=('name'      => $uname.':'.$udom,
                     'timestamp' => time,
                     'symb'      => $symb);

    my $success=&Apache::lonnet::newput('slot_reservations',
                                        {"$slot_name\0$wanted" =>
                                             \%reservation},
                                        $cdom, $cnum);
    if ($success eq 'ok') {
        my %storehash = (
                          symb    => $symb,
                          slot    => $slot_name,
                          action  => 'reserve',
                          context => 'parameter',
                        );
        &Apache::lonnet::write_log('course','slotreservationslog',\%storehash,
                                   '',$uname,$udom,$cnum,$cdom);

        &Apache::lonnet::write_log('course',$cdom.'_'.$cnum.'_slotlog',\%storehash,
                                   '',$uname,$udom,$uname,$udom);
    }
    return $success;
}

# Deletes a slot reservation.
# Used by table UI
# FIXME: I don't understand how this can work when the symb is not defined (if only a map was selected)
#
# @param {string} $slot_name - slot name
# @param {string} $cdom - course domain
# @param {string} $cnum - course number
# @param {string} $uname - user name
# @param {string} $udom - user domain
# @param {string} $symb - resource symb
# @returns {string} - 'ok' or error name
sub delete_slots {
    my ($slot_name,$cdom,$cnum,$uname,$udom,$symb) = @_;
    my $delresult;
    my %consumed = &Apache::lonnet::dump('slot_reservations',$cdom,
                                         $cnum, "^$slot_name\0");
    if (&Apache::lonnet::error(%consumed)) {
        return 'error: unable to determine current slot status';
    }
    my ($tmp)=%consumed;
    if ($tmp=~/^error: 2 /) {
        return 'error: unable to determine current slot status';
    }
    foreach my $key (keys(%consumed)) {
        if ($consumed{$key}->{'name'} eq $uname.':'.$udom) {
            my $num=(split('\0',$key))[1];
            my $entry = $slot_name.'\0'.$num;
            $delresult = &Apache::lonnet::del('slot_reservations',[$entry],
                                              $cdom,$cnum);
            if ($delresult eq 'ok') {
                my %storehash = (
                                  symb    => $symb,
                                  slot    => $slot_name,
                                  action  => 'release',
                                  context => 'parameter',
                                );
                &Apache::lonnet::write_log('course','slotreservationslog',\%storehash,
                                           1,$uname,$udom,$cnum,$cdom);
                &Apache::lonnet::write_log('course',$cdom.'_'.$cnum.'_slotlog',\%storehash,
                                           1,$uname,$udom,$uname,$udom);
            }
        }
    }
    return $delresult;
}

# Returns true if there is a current course.
# Used by handler
#
# @returns {boolean}
sub check_for_course_info {
    my $navmap = Apache::lonnavmaps::navmap->new();
    return 1 if ($navmap);
    return 0;
}

# Returns the current course host and host LON-CAPA version.
#
# @returns {Array} - (course hostname, major version number, minor version number)
sub parameter_release_vars { 
   my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
   my $chome = $env{'course.'.$env{'request.course.id'}.'.home'};
   my $chostname = &Apache::lonnet::hostname($chome);
   my ($cmajor,$cminor) = 
       split(/\./,&Apache::lonnet::get_server_loncaparev($cdom,$chome));
   return ($chostname,$cmajor,$cminor);
}

# Checks if the course host version can handle a parameter required version,
# and if it does, stores the release needed for the course.
#
# @param {string} $name - parameter name
# @param {string} $value - parameter value
# @param {string} $valmatch - name of the test used for checking the value
# @param {string} $namematch - name of the test used for checking the name
# @param {string} $needsrelease - version needed by the parameter, major.minor
# @param {integer} $cmajor - course major version number
# @param {integer} $cminor - course minor version number
# @returns {boolean} - true if a newer version is needed
sub parameter_releasecheck {
    my ($name,$value,$valmatch,$namematch,$needsrelease,$cmajor,$cminor) = @_;
    my $needsnewer;
    my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
    if (($cmajor < $needsmajor) || 
        ($cmajor == $needsmajor && $cminor < $needsminor)) {
        $needsnewer = 1;
    } elsif ($name) {
        if ($valmatch) {
            &Apache::lonnet::update_released_required($Apache::lonnet::needsrelease{'parameter:'.$name.'::'.$valmatch.':'});
        } elsif ($value) { 
            &Apache::lonnet::update_released_required($Apache::lonnet::needsrelease{'parameter:'.$name.':'.$value.'::'});
        }
    } elsif ($namematch) {
        &Apache::lonnet::update_released_required($Apache::lonnet::needsrelease{'parameter::::'.$namematch});
    }
    return $needsnewer;
}

sub get_permission {
    my %permission;
    my $allowed = 0;
    return (\%permission,$allowed) unless ($env{'request.course.id'});
    if ((&Apache::lonnet::allowed('opa',$env{'request.course.id'})) ||
        (&Apache::lonnet::allowed('opa',$env{'request.course.id'}.'/'.
                  $env{'request.course.sec'}))) {
        %permission= (
                       'edit'               => 1,
                       'set'                => 1,
                       'setoverview'        => 1,
                       'addmetadata'        => 1,
                       'ordermetadata'      => 1,
                       'setrestrictmeta'    => 1,
                       'newoverview'        => 1,
                       'setdefaults'        => 1,
                       'settable'           => 1,
                       'parameterchangelog' => 1,
                       'cleanparameters'    => 1,
                       'dateshift1'         => 1,
                       'dateshift2'         => 1,
                       'helper'             => 1,
         );
    } elsif ((&Apache::lonnet::allowed('vpa',$env{'request.course.id'})) ||
             (&Apache::lonnet::allowed('vpa',$env{'request.course.id'}.'/'.
                  $env{'request.course.sec'}))) {
        %permission = (
                       'set'                => 1,
                       'settable'           => 1,
                       'newoverview'        => 1,
                       'setoverview'        => 1,
                       'parameterchangelog' => 1,
                      );
    }
    foreach my $perm (values(%permission)) {
        if ($perm) { $allowed=1; last; }
    }
    return (\%permission,$allowed);
}

##################################################
# HANDLER
##################################################

# Main handler for lonparmset.
# Sub called based on request parameters action and command:
# no command or action: print_main_menu
# command 'set': assessparms (direct access to table mode for a resource)
#                (this can also be accessed simply with the symb parameter)
# action 'setoverview': overview (display all existing parameter settings)
# action 'addmetadata': addmetafield (called to add a portfolio metadata field)
# action 'ordermetadata': order_meta_fields (called to order portfolio metadata fields)
# action 'setrestrictmeta': setrestrictmeta (display or save portfolio metadata)
# action 'newoverview': newoverview (overview mode)
# action 'setdefaults': defaultsetter (UI to change parameter setting default actions)
# action 'settable': assessparms (table mode)
# action 'parameterchangelog': parm_change_log (display log for parameter changes,
#                              blog postings, user notification changes)
# action 'cleanparameters': clean_parameters (unused)
# action 'dateshift1': date_shift_one (overview mode, shift all dates)
# action 'dateshift2': date_shift_two (overview mode, shift all dates)
sub handler {
    my $r=shift;

    &reset_caches();

    &Apache::loncommon::content_type($r,'text/html');
    $r->send_http_header;
    return OK if $r->header_only;

    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                        ['action','state',
                                             'pres_marker',
                                             'pres_value',
                                             'pres_type',
                                             'filter','part',
                                             'udom','uname','symb','serial','timebase']);


    &Apache::lonhtmlcommon::clear_breadcrumbs();
    &Apache::lonhtmlcommon::add_breadcrumb({href=>"/adm/parmset",
                        text=>"Content and Problem Settings",
                        faq=>10,
                        bug=>'Instructor Interface',
                                            help =>
                                            'Parameter_Manager,Course_Environment,Parameter_Helper,Parameter_Overview,Table_Mode'});

# ----------------------------------------------------- Needs to be in a course
    my ($parm_permission,$allowed) = &get_permission();
    my $exists = &check_for_course_info();

    if ($env{'request.course.id'} && $allowed && $exists) {
        #
        # Main switch on form.action and form.state, as appropriate
        #
        # Check first if coming from someone else headed directly for
        #  the table mode
        if (($parm_permission->{'set'}) && 
            ((($env{'form.command'} eq 'set') && ($env{'form.url'})
                && (!$env{'form.dis'})) || ($env{'form.symb'}))) {
            &assessparms($r,$parm_permission);
        } elsif (! exists($env{'form.action'})) {
            &print_main_menu($r,$parm_permission);
        } elsif (!$parm_permission->{$env{'form.action'}}) {
            &print_main_menu($r,$parm_permission);
        } elsif ($env{'form.action'} eq 'setoverview') {
            &overview($r,$parm_permission);
        } elsif ($env{'form.action'} eq 'addmetadata') {
            &addmetafield($r);
        } elsif ($env{'form.action'} eq 'ordermetadata') {
            &order_meta_fields($r);
        } elsif ($env{'form.action'} eq 'setrestrictmeta') {
            &setrestrictmeta($r);
        } elsif ($env{'form.action'} eq 'newoverview') {
            &newoverview($r,$parm_permission);
        } elsif ($env{'form.action'} eq 'setdefaults') {
            &defaultsetter($r);
        } elsif ($env{'form.action'} eq 'settable') {
            &assessparms($r,$parm_permission);
        } elsif ($env{'form.action'} eq 'parameterchangelog') {
            &parm_change_log($r,$parm_permission);
        } elsif ($env{'form.action'} eq 'cleanparameters') {
            &clean_parameters($r);
        } elsif ($env{'form.action'} eq 'dateshift1') {
            &date_shift_one($r);
        } elsif ($env{'form.action'} eq 'dateshift2') {
            &date_shift_two($r);
        }
    } else {
# ----------------------------- Not in a course, or not allowed to modify parms
        if ($exists) {
            $env{'user.error.msg'}=
            "/adm/parmset:opa:0:0:Cannot modify assessment parameters";
        } else {
            $env{'user.error.msg'}=
            "/adm/parmset::0:1:Course environment gone, reinitialize the course";
        }
        return HTTP_NOT_ACCEPTABLE;
    }
    &reset_caches();

    return OK;
}

1;
__END__



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