File:  [LON-CAPA] / loncom / interface / lonpopulate.pm
Revision 1.91: download - view: text, annotated - select for diffs
Mon Jan 3 04:56:27 2022 UTC (2 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_X, version_2_11_4_uiuc, version_2_11_4_msu, version_2_11_4, HEAD
- Extend "zero enrollment failsafe" mechanism so it can also (optionally)
  protect against unwanted drops if partial data retrieved from institutional
  source for specific institutional section.

# automated enrollment configuration handler
# $Id: lonpopulate.pm,v 1.91 2022/01/03 04:56:27 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/
#
package Apache::lonpopulate;

use strict;
use lib qw(/home/httpd/lib/perl);
use Apache::lonnet;
use Apache::loncommon;
use Apache::lonhtmlcommon;
use Apache::lonlocal;
use Apache::loncoursedata;
use Apache::longroup;
use Apache::lonuserutils;
use Apache::Constants qw(:common :http REDIRECT);
use Time::Local;
use LONCAPA::Enrollment;
use LONCAPA qw(:DEFAULT :match);

###############################################################
sub header {
    my ($action,$permref) = @_;
    my $args = &make_crumbs($action,$permref);
    return 
        &Apache::loncommon::start_page('Classlist Manager',undef,$args);
}

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

sub choose_header {
    my ($action,$permref,$dom) = @_;
    my $notify_check = '/^note_[0-9]+$/';
    my $additems;
    my %js_lt = 
        &Apache::lonlocal::texthash(
            adds => 'You must select either "Enable" or "Disable" for nightly additions based on classlist changes',
            drop => 'You must select either "Enable" or "Disable" for nightly removals based on classlist changes',
            noup => 'Hence there is no update to carry out',
            ysno => 'You must select either "Yes" or "No" for immediate removal of unregistered students from the roster',
            eras => 'Click "OK" to erase all recipients, or "Cancel".',
            ynot => 'You have indicated that you want notification of roster changes messages to be sent, but you have not selected any recipients.',
            atle => 'You must check at least one checkbox, before proceeding to the next page',
            noed => 'You do not have rights to modify automated enrollment settings',
    );
    $js_lt{'both'} = &mt('You have selected "No" for both addition and removal of students[_1] in the institutional classlist but not in your LON-CAPA course.[_1]',"\n");
    $js_lt{'nnot'} = &mt('You have indicated that you do not want notification of roster changes messages to be sent, but [_1] have been checked as recipients.[_2]',"'+totalnote+'","\n");
    &js_escape(\%js_lt);

    my $scripttag = '
<script type="text/javascript" language="JavaScript">
// <![CDATA[
';
    if ((ref($permref) ne 'HASH') || (!$permref->{'edit'})) {
        $scripttag .= <<ENDJS;
function process(calling,numauto,nummanual,numlock,numunlock) {
    alert('$js_lt{'noed'}');
    return false;
}
ENDJS
    } else {
        $scripttag .= <<ENDJSONE;
function process(calling,numauto,nummanual,numlock,numunlock) {
 var checker = 1
 var rad1 = 0
 var rad2 = 0
 var formName = document.forms.enter
 if (calling == "viewclass") {
     formName = document.forms.studentform
 }
 formName.action.value = calling
 if (calling == 'chgsettings') {
   for (var j=0; j<formName.autoadds.length; j++) {
       if (formName.autoadds[j].checked) {
           rad1 = 1;
       }
   }
   for (var k=0; k<formName.autodrops.length; k++) {
       if (formName.autodrops[k].checked) {
           rad2 = 1;
       }
   }
   if (rad1 == 0) {
       alert('$js_lt{'adds'}');
       checker = 0
   }
   if (rad2 == 0) {
       alert('$js_lt{'drop'}');
       checker = 0
   }
 }
 if (calling == 'updatenow') {
     var enrolldis;
     var unenrolldis;
     for (var j=0; j<formName.updateadds.length; j++) {
         if (formName.updateadds[j].value == 0) {
             enrolldis = j;
         }
         if (formName.updateadds[j].checked) {
             rad1 = 1;
         }
     }
     for (var k=0; k<formName.updatedrops.length; k++) {
         if (formName.updatedrops[k].value == 0) {
             unenrolldis = k;
         }
         if (formName.updatedrops[k].checked) {
             rad2 = 1;
         }
     }
     if (rad1 == 0) {
         alert('$js_lt{'drop'}');
         checker = 0;
     }
     if (rad2 == 0) {
         alert('$js_lt{'ysno'}');
         checker = 0;
     }
     if (formName.updatedrops[unenrolldis].checked && formName.updateadds[enrolldis].checked ) {
         alert('$js_lt{'both'}$js_lt{'noup'}');
         checker = 0;
     }
 }
 if (calling == 'notify') {
     var totalnote = 0;
     for (var i=0; i<formName.elements.length; i++) {
	 var elementname = formName.elements[i].name;
	 var check_name = elementname.match($notify_check);
	 if (check_name != null) {
	     if (formName.elements[i].checked) {
		 totalnote ++;
	     }
	 } 
     }
     if (totalnote > 0) {
	 if (formName.notify[1].checked == true) {
	     if (confirm('$js_lt{'nnot'}$js_lt{'eras'}')) {
		 checker = 1;
	     } else {
		 checker = 0;
	     }
	 }
     } else {
	 if (formName.notify[0].checked == true) {
	     alert('$js_lt{'ynot'}');
	     checker = 0;
	 }
     }
 }
 if (calling == 'viewclass') {
     var totcheck = 0;
     var numchk = 0;
     if (numauto > 0) {
         numchk = countChecked(document.studentform.chgauto);
         totcheck = totcheck + numchk;
     }
     if (nummanual > 0) {
         numchk = countChecked(document.studentform.chgmanual);
         totcheck = totcheck + numchk;
     }
     if (numlock > 0) {
         numchk = countChecked(document.studentform.lockchg);
         totcheck = totcheck + numchk;
     }
     if (numunlock > 0) {
         numchk = countChecked(document.studentform.unlockchg);
         totcheck = totcheck + numchk;
     }
     if (totcheck > 0) {
        document.forms.studentform.state.value = "process";
     }
     if (totcheck == 0) {
        alert('$js_lt{'atle'}')
        checker = 0;
     }
 } 
 if (checker == 1) {  
     formName.submit();
 }
}
ENDJSONE
    }
    if ($action eq 'viewclass') {
        $scripttag .= &Apache::loncommon::check_uncheck_jscript();
        $scripttag .= <<ENDJSTWO;
function countChecked(field) {
    var count = 0;
    if (field.length > 0) {
        for (var i=0; i<field.length; i++) {
            if (field[i].checked == true) {
                count ++;
            }
        }
    } else {
        if (field.checked == true) {
            count ++;
        }
    }
    return count;
}

ENDJSTWO
    } elsif ($action eq 'chgfailsafe') {
        my %domconfig =
            &Apache::lonnet::get_dom('configuration',['autoenroll'],$dom);
        my $includedom = 1;
        if (ref($domconfig{'autoenroll'}) eq 'HASH') {
            if ($domconfig{'autoenroll'}->{'failsafe'} eq 'off') {
                $includedom = 0;
            }
        }
        $scripttag .= <<ENDJSTHREE;

function toggleFailsafe(form) {
    var radioname = 'autodropfailsafetype';
    var divid = 'autodropfailsafe';
    var num = form.elements[radioname].length;
    if (num) {
        var includedom = '$includedom';
        var setvis = '';
        for (var i=0; i<num; i++) {
            if (form.elements[radioname][i].checked) {
                if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any') || ((form.elements[radioname][i].value == 'dom') && (includedom == 1))) {
                    if (document.getElementById(divid)) {
                        document.getElementById(divid).style.display = 'inline-block';
                    }
                    setvis = 1;
                }
                break;
            }
        }
        if (!setvis) {
            if (document.getElementById(divid)) {
                document.getElementById(divid).style.display = 'none';
            }
        }
    }
    return;
}

ENDJSTHREE
        $additems = { 'onload' => "toggleFailsafe(document.enter);" };
    }
    $scripttag .= <<ENDJS;
// ]]>
</script>
ENDJS
    my $args = &make_crumbs($action,$permref,$additems);
    return &Apache::loncommon::start_page('Classlist Manager',
					  $scripttag,$args);
}

sub make_crumbs {
    my ($action,$permref,$additems) = @_;
    my ($tasklong,$tasktitle) = &get_task_text($permref);
    my $brcrum = [{href=>"/adm/createuser",
                   text=>"User Management",},
                 {href=>"/adm/populate",
                   text=>"Automated Enrollment",
                   help=>'Course_Automated_Enrollment'},
                 ];
    if ($action eq 'newcross') {
        $action = 'crosslist';
    } elsif ($action eq 'newsections') {
        $action = 'sections';
    }
    my $text;
    if (ref($tasklong) eq 'HASH') {
        $text = $tasklong->{$action};
    }
    unless ($action eq 'information') {
        push(@{$brcrum},
                 {href => "javascript:backPage(document.crtuser)",
                  text => $text}
            );
    }
    return {bread_crumbs           => $brcrum,
            bread_crumbs_component => 'Automated Management',
            add_entries => $additems};
}

sub print_navmenu {
    my ($r,$tasksref,$tasklongref,$action,$state) = @_;
#LC_pick_box is used in the following. This is only a temporary solution to adapt the site to the design.
    $r->print('
    <br />
    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="LC_pick_box">
    <tr class="LC_pick_box_row">
      <td valign="top" class="LC_pick_box_title">
');
    foreach my $task (@{$tasksref}) {
        if (($task eq $action) && ($state eq 'choose')) {
            $r->print(' 
   <p>
   <font color="#999999">
    <b>'.$tasklongref->{$task}.'</b><br/>
   </font>
   </p>'); 
        } else {
            $r->print('
   <p>
   <font color="#004263">
    <b><a href="/adm/populate?action='.$task.'">'.$tasklongref->{$task}.'</a></b><br/>
   </font> 
   </p>');

        }
    }
    $r->print('
  <p>&nbsp;</p>
  </td>
  <td valign="top" class="LC_pick_box_value">');
}

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

sub print_main_frame {
  my ($r,$realm,$dom,$crs,$tasktitleref,$permref) = @_;
  my $action = "information";
  if (exists($env{'form.action'}) ) {
      $action = $env{'form.action'};
  }
  my ($disabled,$readonly);
  unless ($permref->{'edit'}) {
      $disabled = ' disabled="disabled"';
      $readonly = 1;
  }

# Get course settings
  my %enrollvar;
  my %settings = &Apache::lonnet::dump('environment',$dom,$crs);
  foreach my $item (keys(%settings)) {
      if ($item =~ m/^internal\.(.+)$/) {
          $enrollvar{$1} = $settings{$item};
      } elsif ($item =~ /^default_enrollment_(start|end)_date$/) {
          $enrollvar{$item} = $settings{$item};
      }
  }

  if ($action eq 'information') {
      $r->print('
          <br /><table border="0" width="100%">
            <tr>
              <td>&nbsp;</td>
              <td><b>'.&mt('Use the menu on the left to choose an enrollment management task.').'</b><br /><br /></td>
            </tr>');
      if ($permref->{'edit'}) {
          $r->print(' 
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Automated adds/drops[_2] to enable or disable automatic nightly adds or drops in your LON-CAPA course based on institutional enrollment information.','<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Change enrollment dates[_2] to change the date of first automated enrollment and/or the date of last automated enrollment for registered students.','<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Change access dates[_2] to change the default start and/or end dates for student roles created by automated enrollment.','<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Notification of changes[_2] to enable or disable notification of enrollment changes and to add or remove course coordinators from the recipient list.','<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Change crosslisting[_2] to include or exclude enrollment from crosslisted classes.',
                        '<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Section settings[_2] to make changes to the choice of sections included for enrollment in your LON-CAPA course.',
                        '<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Student photo settings[_2] to enable or disable automatic import of photos for registered students in your course.',
                        '<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Update roster now[_2] to add and/or drop students from your course based on the [_3]most current[_4] institutional classlist information.','<i>"','"</i>','<b>','</b>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt("Use [_1]Update student photos[_2] to import your institution's [_3]most current[_4] digital photos for registered students in your course.",'<i>"','"</i>','<b>','</b>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]View students and change type[_2] to display the current course roster, and (optionally) change enrollment type for selected students from "auto" to "manual" and vice versa.','<i>"','"</i>').'</td>
            </tr>
            <tr>
             <td>&nbsp;</td>
             <td>'.&mt('Use [_1]View/change enrollment failsafe[_2] to (a) set number of drops from existing enrollments in an institutional section above which no automated drops will occur (e.g., when section enrollment retrieved from institutional data is incomplete) and (b) set whether this only applies when retrieved data contains zero records for the institutional section.','<i>"','"</i>').'</td>
            </tr>');
      } else {
          if (($permref->{'view'}) || ($permref->{'view_section'} ne '')) {
              $r->print('
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Automated adds/drops[_2] to display status of automatic nightly adds or drops based on institutional enrollment information.','<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Enrollment dates[_2] to display the date of first automated enrollment and last automated enrollment for registered students.','<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Access dates[_2] to display the default start and/or end dates for student roles created by automated enrollment.','<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Notification of changes[_2] to display which course coordinators (if any) receive notification of enrollment changes.','<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Crosslisting[_2] to display enrollment settings for crosslisted classes.',
                        '<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Section settings[_2] to display sections included for enrollment.',
                        '<i>"','"</i>').'</td>
            </tr>
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]Student photo settings[_2] to display settings for automatic import of photos for registered students.',
                        '<i>"','"</i>').'</td>
            </tr>
            <tr>
             <td>&nbsp;</td>
             <td>'.&mt('Use [_1]Enrollment failsafe[_2] to display (a) number of drops from existing enrollments in an institutional section above which no automated drops occur (e.g., when section enrollment retrieved from institutional data is incomplete), and (b) whether this only applies when retrieved data contains zero records for the institutional section.','<i>"','"</i>').'</td>
            </tr>');
          }
          if (($permref->{'show'}) || ($permref->{'show_section'} ne '')) {
              $r->print('
            <tr>
              <td>&nbsp;</td>
              <td>'.&mt('Use [_1]View students and enrollment type[_2] to display the current course roster and enrollment type ("auto" or "manual").','<i>"','"</i>').'</td>
            </tr>');
          }
          $r->print('
            <tr>
             <td colspan="2">&nbsp;</td>
            </tr>
            <tr>
             <td>&nbsp;</td>
             <td><b>'.&mt('Note: if automated adds and/or drops are enabled, the nightly enrollment update will ONLY occur once the first enrollment date has been reached.').'</b></td>
            </tr>
          </table>');
      }
  } elsif ($action eq 'chgsettings') {
      my @autosets = (&mt('OFF'),&mt('ON'));
      $r->print('
                  <form name="enter" method="post" action=""><br />
		  <table width="100%" border="0" cellpadding="2" cellspacing="2">
		   <tr>
		    <td align="left"><b>'.$$tasktitleref{$action}.'</b><br />
		       '.&mt('Currently: Nightly adds: [_1], Nightly drops: [_2]',"<i>$autosets[$enrollvar{autoadds}]</i>","<i>$autosets[$enrollvar{autodrops}]</i>").'
		    </td>
                   </tr>
		  </table>
		  <table width="100%" border="0" cellpadding="3" cellspacing="3">
		    <tr>
		     <td>
		        '.&mt('Additions based on classlist changes:').'&nbsp;&nbsp;');
      if ($enrollvar{autoadds}) {
          $r->print('
			    <label><input type="radio" name="autoadds" value="1" checked="checked"'.$disabled.' />&nbsp;'.
                            &mt('Enable').'&nbsp;&nbsp;&nbsp;</label>
			    <label><input type="radio" name="autoadds" value="0"'.$disabled.' />&nbsp;'.
                            &mt('Disable').'</label>');
      } else {
          $r->print('
                            <label><input type="radio" name="autoadds" value="1"'.$disabled.' />&nbsp;'.
                            &mt('Enable').'&nbsp;&nbsp;&nbsp;</label>
                            <label><input type="radio" name="autoadds" value="0" checked="checked"'.$disabled.' />&nbsp;'.
                            &mt('Disable').'</label>');
      }
      $r->print('
              </td>
             </tr>
             <tr>
              <td>
 	       '.&mt('Removals based on classlist changes:').'&nbsp;&nbsp;');
      if ($enrollvar{autodrops}) {
          $r->print('
                <label><input type="radio" name="autodrops" value="1" checked="checked"'.$disabled.' />&nbsp;'.
                &mt('Enable').'&nbsp;&nbsp;&nbsp;</label>
                <label><input type="radio" name="autodrops" value="0"'.$disabled.' />&nbsp;'.
                &mt('Disable').'</label>');
      } else {
          $r->print('
                <label><input type="radio" name="autodrops" value="1"'.$disabled.' />&nbsp;'.
                &mt('Enable').'&nbsp;&nbsp;&nbsp;</label>
                <label><input type="radio" name="autodrops" value="0" checked="checked"'.$disabled,' />&nbsp;'.
                &mt('Disable').'</label>');
      }
      $r->print('
              </td>
             </tr>
             <tr>
              <td>
               <span style="color: #888888">'.
&mt('Note: Any students added manually by course coordinators using the User Manager will be unaffected by the nightly removal process if you choose to enable it.').'
               </span>
              </td>
             </tr>
             <tr>
              <td align="right">
               <input type="button" name="chgsettings" value="'.&mt('Go').'" onclick="process('."'chgsettings'".')"'.$disabled.' />
	      </td>
             </tr>
	    </table>
            <input type="hidden" name="action" value="'.$action.'" />
            <input type="hidden" name="state" value="process" />
            </form>'."\n");
  } elsif ($action eq 'chgfailsafe') {
      my ($autofailsafe,$failsafetype,$failsafesty,%failsafechecked);
      $failsafesty = 'inline-block';
      %failsafechecked = (
          dom => ' checked="checked"',
      );
      my $domdefault;
      my %domconfig =
          &Apache::lonnet::get_dom('configuration',['autoenroll'],$dom);
      if (ref($domconfig{'autoenroll'}) eq 'HASH') {
          $autofailsafe = $domconfig{'autoenroll'}->{'autofailsafe'};
          if ($autofailsafe =~ /\D/) {
              undef($autofailsafe);
          }
          if ($domconfig{'autoenroll'}->{'failsafe'} eq 'off') {
              undef($autofailsafe);
              $failsafesty = 'none';
              $failsafetype = 'off';
              $domdefault = &mt('Failsafe is not in use.');
          } elsif ($domconfig{'autoenroll'}->{'failsafe'} eq 'any') {
              $failsafesty = 'inline-block';
              $failsafetype = 'any';
              $domdefault = &mt('Failsafe will apply if retrieved enrollment for institutional section is zero or greater.');
          } else {
              $failsafesty = 'inline-block';
              $failsafetype = 'zero';
              $domdefault = &mt('Failsafe will only apply if retrieved enrollment for institutional section is zero.');
          }
      }
      if ((exists($enrollvar{'autodropfailsafetype'})) &&
          ($enrollvar{'autodropfailsafetype'} ne '')) {
          if ($enrollvar{'autodropfailsafetype'} eq 'off') {
              $failsafesty = 'none';
              $failsafechecked{'dom'} = '';
              $failsafechecked{'off'} = ' checked="checked"';
          } elsif ($enrollvar{'autodropfailsafetype'} eq 'any') {
              $failsafesty = 'inline-block';
              $failsafechecked{'dom'} = '';
              $failsafechecked{'any'} = ' checked="checked"';
          } elsif ($enrollvar{'autodropfailsafetype'} eq 'zero') {
              $failsafesty = 'inline-block';
              $failsafechecked{'dom'} = '';
              $failsafechecked{'zero'} = ' checked="checked"';
          }
      }
      $r->print('
          <form name="enter" method="post" action=""><br />
           <table width="100%" border="0" cellpadding="2" cellspacing="2">
            <tr>
             <td align="left"><b>'.$$tasktitleref{$action}.'</b><br /><p>'.
             &mt('The "failsafe" mechanism for automated enrollment can prevent unwanted expiration of student roles for registered students in an institutional section, in the case where either no enrollment, or only partial enrollment, is returned for that particular section because of a temporary institutional data retrieval problem external to LON-CAPA.').'</p>'.
            '<p>'.&mt('For example if the threshold is set to 10, and the current LON-CAPA enrollment count is 11 or more for a particular course section, no role expiration will occur if the latest retrieved enrollment count is zero for that institutional section (or cross-listing).').'</p>');
      if ($enrollvar{'autodropfailsafe'} eq '') {
          $r->print('<p>'.&mt('Currently no course-specific failsafe threshold is set.').' ');
          if ($autofailsafe eq '') {
              $r->print(&mt('Currently no domain default failsafe is set either.'));
          } else {
              $r->print(&mt('The current domain default of [_1] will apply unless a value is set here specific to this course.','<b>'.$autofailsafe.'</b>'));
          }
          $r->print('</p>');
      } else {
          unless (($enrollvar{'autodropfailsafetype'} eq 'off') || 
                  (($enrollvar{'autodropfailsafetype'} eq '') && ($failsafetype eq 'off'))) {
              $r->print('<p>'.&mt('Currently, the course-specific failsafe is set to [_1].',"<i>$enrollvar{'autodropfailsafe'}</i>").'</p>');
          }
      }
      unless (($enrollvar{'autodropfailsafe'} eq '') && ($autofailsafe eq '')) {
          if ($enrollvar{'autodropfailsafetype'} eq '') {
              $r->print('<p>'.&mt('Currently no course-specific failsafe condition is set.').' ');
              if ($failsafetype eq 'any') {
                  $r->print(&mt('The current domain default, whereby the failsafe is in effect if the retrieved section enrollment is zero or greater, will apply unless overridden here for this specific course.'));
              } elsif ($failsafetype eq 'zero') {
                  $r->print(&mt('The current domain default, whereby the failsafe is only in effect if the retrieved section enrollment is zero, will apply unless overridden here for this specific course.'));
              } elsif ($failsafetype eq 'off') {
                  $r->print(&mt('The current domain default (failsafe not in use) will apply unless overridden here for this specific course.'));
              }
              $r->print('</p>');
          } else {
              if ($enrollvar{'autodropfailsafetype'} eq 'zero') {
                  $r->print('<p>'.&mt('Currently, the course-specific failsafe condition is set such that any failsafe threshold is only in effect when the retrieved institutional section enrollment is zero.'));
              } elsif ($enrollvar{'autodropfailsafetype'} eq 'any') {
                  $r->print('<p>'.&mt('Currently, the course-specific failsafe condition is set such that any failsafe threshold is in effect when the retrieved institutional section enrollment is zero (or greater).'));
              } elsif ($enrollvar{'autodropfailsafetype'} eq 'off') {
                  $r->print('<p>'.&mt('Currently, the course-specific failsafe condition is set such that a failsafe will not be used.'));
              }
              $r->print('</p>');
          }
      }
      $r->print('
             </td>
            </tr>
           </table>
           <table width="100%" border="0" cellpadding="3" cellspacing="3">
             <tr>
             <td><b>'.&mt('Condition for use of failsafe in this course').'</b><br />
             <span class="LC_nobreak"><label><input type="radio" name="autodropfailsafetype" value="dom" onclick="toggleFailsafe(this.form);"'.$failsafechecked{'dom'}.$disabled.' />'.&mt('Use domain default').'</label></span>&nbsp;--&nbsp;'.$domdefault.'<br />
             <span class="LC_nobreak"><label><input type="radio" name="autodropfailsafetype" value="zero" onclick="toggleFailsafe(this.form);"'.$failsafechecked{'zero'}.$disabled.' />'.&mt('Failsafe will apply if retrieved institutional section enrollment is zero.').'</label></span><br />
             <span class="LC_nobreak"><label><input type="radio" name="autodropfailsafetype" value="any" onclick="toggleFailsafe(this.form);"'.$failsafechecked{'any'}.$disabled.' />'.&mt('Failsafe will apply if retrieved institutional section enrollment is zero or greater.').'</label></span><br />
             <span class="LC_nobreak"><label><input type="radio" name="autodropfailsafetype" value="off" onclick="toggleFailsafe(this.form);"'.$failsafechecked{'off'}.$disabled.' />'.&mt('Failsafe will not be in use in this course.').'</label></span><br />
             <div class="LC_floatleft" style="display:'.$failsafesty.';" id="autodropfailsafe">
             <span class="LC_nobreak"><b>'.
             &mt('Failsafe threshold (enter an integer)').'</b>&nbsp;&nbsp;
             <input type="text" name="autodropfailsafe" value="'.$enrollvar{'autodropfailsafe'}.'" size="4"'.$disabled.' /></span><br />');
       if ($autofailsafe) {
           $r->print(&mt('Leave blank to use domain default of [_1].','<b>'.$autofailsafe.'</b>'));
       } else {
           $r->print(&mt('As no domain default is set, failsafe will not be used if blank.'));
       }
       $r->print('</div>
             </td>
            </tr>
            <tr>
              <td>&nbsp;</td>
            </tr>
            <tr>
              <td>'.&mt('Push "Go" to save your changes').'
            <tr>
              <td>&nbsp;</td>
            </tr>
            <tr>
             <td align="right">
              <input type="button" name="updatefailsafe" value="'.&mt('Go').'" onclick="'."process('chgfailsafe')".'"'.$disabled.' />
             </td>
            </tr>
           </table>
           <input type="hidden" name="action" value="'.$action.'" />
           <input type="hidden" name="state" value="process" />
           </form>'."\n");
  } elsif ($action eq 'setdates') {
      my ($start_table,$end_table) = &date_setting_table($enrollvar{autostart},$enrollvar{autoend},$action,$readonly);
      my $oldstartshow = '';
      my $oldendshow = '';
      if ( defined($enrollvar{autostart}) ) {
          $oldstartshow = &Apache::lonlocal::locallocaltime($enrollvar{autostart});
      }
      if ( defined($enrollvar{autoend}) ) {
          $oldendshow = &Apache::lonlocal::locallocaltime($enrollvar{autoend});
          if ($enrollvar{autoend} == 0) {
              $oldendshow = &mt("'No end date'");
          }
      }
      my $dateshow;
      if ( ($oldendshow eq '') && ($oldstartshow eq '') ) {
         $dateshow = '<br /><span class="LC_warning"><b>'.&mt('Warning.').'</b> '.&mt('Currently [_1]NO[_2] first enrollment or last enrollment dates are set.','<b>','</b>').' '.
                     &mt('You [_1]must[_2] use this menu to set a start date and an end date if you plan to utilise automated adds and/or drops in this course.','<b>','</b>')."</span>\n";
      } else {
         $dateshow = &mt('Currently: First enrollment[_1] Last enrollment[_2]',
                         " -- <b><i>$oldstartshow</i></b>"," -- <b><i>$oldendshow</i></b>")."\n";
      }
      $r->print('
                  <form name="enter" method="post" action=""><br />              
                  <table width="100%" border="0" cellpadding="2" cellspacing="2">
	           <tr>
	            <td align="left"><b>'.$$tasktitleref{$action}.'</b><br /><br />
                     '.$dateshow.'
	            </td>
                   </tr>
	          </table>
                  <table width="100%" border="0" cellpadding="3" cellspacing="3">
                   <tr>
                    <td align="left" colspan="2">
                     <table border="0" cellspacing="0" cellpadding="2">
                      <tr>
                       <td colspan="3">
                        <i>'.&mt('Set date of first automated enrollment for registered students').'</i>
                       </td>
                      </tr>
                      <tr>
                       <td>'.$start_table.'
                       </td>
                      </tr>
                     </table>
                    </td>
                   </tr>
                   <tr>
                    <td colspan="2"><span style="color: #888888">'.
                    &mt('If automated adds and/or drops are enabled, then your class roster will be automatically updated nightly, once the first enrollment date has been reached. Prior to this date, the class roster will only contain students you have added directly using the standard LON-CAPA enrollment tools.').'</span></td>
                   </tr>
                   <tr>
                    <td align="left" colspan="2">
                     <table border="0" cellspacing="0" cellpadding="2">
                      <tr>
                       <td colspan="3">
                        <i>'.&mt('Set date of last automated enrollment for registered students').'</i>
                       </td>
                      </tr>
                      <tr>
                       <td>'.$end_table.'
                       </td>
                      </tr>
                     </table>
                    </td>
                   </tr>
                   <tr>
                    <td colspan="2"><span style="color: #888888">'.&mt('If automated adds and/or drops are enabled, then your class roster will be automatically updated nightly, until the last enrollment date has been reached.').'</span></td>
                   </tr>
                  </table>
                  <table width="100%">
                   <tr>
                    <td align="right">
                      <input type="button" name="setdates" value="'.&mt('Go').'" onclick="process('."'setdates'".')"'.$disabled.' />
                    </td>
	           </tr>
                  </table>
                  <input type="hidden" name="action" value="'.$action.'" />
                  <input type="hidden" name="state" value="process" />
                  </form>
');
  } elsif ($action eq 'setaccess') {
      &print_accessdate_table($r,\%enrollvar,$tasktitleref,$action,$readonly);
      $r->print('
                  <table width="100%">
                   <tr>
                    <td align="right">
                      <input type="button" name="'.$action.'" value="'.&mt('Go').'" onclick="'."process('$action')".'"'.$disabled.' />
                    </td>
                   </tr>
                  </table>
                  <input type="hidden" name="action" value="'.$action.'" />
                  <input type="hidden" name="state" value="process" />
                  </form>
      ');
  } elsif ($action eq 'notify') {
      my $notifycount = 0;
      my @notified = split(/,/,$enrollvar{notifylist});
      my (@domcoord,@showdom,@olddomcoord,@futuredomcoord);
      for (my $i=0; $i<@notified; $i++) {
          if ($notified[$i] !~ /:/) {
              $notified[$i] =~ s/\@/:/;
          }
	  unless ($notified[$i] eq '') { $notifycount ++; } 
      }
      my $noteset = '';
      if ($notifycount) {
          $noteset = &mt('ON');
      } else {
          $noteset = &mt('OFF');
      }
      my $now = time;
      my %dompersonnel = &Apache::lonnet::get_domain_roles($dom,['dc']);
      foreach my $server (keys(%dompersonnel)) {
          foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
              my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
              my ($end,$start) = split(':',$dompersonnel{$server}{$user});
              if (($end eq '') || ($end == 0) || ($end > $now)) {
                  if ($start > $now) {
                      if (!grep(/^\Q$uname\E:\Q$udom\E$/,@futuredomcoord)) {
                          push(@futuredomcoord,$uname.':'.$udom);
                      }
                  } else {
                      if (!grep(/^\Q$uname\E:\Q$udom\E$/,@domcoord)) {
                          push(@domcoord,$uname.':'.$udom);
                      }
                  }
              } else {
                  if (!grep(/^\Q$uname\E:\Q$udom\E$/,@olddomcoord)) {
                      push(@olddomcoord,$uname.':'.$udom);
                  }
              }
          }
      }
      $r->print('
                  <form name="enter" method="post" action=""><br />
                   <table width="100%" border="0" cellpadding="6" cellspacing="0">
                    <tr>
                     <td align="left"><b>'.$tasktitleref->{$action}.'</b><br />'.
                      &mt('Currently -- Notification:').' '.$noteset.'
                     </td>
                    </tr>
                   </table>
                   <table width="100%" border="0" cellpadding="3" cellspacing="3">
                    <tr>
                     <td>'.
                     &mt('Notification of LON-CAPA course roster changes resulting from nightly automated enrollment process?')
      );
      if ($notifycount) {
          $r->print('
                        <label><input type="radio" name="notify" value="1" checked="checked"'.$disabled.' />&nbsp;'.&mt('Yes').'&nbsp;&nbsp;&nbsp;</label>
                        <label><input type="radio" name="notify" value="0"'.$disabled.' />&nbsp;'.&mt('No').'</label>
          ');
      } else {
          $r->print('
                        <label><input type="radio" name="notify" value="1"'.$disabled.' />&nbsp;'.&mt('Yes').'&nbsp;&nbsp;&nbsp;</label>
                        <label><input type="radio" name="notify" value="0" checked="checked"'.$disabled.' />&nbsp;'.&mt('No').'</label>
          ');
      }
      $r->print('
              </td>
             </tr>
      ');
      my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$dom,$crs);
      my @ccs;
      my %pname;
      my %notifystate;
      my %status;
      foreach my $person (sort(keys(%coursepersonnel))) {
          my $match = 0;
          my ($role,$user,$usec) = ($person =~ /^([^:]+):([^:]+:[^:]+):([^:]*)/);
          $user =~ s/:$//;
          my ($end,$start) = split(/:/,$coursepersonnel{$person});
          if ($end == -1 || $start == -1) {
              next;
          }
          if ($role eq 'cc')  {
              unless (grep(/^$user$/,@ccs)) {
                  if ($end && $end < $now) {
                      $status{$user} = 'previous';
                  } elsif ($start > $now) {
                      $status{$user} = 'future';
                  } else {
                      $status{$user} = 'active';
                  }
                  push(@ccs,$user);
                  my ($uname,$udom) = split(/:/,$user);
                  $pname{$user} = 
                           &Apache::loncommon::plainname($uname,$udom);
                  if (grep(/^$user$/,@notified)) {
                      $notifystate{$user} = 1;
                  } else {
                      $notifystate{$user} = 0;
                  }
              }
          }
      }
      my $notifyshow = 0; 
      my %lt = &Apache::lonlocal::texthash(
                                  name => 'Name',
                                  usnm => 'username:domain',
                                  coac => 'Course Access',
                                  curn => 'Current notification status',
                                  doms => 'Domain Coordinator status',
                                  notf => 'Notification?',
                                  ntac => 'Notification active',
                                  ntin => 'Notification inactive',
      );
      if (@ccs > 0) {
          @ccs = sort @ccs;
          $r->print('
             <tr>
               <td>'.&mt('The table below contains a list of [_1]s in this course.',&Apache::lonnet::plaintext('cc')).'
              </td>
             </tr>
             <tr>
              <td>
          ');
          $r->print(&notifier_tables('cc',\%lt,\@ccs,\%status,\%notifystate,
                                     \%pname,\$notifyshow,undef,undef,$disabled));
          $r->print('</td></tr>');
      } else {
          $r->print('
             <tr>
              <td>'.
             &mt('No [_1]s found.',
                 &Apache::lonnet::plaintext('cc')).'
            </td>
           </tr>
          ');
      }
      my $viewer = $env{'user.name'}.':'.$env{'user.domain'};
      my $showalldc = 0;
      if (grep(/^\Q$viewer\E$/,@domcoord)) {
          $showalldc = 1;
      }
      foreach my $dc (@domcoord,@futuredomcoord) {
          if (!grep(/^\Q$dc\E$/,@ccs)) {
              if (grep(/^\Q$dc\E$/,@notified)) {
                  $notifystate{$dc} = 1;
              } else {
                  $notifystate{$dc} = 0;
                  if (!$showalldc) {
                      next;
                  }
              }
              my ($dcuname,$dcdom) = split(/:/,$dc);
              $pname{$dc} =  &Apache::loncommon::plainname($dcuname,$dcdom);
              push(@showdom,$dc);
          }
      }
      foreach my $olddc (@olddomcoord) {
          if (grep(/^\Q$olddc\E$/,@notified)) {
              if (!grep(/^\Q$olddc\E$/,@ccs)) {
                  $notifystate{$olddc} = 1;
                  my ($dcname,$dcdom) = split(/:/,$olddc);
                  $pname{$olddc} =  &Apache::loncommon::plainname($dcname,$dcdom);
                  push(@showdom,$olddc);
              }
          }
      }
      my $showdomnum = scalar(@showdom);
      if ($showdomnum) {
          $r->print('
             <tr>
              <td>&nbsp;</td>
             </tr><tr>
              <td>');
          if ($showalldc) {
              $r->print(&mt("The table below contains a list of [_1]s from this course's domain who are not also [_2]s.",&Apache::lonnet::plaintext('dc'),&Apache::lonnet::plaintext('cc')));
          } else {
              $r->print(&mt("The table below contains a list of [_1]s from this course's domain who currently receive notification, and are not also [_2]s.",&Apache::lonnet::plaintext('dc'),&Apache::lonnet::plaintext('cc')));
          }
          $r->print('
              </td>
             </tr>
             <tr>
              <td>');
          $r->print(&notifier_tables('dc',\%lt,\@showdom,\%status,\%notifystate,\%pname,
                                     \$notifyshow,\@olddomcoord,\@futuredomcoord,$disabled));
          $r->print('
             </td>
          </tr>');
      }
      if (@ccs > 0 || @showdom > 0) {
          $r->print('<tr><td>&nbsp;</td></tr><tr><td>');
          if ($notifycount) {
              $r->print(&mt('Uncheck the checkbox(es) to terminate notification for people currently informed of roster changes from the nightly enrollment update.').'<br />');
         }
         if ((@ccs + @showdom) > $notifycount) {
             $r->print(&mt('Check the checkbox(es) to initiate notification for people not currently informed of roster changes from the nightly enrollment update.').'<br />');
         }
         $r->print(&mt("Click 'Go' to save your changes.").'
           <br />
           <table width="100%" border="0" cellpadding="2" cellspacing="2">
            <tr>
             <td align="right">
              <input type="button" name="notifyset" value="'.&mt('Go').'" onclick="'."process('notify')".'"'.$disabled.' />
             </td>
            </tr>
           </table>
          </td>
         </tr>
      ');
      }
      $r->print('
      </table>
      <input type="hidden" name="notifyshow" value="'.$notifyshow.'" />
      <input type="hidden" name="action" value="'.$action.'" />
      <input type="hidden" name="state" value="process" />
      </form>
      ');
  } elsif ($action eq "crosslist") {
      my @xlists;
      if ($enrollvar{crosslistings} ne '') {
	  @xlists = split(/,/,$enrollvar{crosslistings});
      }
      my $cross_str = @xlists;
      $r->print('
            <form name="enter" method="post" action=""><br />
            <table width="100%" border="0" cellpadding="2" cellspacing="2">
             <tr>
              <td align="left"><b>'.$tasktitleref->{$action}.'</b><br />
      ');
      if ($cross_str > 0) {
          $r->print(
              &mt('Currently, this LON-CAPA course is crosslisted with [quant,_1,course section,course sections].',$cross_str).' '.
              &mt('Students enrolling in these course sections will be automatically added to the class roster for the course, if you have chosen to enable a nightly automated enrollment update.').' '.
              &mt('For each crosslisting, leave the checkbox checked if you want registered students in that course to be included in the student roster for LON-CAPA course: [_1]; otherwise uncheck it.',"<b>$realm ($enrollvar{coursecode})</b>").' '.
              &mt('If you wish to change the section ID assigned in your LON-CAPA course for a crosslisted course, enter the new section ID in the appropriate textbox.').' '.
              &mt('The LON-CAPA section ID can be left (or set to) empty, if you do not wish to tie a section ID to this crosslisting.').' '.
              &mt('If you wish to add new crosslisted courses, enter the number of new courses to add in the textbox at the bottom of the page.').' '.
              &mt('You will provide information about each of the new crosslistings on a subsequent page.').' '.
              &mt("Click 'Go' to save your changes.").'
              </td>
             </tr>
            </table>
            <br />
          ');
          $r->print(&Apache::loncommon::start_data_table());
          $r->print(&Apache::loncommon::start_data_table_row());
          $r->print('
                 <th>'.&mt('Enrollment?').'</th>
                 <th>'.&mt('Crosslisted course').'</th>
                 <th>'.&mt('LON-CAPA section ID').'</th>
          ');
          $r->print(&Apache::loncommon::end_data_table_row());
          my @showable;
          &reformat_xlists($dom,$crs,$enrollvar{'coursecode'},\@xlists,\@showable);
          for (my $i=0; $i<@showable; $i++) {
              my $xl = '&nbsp;';
              my $lc_sec = '&nbsp;';
              if ($showable[$i] =~ /^([^:]+):?(.*)$/) {
                  $xl = $1;
                  $lc_sec = $2;
              }               
              $r->print(&Apache::loncommon::start_data_table_row());
              $r->print('
                 <td><input type="checkbox" name="cross_'.$i.'" checked="checked"'.$disabled.' /></td>
                 <td>'.$xl.'</td>
                 <td><input type="text" size="10" name="lcsec_'.$i.'" value="'.$lc_sec.'"'.$disabled.' /></td>
              ');
              $r->print(&Apache::loncommon::end_data_table_row());
          }
          $r->print(&Apache::loncommon::end_data_table());
      }
      else {
          $r->print(
                &mt('Currently no crosslisted courses are recorded for [_1].',$enrollvar{coursecode}).'
              </td>
             </tr>
            </table>
          ');
      }
      $r->print('   
            <br />
            <table width="100%" border="0" cellpadding="3" cellspacing="3">
             <tr>
              <td align="left">
               <b>'.&mt('Add new crosslistings.').'</b><br />'.
               &mt('Number of new crosslistings to add:[_1]','&nbsp;&nbsp;<input type="text" size="2" name="numcross" value="0"'.$disabled.' />').'
              </td>
             </tr>
            </table>
            <br />
            <table width="100%" border="0" cellpadding="2" cellspacing="2">
             <tr>
              <td align="right">
               <input type="button" name="crosslist" value="',&mt('Go').'" onclick="'."process('crosslist')".'"'.$disabled.' />
              </td>
             </tr>
            </table>
            <input type="hidden" name="action" value="$action" />
            <input type="hidden" name="state" value="process" />
            </form> 
      ');
  } elsif ($action eq 'sections') {
      my @sections = ();
      @sections = &Apache::lonnet::auto_get_sections($crs,$dom,$enrollvar{coursecode});
      my @storedsections = split(/,/,$enrollvar{sectionnums});
      my @currsections = ();
      my %sec_id = ();
      foreach (@storedsections) {
          if ($_ =~ m/^(\w+):(\w*)$/) {
              push(@currsections,$1);
              $sec_id{$1} = $2;
          }
      }
      if (@sections > 0) {
          my $secshow = @sections;
          $r->print('
            <form name="enter" method="post" action=""><br />
            <table width="100%" border="0" cellpadding="3" cellspacing="3">
             <tr>
              <td align="left">
               <b>'.$tasktitleref->{$action}.'</b><br />'.
               &mt("Your institution's course catalog includes [quant,_1,section] for course code: [_2].",$secshow,$enrollvar{coursecode}).'
              </td>
             </tr>
             <tr>
              <td>'.&mt('For each section, check the checkbox if you want registered students in that section to be included in the student roster for LON-CAPA course: [_1]; otherwise uncheck it.',"<b>$realm ($enrollvar{coursecode})</b>").' '.
                   &mt('If you want to change the section ID designation used for this section in LON-CAPA, delete the current value in the LON-CAPA section ID textbox and enter the new value.').' '.
                   &mt('The LON-CAPA section ID can be left (or set to) empty, if you do not wish to tie a section ID to this section.').' '.
                   &mt("To add a new section, check the 'Enrollment in this course?' checkbox, and enter the desired LON-CAPA section ID in the appropriate textbox.").' '.
                   &mt("Click 'Go' to save your changes.").'</td>
             </tr>
            </table>
            <br />
          ');
          $r->print(&Apache::loncommon::start_data_table());
          $r->print(&Apache::loncommon::start_data_table_row());
          $r->print('
              <th>'.&mt('Enrollment').'</th>
              <th>'.&mt('Institutional Section').'</th>
              <th>'.&mt('LON-CAPA section ID').'</th>
          ');
          $r->print(&Apache::loncommon::end_data_table_row());
          for (my $i=0; $i<@sections; $i++) {
              my $checked;
              if (grep/^\Q$sections[$i]\E$/,@currsections) {
                  $checked = ' checked="checked"';
              }
              $r->print(&Apache::loncommon::start_data_table_row().'
                  <td><input type="checkbox" name="sec_'.$i.'"'.$checked.$disabled.' /></td>
                  <td>'.$sections[$i].'<input type="hidden" name="secnum_'.$i.'" value="'.$sections[$i].'" /></td>
                  <td><input type="text" size="10" name="loncapasec_'.$i.'" value="'.$sec_id{$sections[$i]}.'"'.$disabled.' /></td>'.
                  &Apache::loncommon::end_data_table_row());
          }
          $r->print(&Apache::loncommon::end_data_table());
          $r->print('
            <br />
            <table width="100%" border="0" cellspacing="3" cellpadding="3">
             <tr> 
              <td align="right">
               <input type="hidden" name="secshow" value="'.$secshow.'" />
               <input type="button" name="sections" value="'.&mt('Go').'" onclick="'."process('sections')".'"'.$disabled.' />
              </td>
             </tr>
            </table>
            <input type="hidden" name="action" value="'.$action.'" />
            <input type="hidden" name="state" value="process" />
            </form>
          ');
      } else {
          $r->print('
            <form name="enter" method="post" action=""><br />
            <table width="100%" border="0" cellpadding="2" cellspacing="2">
             <tr>
              <td align="left"><b>'.$tasktitleref->{$action}.'</b><br />
          ');
          if (@currsections) {
              my $secshow = @currsections;
              $r->print(
                  &mt('Currently, this LON-CAPA course incorporates enrollment from [quant,_1,section].',$secshow).' '.
                  &mt('Students enrolling in any of these course sections will be automatically added to the class roster for the course, if you have chosen to enable a nightly automated enrollment update.').' '.
                  &mt('For each section, uncheck the checkbox if you want registered students in that section to cease being included in the student roster for LON-CAPA course: [_1]; otherwise leave it checked.',"<b>$realm ($enrollvar{coursecode})</b>").' '.
                  &mt('If you want to change the section ID designation used for this section in LON-CAPA, delete the current value in the LON-CAPA section ID textbox and enter the new value.').' '.
                  &mt('If you wish to add new course section, enter the number of new sections to add in the textbox at the bottom of the page.').' '.
                  &mt('You will provide information about each of the new sections on a subsequent page.').' '.
                  &mt("Click 'Go' to save your changes.").'
              </td>
             </tr>
            </table>
            <br />
              ');
              $r->print(&Apache::loncommon::start_data_table().
                        &Apache::loncommon::start_data_table_row().'
                 <th>'.&mt('Enrollment?').'</th>
                 <th>'.&mt('Section').'</th>
                 <th>'.&mt('LON-CAPA section ID').'</th>
              ');
              $r->print(&Apache::loncommon::end_data_table_row());
              for (my $j=0; $j<@currsections; $j++) {
                  $r->print(
                 &Apache::loncommon::start_data_table_row().
                 '<td><input type="checkbox" name="sec_'.$j.'" checked="checked"'.$disabled.' /></td>
                 <td>'.$currsections[$j].'</td>
                 <td><input type="text" name="lcsec_'.$j.'" size="10" value="'.$sec_id{$currsections[$j]}.'"'.$disabled.' /></td>
                 '.&Apache::loncommon::end_data_table_row());
              }
              $r->print(&Apache::loncommon::end_data_table());
          } else {
              $r->print(
                  &mt('Currently no sections of [_1] are contributing enrollment to the LON-CAPA class roster.',"$realm ($enrollvar{coursecode})").'
              </td>
             </tr>
            </table>
              ');
          }
          $r->print('
            <br />
            <table width="100%" border="0" cellpadding="3" cellspacing="3">
             <tr>
              <td align="left">
               <b>'.&mt('Add enrollment from additional sections.').'</b><br />'.
               &mt('Number of new sections to add:').'&nbsp;&nbsp;<input type="text" size="2" name="numsec" value="0"'.$disabled.' />
              </td>
             </tr>
            </table>
            <br />
            <table width="100%" border="0" cellpadding="2" cellspacing="2">
             <tr>
              <td align="right">
               <input type="button" name="sections" value="'.&mt('Go').'" onclick="'."process('sections')".'"'.$disabled.' />
              </td>
             </tr>
            </table>
            <input type="hidden" name="action" value="'.$action.'" />
            <input type="hidden" name="state" value="process" />
            </form> 
          ');
      }
  } elsif ($action eq 'photos') {
      my @photosets = (&mt('OFF'),&mt('ON'));
      $r->print('
                  <form name="enter" method="post" action=""><br />
                  <table width="100%" border="0" cellpadding="2" cellspacing="2">
                   <tr>
                    <td align="left"><b>'.$tasktitleref->{$action}.'</b><br />'.
                       &mt('Currently -- Student photo import:').' <i>'.$photosets[$enrollvar{showphoto}].'</i>
                    </td>
                   </tr>
                  </table>
                  <table width="100%" border="0" cellpadding="3" cellspacing="3">
                    <tr>
                     <td>
                         '.&mt('Automatic import of student photos from institutional data repository:').'&nbsp;&nbsp;');
      if ($enrollvar{showphoto}) {
          $r->print('
                        <label><input type="radio" name="showphotos" value="1" checked="checked"'.$disabled.' />&nbsp;'.&mt('Yes').'&nbsp;&nbsp;&nbsp;</label>
                        <label><input type="radio" name="showphotos" value="0"'.$disabled.' />&nbsp;'.&mt('No').'</label>
          ');
      } else {
          $r->print('
                        <label><input type="radio" name="showphotos" value="1"'.$disabled.' />&nbsp;'.&mt('Yes').'&nbsp;&nbsp;&nbsp;</label>
                        <label><input type="radio" name="showphotos" value="0" checked="checked"'.$disabled.' />&nbsp;'.&mt('No').'</label>
          ');
      }
      $r->print('
                     </td>
                    </tr>
      ');
      my ($result,$perm_reqd)=&Apache::lonnet::auto_photo_permission($crs,$dom);
      my $can_enable = 1;
      my $institution = &Apache::lonnet::domain($dom,'description');
      if ($result eq 'ok') {
          if ($perm_reqd eq 'yes') {
              if (!($enrollvar{'photopermission'} eq 'yes')) {
                  $can_enable = 0;
              } else {
                  if (&user_is_courseowner($enrollvar{'courseowner'})) {
                      $r->print('
                    <tr>
                     <td>'.
&mt('Previously the owner of this course agreed to the conditions of use of digital student photos required by [_1].', $institution).'<br />'.
&mt('As a result [_1]s can choose to automatically import student photos into this course.',&Apache::lonnet::plaintext('cc')).
'<br /><span class="LC_nobreak"><label>'.
&mt('[_1]Cancel[_2] owner acceptance of these conditions of use?','<b>','</b>').'&nbsp;<input type="checkbox" name="cancel_agreement" value="1"'.$disabled.' /></label></span>
                     </td>
                    </tr>
                      ');
                  }
              }
          }
      } else {
          $r->print('
                    <tr>
                     <td>'.
&mt('There was a problem determining whether course owner permission is required in order for a course coordinator to have access to student photos in this domain.').' '.
&mt('As a result you will not be able to configure access to student photos at this time').
'<br /><br /><input type="button" name="mainmenu" value="'.&mt('Go back').'" onclick="javascript:history.go(-1);" />
                    </td>
                   </tr>
                  </form>
          ');
          return;
      }
      if ($can_enable) {
          $r->print('
                    <tr>
                     <td>
                      <span style="color: #888888">'.
&mt('Note: if you enable automatic import of student photos, your course will automatically have access to photos saved by your institution for officially registered students, via a conduit established by your LON-CAPA domain coordinator.').'
                      </span>
                     </td>
                    </tr>
          ');
      } else {
          if (&user_is_courseowner($enrollvar{'courseowner'})) {
              $r->print('
                    <tr>
                     <td>'.
&mt('[_1] requires a course owner to indicate acceptance of conditions of use of digital student photos before enabling automatic import into a course.',$institution).' '.
&mt('If you choose to enable import of photos you will be prompted for your agreement on the next page.').'
                     </td>
                    </tr>
              ');
          } else {
              my ($ownername,$owneremail) = &get_ownerinfo($dom,
                                                    $enrollvar{'courseowner'});
              my $emailstr;
              if ($owneremail) {
                  $emailstr = "(e-mail: $owneremail)";
              }
              $r->print('
                    <tr>
                     <td>'
                      .&mt('The policies of your institution ([_1]) require that the course owner ([_2]) must indicate acceptance of the conditions of use of digital photos of registered students, before they may be made available for use in a course.',$institution,$ownername)
                      .'<br /><br />'
                      .&mt('Please direct the course owner [_1] to visit the "Student photos" page in the Automated Enrollment Manager to indicate acceptance of these conditions of use.',$emailstr)
                      .'<br /><br /><input type="button" name="mainmenu" value="'.&mt('Go back').'" onclick="javascript:history.go(-1);" />
                    </td>
                   </tr>
                  </form>
             ');
             return;
          }
      }
      $r->print('
                    <tr>
                     <td>&nbsp;</td>
                    </tr>
                    <tr>
                     <td align="right">
                      <input type="button" name="showphotos" value="'.&mt('Go').'" onclick="process('."'photos'".')"'.$disabled.' />
                     </td>
                    </tr>
                   </table>
                   <input type="hidden" name="action" value="'.$action.'" />
                   <input type="hidden" name="state" value="process" />
                   </form>
      ');
  } elsif ($action eq "updatenow") {
      $r->print('
                   <form name="enter" method="post" action=""><br />
		   <table width="100%" border="0" cellpadding="2" cellspacing="2">
		    <tr>
		     <td align="left"><b>'.$tasktitleref->{$action}.'</b>
		     </td>
                    </tr>
		   </table>
		   <table width="100%" border="0" cellpadding="3" cellspacing="3">
		    <tr>
		     <td>'.
	             &mt('Add any students currently included in institutional classlist(s) but not enrolled in your LON-CAPA course.').'<br />  
		      <label><input type="radio" name="updateadds" value="1"'.$disabled.' />&nbsp;'.&mt('Yes').'&nbsp;</label>
                      <label><input type="radio" name="updateadds" value="0"'.$disabled.' />&nbsp;'.&mt('No').'&nbsp;</label>
                     </td>
                    </tr>
                    <tr>
                     <td>'.
 	             &mt('Expire students previously added by nightly enrollment process, but no longer listed in institutional classlist(s).').'<br />
                      <label><input type="radio" name="updatedrops" value="1"'.$disabled.' />&nbsp;'.&mt('Yes').'&nbsp;</label>
                      <label><input type="radio" name="updatedrops" value="0"'.$disabled.' />&nbsp;'.&mt('No').'&nbsp;</label><br />
                     </td>
                    </tr>
                    <tr>
                     <td><span style="color: #888888;">'.
&mt("Note: Any students previously added manually by course coordinator(s) using either 'Upload classlist CSV file' or 'Enroll a single user' will be unaffected by the removal process.").'
                      </span>
                     </td>
                    </tr>
                    <tr>
                     <td>
      ');
      &print_accessdate_table($r,\%enrollvar,$tasktitleref,$action,$readonly);
      $r->print('
                     </td>
                    </tr>
                    <tr>
                     <td align="right">
                      <input type="button" name="updatenow" value="'.&mt('Go').'" onclick="'."process('updatenow')".'"'.$disabled.' />
                     </td>
                    </tr>
	           </table>
                   <input type="hidden" name="action" value="'.$action.'" />
                   <input type="hidden" name="state" value="process" />
                  </form>
      ');
  } elsif ($action eq 'updatephotos') {
      $r->print('
                   <table width="100%" border="0" cellpadding="2" cellspacing="2">
                    <tr>
                     <td align="left"><b>'.$tasktitleref->{$action}.'</b>
                     </td>
                    </tr><tr><td>');
      if ($enrollvar{'showphoto'}) {
          my ($update,$commentary) = &Apache::lonnet::auto_photochoice($crs,
								       $dom);
          if ($update) { 
              $r->print('<br />'.$commentary.'<br /><br />
<form name="photoupdate" method="post" action="">
<input type="button" name="retrieve" value="'.&mt('Update photo repository').'"
onclick="javascript:document.photoupdate.submit()"'.$disabled.' />
<input type="hidden" name="action" value="'.$action.'" />
<input type="hidden" name="state" value="process" />
</form>');
          } else {
              $r->print(&mt('Update of photos via the Automated Enrollment Manager is unavailable in this domain.')
                       .'<br /><br /><input type="button" name="mainmenu" value="'.&mt('Go back').'" onclick="javascript:history.go(-1);" />');
          }
      } else {
          $r->print(&mt('Update of photos is unavailable, as import of student photos is currently disabled.').'<br />'.
                    &mt('Enable this first via: [_1]','<a href="/adm/populate?action=photos">'.$tasktitleref->{'photos'}.'</a>'));
      }
      $r->print('</td></tr>
                 <tr><td>&nbsp;</td></tr>
                </table>');
  } elsif ($action eq 'viewclass') {
      $r->print('
                   <form name="studentform" method="post" action=""><br />
                   <table width="100%" border="0" cellpadding="2" cellspacing="2">
                    <tr>
                     <td align="left"><b>'.$tasktitleref->{$action}.'</b>
                     </td>
                    </tr>
                    <tr>
                     <td>'.
                &mt('Section changes, name changes, and class drops that can be set to occur either automatically or when using the [_1]Update roster now[_2] feature, will affect only those students with an enroll type of [_1]auto[_2].',"'<b>","'</b>").' '.
                &mt("Students with an enroll type of [_1]manual[_2], will be converted automatically to the 'auto' type, when they first appear in the institutional classlist for the course - as long as nightly adds are enabled and active, or the update roster utility is used.","'<b>","'</b>").' '.
                &mt("Use the 'Lock' checkbox for any manually enrolled students for whom you wish to prevent type conversion.").' '.
                &mt("Use the 'Change' checkbox to switch the enroll type from auto to manual, and vice versa.").' '.
                &mt("Use the 'Unlock' checkbox for any maually enrolled students for whom you no longer wish to lock the enroll type.").' '.
                &mt("Click the 'Go' button at the end of the page to process your desired changes.").'</td>
                    </tr>
                    <tr><td>&nbsp;</td></tr> 
                   </table>
                   <table>
                    <tr>
                     <td>
      ');
      if (! exists($env{'form.sortby'})) {
          $env{'form.sortby'} = 'username';
      }
      if ($env{'form.Status'} !~ /^(Any|Expired|Active|Future)$/) {
          $env{'form.Status'} = 'Active';
      }
      my $status_select = &Apache::lonhtmlcommon::StatusOptions($env{'form.Status'});
#  Get current classlist
      my %userlist;
      my ($indexhash,$keylist) = &Apache::lonuserutils::make_keylist_array();
      my $classlist = &Apache::loncoursedata::get_classlist();
      my $secidx = &Apache::loncoursedata::CL_SECTION();
      my $crstype =&Apache::loncommon::course_type();
      my ($permission,$allowed) = &Apache::lonuserutils::get_permission('course',$crstype);
      foreach my $student (keys(%{$classlist})) {
          if (exists($permission->{'view_section'})) {
              if ($classlist->{$student}[$secidx] ne $permission->{'view_section'}) {
                  next;
              } else {
                  $userlist{$student} = $classlist->{$student};
              }
          } else {
              $userlist{$student} = $classlist->{$student};
          }
      }

      if (! defined($classlist)) {
          $r->print(&mt('There are no students either currently or previously enrolled.').'
                      </td>
                     </tr>'."\n");
      } else {
          $r->print(&mt('Student Status: [_1]',$status_select)."\n");
          $r->print('<input type="submit" value="'.&mt('Update Display').'" />'.
              "\n");
          my $context = 'course';
          my $mode = 'autoenroll';
          my ($studentcount,$autocount,$manualcount,$lockcount,$unlockcount) = 
              &Apache::lonuserutils::show_users_list($r,$context,$mode,$permission,$env{'form.Status'},\%userlist,$keylist);
          $r->print('
                     </td>
                    </tr>
          ');
          if ($studentcount > 0) {
              $r->print('
                    <tr><td><table border="0" cellpadding="5"><tr>
              ');
              my $cellcount = 0;
              if ($autocount > 0) {
                  $cellcount ++;
                  $r->print('
                      <td><fieldset><legend>'.&mt('Change auto').'</legend><input type="button" value="'.&mt('check all').'" onclick="javascript:checkAll(document.studentform.chgauto)"'.$disabled.' />&nbsp;&nbsp;
                      <input type="button" value="'.&mt('uncheck all').'" onclick="javascript:uncheckAll(document.studentform.chgauto)"'.$disabled.' /></fieldset></td>
                  ');
              }
              if ($manualcount > 0) {
                  $cellcount ++;
                  $r->print('
                      <td><fieldset><legend>'.&mt('Change manual').'</legend><input type="button" value="'.&mt('check all').'" onclick="javascript:checkAll(document.studentform.chgmanual)"'.$disabled.' />&nbsp;&nbsp;
                      <input type="button" value="'.&mt('uncheck all').'" onclick="javascript:uncheckAll(document.studentform.chgmanual)"'.$disabled.' /></fieldset></td>
                  ');
              }
              if ($lockcount > 0) {
                  if ($cellcount == 2) {
                      $r->print('</tr><tr>');
                  }
                  $cellcount ++;
                  $r->print('
                       <td><fieldset><legend>'.&mt('Lock manual').'</legend><input type="button" value="'.&mt('check all').'" onclick="javascript:checkAll(document.studentform.lockchg)"'.$disabled.' />&nbsp;&nbsp;
                       <input type="button" value="'.&mt('uncheck all').'" onclick="javascript:uncheckAll(document.studentform.lockchg)"'.$disabled.' /></fieldset></td>
                  ');
              }
              if ($unlockcount > 0) {
                  if ($cellcount == 2) {
                      $r->print('</tr><tr>');
                  }
                  $cellcount ++;
                  $r->print('
                       <td><fieldset><legend>'.&mt('Unlock manual').'
                       </legend><input type="button" value="'.&mt('check all').'" onclick="javascript:checkAll(document.studentform.unlockchg)"'.$disabled.' />&nbsp;&nbsp;
                       <input type="button" value="'.&mt('uncheck all').'" onclick="javascript:uncheckAll(document.studentform.unlockchg)"'.$disabled.' /></fieldset></td>');
              }
              $r->print('
                       </tr>
                      </table>
                     <td>&nbsp;</td>
                    </tr>
                    <tr>
                     <td align="right">
                      <input type="button" name="viewclass" value="'.&mt('Go').'" onclick="'."process('viewclass','$autocount','$manualcount','$lockcount','$unlockcount')".'"'.$disabled.' />
                     </td>
                    </tr>
              ');
          } else {
              $r->print('
                    <tr>
                     <td><br />
                      '.&mt('There are no students with the selected status.').'
                     </td>
                    </tr>
              ');
          }
          $r->print('
                   </table>
                   <input type="hidden" name="action" value="'.$action.'" />
                   <input type="hidden" name="state" value="choose" />
                  </form>
          ');
      }
  }
}

sub notifier_tables {
    my ($role,$lt,$users,$status,$notifystate,$pname,$notifyshow,$olddomcoord,
        $futuredomcoord,$disabled) = @_;
    my $output = &Apache::loncommon::start_data_table();
    $output .= &Apache::loncommon::start_data_table_header_row();
    $output .= "<th>$$lt{name}</th>
                <th>$$lt{usnm}</th>";
    if ($role eq 'dc') {
        $output .= "<th>$$lt{doms}</th>";
    } elsif ($role eq 'cc') {
        $output .= "<th>$$lt{coac}</th>";
    } 
    $output .=  "<th>$$lt{curn}</th>
                 <th>$$lt{notf}</th>";
    $output .= &Apache::loncommon::end_data_table_header_row();
    for (my $i=0; $i<@{$users}; $i++) {
        $output .= &Apache::loncommon::start_data_table_row();
        $output .= '<td>'.$$pname{$$users[$i]}.'</td>'.
                   '<td><input type="hidden" name="notifyname_'.$$notifyshow.
                   '" value="'.$$users[$i].'" />'.$$users[$i].'</td>';
        if ($role eq 'dc') {
            $output .= '<td>';
            if ((ref($olddomcoord) eq 'ARRAY') && (ref($futuredomcoord) eq 'ARRAY')) {
                if (grep(/^\Q$users->[$i]\E$/,@{$olddomcoord})) {
                    $output .= &mt('expired');
                } elsif (grep(/^\Q$users->[$i]\E$/,@{$futuredomcoord})) {
                    $output .= &mt('future');
                } else {
                    $output .= &mt('active');
                }
            }
            $output .= '</td>';
        } elsif ($role eq 'cc') {
            $output .= '<td>'.$$status{$$users[$i]}.'</td>';
        }
        $output .= '<td>';
        if ($$notifystate{$$users[$i]} == 1) {
            $output .= $$lt{ntac};
        } else {
            $output .= $$lt{ntin};
        }
        $output .= '</td><td><input type="checkbox" name="note_'.$$notifyshow.'"'; 
        if ($$notifystate{$$users[$i]} == 1) {
            $output .= ' checked="checked"';
        }
        $output .= $disabled.' /></td>';
        $output .= &Apache::loncommon::end_data_table_row();
        $$notifyshow ++;
    }
    $output .= &Apache::loncommon::end_data_table();
    return $output;
}

sub print_accessdate_table {
    my ($r,$enrollvar,$tasktitleref,$action,$readonly) = @_;
    my ($start_table,$end_table) = &date_setting_table($$enrollvar{'default_enrollment_start_date'},$$enrollvar{'default_enrollment_end_date'},$action,$readonly);
    my ($oldstartshow,$oldendshow);
    if ( defined($$enrollvar{'default_enrollment_start_date'}) ) {
        $oldstartshow = &Apache::lonlocal::locallocaltime($$enrollvar{'default_enrollment_start_date'});
    }
    if ( defined($$enrollvar{'default_enrollment_end_date'}) ) {
        $oldendshow = &Apache::lonlocal::locallocaltime($$enrollvar{default_enrollment_end_date});
        if ($$enrollvar{'default_enrollment_end_date'} eq '0') {
            $oldendshow = &mt("'No end date'");
        }
    }
    my %lt =&Apache::lonlocal::texthash(
         'cuno' => 'Currently NO default first access or last access dates are set.',
         'ifyo' => 'If you do not set a start date and an end date, then student roles for students added by the automated enrollment process will start immediately when the student is added and will never become inactive.',
         'ifyd' => 'If you do not set an access start date and an end date, then student roles for new students added when you click "Go" will become active immediately and will never become inactive.',
         'setf' => 'Set date of first access',
         'setl' => 'Set date of last access',
         'freg' => 'for registered students added via automated enrollment',
         'fnew' => 'for new students added when you update the class roster',
         'ifad'  => 'If automated adds are enabled, then when students are added their student roles will become active on the date set here for first access, and their roles will become inactive on the date set here for last access.  These default access dates will be overridden for specific students if the institutional classlist data supplied to the automatic enrollment process includes entries for the startdate and enddate fields for those students.',
    );
    $lt{'ncds'} = &mt('Changing default start and end access dates will affect [_1]future enrollments[_2] and also [_1]currently inactive[_2] students (i.e., those for whom access will begin in the future).','<b>','</b>');
    $lt{'tcha'} = &mt('To change access dates for [_1]currently active[_2] students, use User Management -> "Manage Course Users" to display currently active students, then use the dropdown menu for "Action to take for selected users:" to choose "Change starting/ending dates", select the students to change, and click "Proceed".','<b>','</b>');
    my $dateshow;
    if ( ($oldendshow eq '') && ($oldstartshow eq '') ) {
       $dateshow = '<br /><span class="LC_warning">'.
                   &mt('Warning.').'&nbsp;'.$lt{'cuno'}.' ';
       if ($action eq 'setaccess') {
           $dateshow .= $lt{'ifyo'}."\n";
       } elsif ($action eq 'updatenow') {
           $dateshow .= $lt{'ifyd'}."\n";
       }
       $dateshow .= '</span>';
    } else {
        $dateshow = &mt('Currently: default first access').": <b><i>$oldstartshow</i></b>, ".&mt('default last access').": <b><i>$oldendshow</i></b>\n";
    }
    if ($action eq 'setaccess') {
        $r->print('
                <form name="enter" method="post" action=""><br />
                <table width="100%" border="0" cellpadding="2" cellspacing="2">
                 <tr>
                  <td align="left"><b>'.$tasktitleref->{$action}.'</b>
                  <br /><br />'.
                   $dateshow.'
                  </td>
                 </tr>
                </table>
        ');
    } elsif ($action eq 'updatenow') {
        $r->print('
                <br /><br />'.$dateshow."\n");
    }
    $r->print('
                <table width="100%" border="0" cellpadding="3" cellspacing="3">
                 <tr>
                  <td align="left" colspan="2">
                   <table border="0" cellspacing="0" cellpadding="2">
                    <tr>
                     <td colspan="3">
');
    if ($action eq 'setaccess') {
        $r->print("<i>$lt{'setf'} $lt{'freg'}</i>");
    } elsif ($action eq 'updatenow') {
        $r->print("<i>$lt{'setf'} $lt{'fnew'}</i>");
    }
    $r->print(' 
                       </td>
                      </tr>
                      <tr>
                       <td>'.$start_table.'
                       </td>
                      </tr>
                     </table>
                    </td>
                   </tr>
                   <tr>
                    <td align="left" colspan="2">
                     <table border="0" cellspacing="0" cellpadding="2">
                      <tr>
                       <td colspan="3">
    ');
    if ($action eq 'setaccess') {
        $r->print("<i>$lt{'setl'} $lt{'freg'}</i>");
    } elsif ($action eq 'updatenow') {
        $r->print("<i>$lt{'setl'} $lt{'fnew'}</i>");
    }
    $r->print('
                       </td>
                      </tr>
                      <tr>
                       <td>'.$end_table.'
                       </td>
                      </tr>
                     </table>
                    </td>
                   </tr>
    ');
    if ($action eq 'setaccess') {
        $r->print('
                   <tr>
                    <td colspan="2"><span style="color: #888888">'.$lt{'ifad'}.'</span></td>
                   </tr>
                   <tr>
                    <td colspan="2">&nbsp;</td>
                   </tr>
                   <tr>
                    <td colspan="2"><b>'.&mt('Note').':</b> '.$lt{'ncds'}.' '.$lt{'tcha'}.'</td>
                   </tr>
                  </table>
        ');
    } elsif ($action eq 'updatenow') {
        $r->print('
                  </table>
        ');
    }
}

###############################################################
sub print_doc_base {
    my ($r) = @_;
    $r->print('
  </td>
 </tr>
</table>
<br />'."\n".
    &Apache::loncommon::end_page());
}
 
###################################################################
sub print_chgsettings_response {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my %settings = &Apache::lonnet::get('environment',['internal.autoadds','internal.autodrops'],$dom,$crs);
    my ($curradds,$currdrops,$autoadds,$autodrops,$response,$warning,
        $warn_prefix,$warn_suffix,$warnfiller);
    if ( defined($settings{'internal.autoadds'}) ) {
	$curradds = $settings{'internal.autoadds'};
    }
    if ( defined($settings{'internal.autodrops'}) ) {
	$currdrops = $settings{'internal.autodrops'};
    }
    if ( exists($env{'form.autoadds'}) ) {
	$autoadds=$env{'form.autoadds'};
    }
    if ( exists($env{'form.autodrops'}) ) {
	$autodrops=$env{'form.autodrops'};
    }
    my %cenv = ('internal.autoadds' => $autoadds,
		'internal.autodrops' => $autodrops);
    my $reply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
    if ($reply ne 'ok') {
	$response = 
            &mt('There was a problem processing your requested changes.').' '.
            &mt('The automated enrollment settings for this course have been left unchanged.').'<br />';
    } else {
	if ($autoadds) {
	    if ($curradds) {
                $response =
                    &mt('Nightly additions based on classlist changes still [_1]enabled[_2]','<b>','</b>').'<br />';
	    } else {
                $response = 
                    &mt('Nightly additions based on classlist changes now [_1]enabled[_2]','<b>','</b>').'<br />';
	    }
	} else {
	    if ($curradds) {
		$response = 
                    &mt('Nightly additions based on classlist changes now [_1]disabled[_2]','<b>','</b>').'<br />';
	    } else {
		$response = 
                    &mt('Nightly additions based on classlist changes still [_1]disabled[_2]','<b>','</b>').'<br />';
	    }
	}
	if ($autodrops) {
	    if ($currdrops) {
		$response .= &mt('Nightly removals based on classlist changes still [_1]enabled[_2]','<b>','</b>').'<br />';
	    } else {
		$response .= &mt('Nightly removals based on classlist changes now [_1]enabled[_2]','<b>','</b>').'<br />';
	    }
	} else {
	    if ($currdrops) {
		$response .= &mt('Nightly removals based on classlist changes now [_1]disabled[_2]','<b>','</b>').'<br />';
	    } else {
		$response .= &mt('Nightly removals based on classlist changes still [_1]disabled[_2]','<b>','</b>').'<br />';
	    }
	}
	if ($autoadds || $autodrops) {
	    $warning = &warning_message($dom,$crs,$action);
            unless ($warning eq '') {
	        $response .= '<br /><span class="LC_warning">'.
                             '<b>'.&mt('Warning.').'</b> ';
                if ($autoadds && $autodrops) {
                    $response .= 
                        &mt('Although you indicated that nightly adds and drops should be enabled, additional action is required.');
                } elsif ($autoadds) {
                    $response .= 
                        &mt('Although you indicated that nightly adds should be enabled, additional action is required.');
                } else {
                    $response .=
                        &mt('Although you indicated that nightly drops should be enabled, additional action is required.');
                }
	        $response .= '</span><br />'.$warning;
	    }
        }
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub print_chgfailsafe_response {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my %settings = &Apache::lonnet::get('environment',
                                        ['internal.autodropfailsafe',
                                         'internal.autodropfailsafetype'],
                                        $dom,$crs);
    my ($currfailsafe,$newfailsafe,$currfailsafetype,$newfailsafetype,$response);
    if (defined($settings{'internal.autodropfailsafe'})) {
        $currfailsafe = $settings{'internal.autodropfailsafe'};
    }
    if (defined($settings{'internal.autodropfailsafetype'})) {
        $currfailsafetype = $settings{'internal.autodropfailsafetype'};
    }
    if (exists($env{'form.autodropfailsafe'})) {
        $env{'form.autodropfailsafe'} =~ s{^\s+|\s+$}{}g;
        if ($env{'form.autodropfailsafe'} !~ /\D/) { 
            $newfailsafe = $env{'form.autodropfailsafe'};
        }
    }
    if ($env{'form.autodropfailsafetype'} =~ /^(any|zero|off)$/) {
        $newfailsafetype = $env{'form.autodropfailsafetype'};
    }
    if (($currfailsafe ne $newfailsafe) || ($currfailsafetype ne $newfailsafetype)) {
        my %cenv = ('internal.autodropfailsafe' => $newfailsafe,
                    'internal.autodropfailsafetype' => $newfailsafetype,
                   );
        my $reply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
        if ($reply ne 'ok') {
            $response =
                &mt('There was a problem processing your requested changes.').' '.
                &mt('The automated enrollment settings for this course have been left unchanged.').'<br />';
        } else {
            if ($currfailsafetype ne $newfailsafetype) {
                if ($env{'form.autodropfailsafetype'} eq 'dom') {
                    $response = &mt('Course-specific setting for condition for when failsafe applies deleted; domain default now applies.');
                } elsif ($newfailsafetype eq 'off') {
                    $response = &mt('Course-specific setting set to disable failsafe use.');
                } elsif ($newfailsafetype eq 'zero') {
                    $response = &mt('Course-specific setting set so failsafe applies when zero enrollment retrieved for an institutional section.');
                } else {
                    $response = &mt('Course-specific setting set so failsafe applies when zero or greater enrollment is retrieved for an institutional section.');
                }
                $response .= '<br />';
            }
            if ($currfailsafe ne $newfailsafe) {
                if ($newfailsafe ne '') {
                    $response .= &mt('Course-specific setting for drop failsafe threshold set to [_1]',$newfailsafe);
                } else {
                    $response .= &mt('Course-specific setting for drop failsafe threshold deleted; domain default now applies.');
                }
            }
        }
    } else {
        $response = &mt('The new values for the automated drop failsafe threshold and conditions under which failsafe applies were the same as the existing values, so no changes have been made.'); 
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub print_setdates_response {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my %settings = 
        &Apache::lonnet::get('environment',
                             ['internal.autostart','internal.autoend'],
                             $dom,$crs);
    my $currstart = $settings{'internal.autostart'};
    my $currend = $settings{'internal.autoend'};
    my ($response,$showstart,$showend,$warning,$warn_prefix);
    my ($autostart,$autoend) = &get_dates_from_form();
    if ( ($autostart eq '') || ($autoend eq '') ) {
        $response = 
            &mt('There was a problem processing your requested changes.').' '.
            &mt('The automated enrollment settings for this course have been left unchanged.').'<br />';
    } elsif (($autoend > 0) && ($autoend <= $autostart)) {
        $response = 
            &mt('The date/time selected for starting auto-enrollment was the same or later than the date/time selected for ending auto-enrollment.').' '.
            &mt('As this means auto-enrollment will never be active, your requested changes have not been processed, and the existing values remain in effect.').' '.
            &mt('Please [_1]go back[_2] to the previous page to try your changes again.',
                '<a href="javascript:history.go(-1)">','</a>')."\n";
    } else {       
        $showstart = &Apache::lonlocal::locallocaltime($autostart);
        if ($autoend) {
	    $showend = &Apache::lonlocal::locallocaltime($autoend);
        } else {
	    $showend = &mt("'No end date'");
        } 

        my %cenv = ('internal.autostart' => $autostart,
  		    'internal.autoend' => $autoend);
        my $reply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
        if ($reply ne 'ok') {
	    $response = 
                &mt('There was a problem processing your requested changes.').' '.
                &mt('The automated enrollment settings for this course have been left unchanged.').'<br />';
        } else {
	    if ($currstart == $autostart) {
	        $response = &mt('The first date for automated enrollment has been left unchanged as [_1]',$showstart).'<br />';
	    } else {
	        $response = &mt('The first date for automated enrollment has been changed to [_1]',$showstart).'<br />';
	    } 
	    if ($currend == $autoend) {
	        $response .= &mt('The last date for automated enrollment has been left unchanged as [_1]',$showend).'<br />';
	    } else {
	        $response .= &mt('The last date for automated enrollment has been changed to [_1]',$showend).'<br />';
	    }
 
# Generate message in case where old first enrollment date was later than today, but new first enrollment date is now today or earlier.

	    my $rosterupdated = 0;
            my ($firstaccess,$nextupdate,$lastupdate);
	    my $nowstamp = time;
	    my @date_list=localtime(time);
	    my $cur_year = $date_list[5];
	    my $curday = $date_list[3];
	    my $curmonth = $date_list[4];
	    my $lastmidnt = timelocal(0,0,0,$date_list[3],$date_list[4],$date_list[5]);
	    my $nextmidnt = 86400 + $lastmidnt;

	    my $todayupdate = timelocal(0,30,1,$date_list[3],$date_list[4],$date_list[5]);
	    my $lastupdate = $todayupdate - 86400;
	    if ($nowstamp < $todayupdate) {
	      $nextupdate = "today";
	    } else {
	      $nextupdate = "tomorrow";
	    }
	    if ($currstart < $lastupdate) {
	        $rosterupdated = 1;
	    }
	    if ($autostart < $nextmidnt ) {
	        if ( $autostart >= $lastmidnt) {
		    $firstaccess = "today";
	        } else {
	  	    $firstaccess = "a date prior to today";
	        }
	        if (($nowstamp >= $autostart) && ($rosterupdated == 0)) {
		    $response .= 
                        '<br />'.
                        &mt("Although you have now set the first enrollment date to $firstaccess, automatic enrollment will [_1]not[_2] occur until the next automatic enrollment update occurs for all LON-CAPA courses at 1.30 am $nextupdate.",'<b>','</b>').' '.
                        &mt('If you wish to immediately enroll registered students included in the institutional classlist for this class, please visit the [_1]roster update page[_2].'.
                           '<a href="/adm/populate?action=updatenow">','</a>').
                        '<br />';
	        }
	    }
	    $warning = &warning_message($dom,$crs,$action);
            unless ($warning eq '') {
                $response .= 
                    '<br /><span class="LC_warning">'.
                    '<b>'.&mt('Warning.').'</b> '.
                    &mt('Although you set a start and end date for auto-enrollment, additional action is required.').'</span><br />'.$warning;
	    }
        }
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub print_setaccess_response {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my %settings = 
        &Apache::lonnet::get('environment',
                             ['default_enrollment_start_date',
                              'default_enrollment_end_date',
                              'internal.autostart'],$dom,$crs);
    my $currstart = $settings{'default_enrollment_start_date'};
    my $currend = $settings{'default_enrollment_end_date'};
    my $autostart = $settings{'internal.autostart'};
    my $response;
    my ($startaccess,$endaccess) = &get_dates_from_form();
    if (($startaccess eq '') || ($endaccess eq '')) {
        $response = 
            &mt('There was a problem processing your requested changes.').' '.
            &mt('The default start and end access dates for this course have been left unchanged.').
            '<br />';
    } elsif (($endaccess > 0) && ($endaccess <= $startaccess)) {
        $response = 
            &mt('The default start access date/time you chose was the same or later than the default end access date/time.').' '.
            &mt('As this means that roles will never be active, your requested changes have not been processed, and the existing values remain in effect.').' '.
            &mt('Please [_1]go back[_2] to the previous page to try your changes again.',
                '<a href="javascript:history.go(-1)">','</a>')."\n";
    } else {
        my $showstart = &Apache::lonlocal::locallocaltime($startaccess);
        my ($showend,$warning,$warn_prefix);
        if ($endaccess) {
	    $showend = &Apache::lonlocal::locallocaltime($endaccess);
        } else {
	    $showend = &mt("'No end date'");
        }

        my %cenv = ('default_enrollment_start_date' => $startaccess,
		'default_enrollment_end_date' => $endaccess);
        my $reply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
        if ($reply ne 'ok') {
	    $response = 
                &mt('There was a problem processing your requested changes.').' '.
                &mt('The automated enrollment settings for this course have been left unchanged.').'<br />';
        } else {
	    if ($currstart == $startaccess) {
	        $response = &mt('The first access date for students being added via automated enrollment has been left unchanged as [_1].',$showstart).'<br />';
	    } else {
	        $response = &mt('The first access date for students being added via automated enrollment has been changed to [_1].',$showstart).'<br />';
	    }
	    if ($currend == $endaccess) {
	        $response .= &mt('The last access date for students being added via automated enrollment has been left unchanged as [_1].',$showend).'<br />';
	    } else {
	        $response .= &mt('The last access date for students being added via automated enrollment has been changed to [_1]',$showend).'<br />';
	    }
            $response .= 
                '<br />'.
                &mt('Any change in access dates will only apply to students who are not currently active, i.e., those who currently have access start dates in the future, and to those added by future automated enrollment.').
                '<br /><br />'.
                 &mt('To change access dates for [_1]currently active[_2] students, use User Management -> "Manage course users" to display currently active students, then use the dropdown menu for "Action to take for selected users:" to choose "Change starting/ending dates", select the students to change, and click "Proceed".','<b>','</b>').
                '<br />';

# Generate message in case where old first access date was later than today, but new first access date is now today or earlier.

	    my $accessgiven= 0;
	    my ($firstaccess,$nextupdate,$lastupdate);
	    my $nowstamp = time;
	    my @date_list=localtime(time);
	    my $cur_year = $date_list[5];
	    my $curday = $date_list[3];
	    my $curmonth = $date_list[4];
	    my $lastmidnt = timelocal(0,0,0,$date_list[3],$date_list[4],$date_list[5]);
	    my $nextmidnt = 86400 + $lastmidnt;

	    my $todayupdate = timelocal(0,30,1,$date_list[3],$date_list[4],$date_list[5]);
	    my $tomorrowupdate = $todayupdate + 86400;
	    my $lastupdate = $todayupdate - 86400;

	    if ($autostart < $nextmidnt) {
	        if ($nowstamp < $todayupdate) {
		    $nextupdate = 'at 1.30 am today';
	        } else {
		    $nextupdate = 'at 1.30 am tomorrow';
	        }
	    } else {
	        my @enrollstart = localtime($autostart);
	        $nextupdate = timelocal(0,30,1,$enrollstart[3],$enrollstart[4],$enrollstart[5]);
	        unless (($enrollstart[2] < 1) || ($enrollstart[2] == 1 && $enrollstart[1] <=30))  {
		    $nextupdate += 86400; 
	        }
	        $nextupdate = &Apache::lonlocal::locallocaltime($nextupdate);
	    }
	    if (($currstart < $lastupdate) && ($autostart < $lastupdate)) {
	        $accessgiven = 1;
	    }
	    if ($startaccess < $nextmidnt ) {
	        if ( $startaccess >= $lastmidnt) {
	    	    $firstaccess = 'today';
	        } else {
		    $firstaccess = 'a date prior to today';
	        }
	        if (($nowstamp >= $startaccess) && ($accessgiven == 0)) {
		    $response .= 
                        '<br />'.
                        &mt("Although you have now set the first access date to $firstaccess, automatic enrollment will [_1]not[_2] occur until the next automatic enrollment update occurs for all LON-CAPA courses $nextupdate.",
                            '<b>','</b>').' '.
                        &mt('If you wish to grant immediate course access for registered students included in the institutional classlist for this class, please visit the [_1]roster update page[_2].',
                            '<a href="/adm/populate?action=updatenow">','</a>').
                       '<br />';
	        }
	    }
	    $warning = &warning_message($dom,$crs,$action);
            unless ($warning eq '') {
	        $response .= '<br /><span class="LC_warning">'.
                             '<b>'.&mt('Warning.').'</b> '.
                             &mt('Although you have set default first and last access dates for students who are added via automatic enrollment, additional action is required.').
                            '</span><br />'.$warning;
	    }
        }
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub print_notify_response {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;

# Get current settings
    my %settings = 
        &Apache::lonnet::get('environment',
                             ['internal.notifylist','internal.coursecode'],
                             $dom,$crs);
    my $notifylist = $settings{'internal.notifylist'};
    my $coursecode = $settings{'internal.coursecode'};
    my @currpeople = split(/,/,$notifylist);
    my $notify = 0;
    my ($peoplestr,$response,@people);
    my $noprocess = 0;
    my $currcount = 0;
    foreach my $item (@currpeople) {
	unless ($item eq '') { $currcount ++; } 
    }
    if ( exists($env{'form.notify'}) ) {
	$notify=$env{'form.notify'};
    }
    if ( exists($env{'form.notifyshow'}) ) {
	my $notifyshow = $env{'form.notifyshow'};
	for (my $i=0; $i<$notifyshow; $i++) {
	    if ( exists($env{"form.note_$i"}) ) {
		if ( exists($env{"form.notifyname_$i"}) ) {
		    unless ( $env{"form.notifyname_$i"} eq '' ) {
			push(@people,$env{"form.notifyname_$i"});
		    }
		}
	    }
	}
	if ($notify) { $peoplestr = join(',',@people); }
    } else {
	if ($notify) {
	    if ($currcount) {
		$response = &mt('There was a problem retrieving the updated list of recipients of notification messages.').' '.
                            &mt('The notification settings for this course have been left unchanged.').'<br />';
		$peoplestr = $notifylist;
		@people = @currpeople;
		$noprocess = 1;
	    }
	}
    }
    unless ($noprocess == 1) {
	my %cenv = ('internal.notifylist' => $peoplestr);
	my $reply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
	if ($reply ne 'ok') {
	    $response = 
                &mt('There was a problem processing your requested changes.').' '.
                &mt('The notification settings for this course have been left unchanged.').
                '<br />';
	} else {
	    if ($notify) {
		if (@people) {
		    if ($currcount) {
			$response .=
                            &mt('Notification of enrollment changes still [_1]enabled[_2]','<b>','</b>').
                            '<br />';
		    } else {
			$response .=
                            &mt('Notification of enrollment changes now [_1]enabled[_2]'.'<b>','</b>').
                            '<br />';
		    }
		    $response .= 
                        '<br />'.
                        &mt('The following will receive notification if there are any changes in enrollment in LON-CAPA course: [_1] as a result of the nightly enrollment check:',"$realm ($coursecode)").
                        '<br /><ul>'."\n";
		    foreach my $person (@people) {
			$response .= "<li>$person</li>\n";
		    }
		    $response .= "</ul>\n";
		} else {
		    $response = &mt('Notification of enrollment changes was [_1]not enabled[_2] as no [_3]s were selected as recipients.','<b>','</b>',&Apache::lonnet::plaintext('cc')).'<br />';
		}
	    } else {
		if ($currcount) {
		    $response = &mt('Notification of enrollment changes now [_1]disabled[_2]','<b>','</b>').'<br />';
		} else {
		    $response = &mt('Notification of enrollment changes still [_1]disabled[_2]','<b>','</b>').'<br />';
		}
	    }
	}
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub print_crosslistings_menu {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my %settings = 
        &Apache::lonnet::get('environment',
                             ['internal.crosslistings','internal.coursecode'],
                             $dom,$crs);
    my (@currxlists,@xlists,$xliststr,$response);
    my $crosscount = 0;
    my $removecount = 0;
    my $coursecode = $settings{'internal.coursecode'};
    if ($settings{'internal.crosslistings'} ne '') {
	@currxlists = split(/,/,$settings{'internal.crosslistings'});
    }
    if (@currxlists > 0) {
	for (my $i=0; $i<@currxlists; $i++) {
	    my $xlist = "cross_".$i;
	    my $lc_sec = "lcsec_".$i;
	    if ( exists($env{"form.$xlist"}) ) {
		my $xlistentry = '';
		if ($currxlists[$i] =~ /^([^:]+)/) {
		    $xlistentry = $1.':';
		}
		if ( exists($env{"form.$lc_sec"}) ) {
		    $xlistentry .= $env{"form.$lc_sec"};
		}
		push(@xlists,$xlistentry);
		$crosscount ++;
	    } else {
		$removecount ++;
	    }
	}
    }

    $xliststr = join(',',@xlists);

    my %cenv = ('internal.crosslistings' => $xliststr);
    my $reply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
    if ($reply ne 'ok') {
	$response = &mt('There was a problem processing your requested changes.').' '.
                    &mt('The automated enrollment settings for this course have been left unchanged.').'<br />';
    } else {
	if ($removecount > 0) {
	    $response = &mt('A total of [quant,_1,course is,courses are] no longer crosslisted with LON-CAPA course: [_2].',
                            $removecount,"$realm ($coursecode").'<br /><br />';
	}
	if ($crosscount > 0) {
	    $response .= &mt('The [quant,_1,course] listed below remain crosslisted with this LON-CAPA course, and students enrolling in these course sections will be automatically added to the class roster for the course, if you have chosen to enable a nightly automated enrollment update.',$crosscount).
                         '<br /><ul>'."\n";
            my @showable;
            &reformat_xlists($dom,$crs,$coursecode,\@xlists,\@showable);
            foreach my $item (@showable) {
                my ($xlist,$lc_sec) = split(/:/,$item);
		$response .= 
                    '<li>'.&mt('[_1] - ID: [_2]',$xlist,$lc_sec).'</li>'."\n";
	    }
	    $response .= '</ul><br />'."\n";
	}
    }
    if ( exists($env{'form.numcross'}) ) {
	my $numcross = $env{'form.numcross'};
	if ($numcross) {
            my (@codetitles,%cat_titles,%cat_order,@code_order);
            &Apache::lonnet::auto_possible_instcodes($dom,\@codetitles,\%cat_titles,
                                                     \%cat_order,\@code_order);       
	    $response .=
                &mt('You indicated that you wish to add an additional [quant,_1,crosslisting].',$numcross).' ';
            if (@codetitles > 0) {
                my $lastitem = pop(@codetitles);
                $response .=
                    &mt('For each new crosslisting select [_1], and enter the [_2] and the LON-CAPA section ID.',join(', ',@codetitles),$lastitem).' '.
                    &mt('The LON-CAPA section ID can be left blank, if you do not wish to tie a section ID to this crosslisting.').' '.
                    '<br /><br />'.
                    '<form name="enter" method="post" action="">'."\n".
                    &Apache::loncommon::start_data_table()."\n".
                    &Apache::loncommon::start_data_table_header_row()."\n";
                foreach my $title (@codetitles) {
                    if (ref($cat_order{$title}) eq 'ARRAY') {
                        if (@{$cat_order{$title}} > 0) {
                            $response .= '<th>'.$title.'</th>';
                        }
                    }
                }
                $response .= '<th>'.$lastitem.'</th>'."\n".
                             '<th>'.&mt('Institutional section').'</th>'."\n".
                             '<th>'.&mt('LON-CAPA section').'</th>'."\n".
                             &Apache::loncommon::end_data_table_header_row()."\n";
                for (my $i=0; $i<$numcross; $i++) {
                    $response .=
                        &Apache::loncommon::start_data_table_row()."\n";
                    foreach my $title (@codetitles) {
                        if (ref($cat_order{$title}) eq 'ARRAY') {
                            if (@{$cat_order{$title}} > 0) {
                                $response .= '<td align="center">'.
                                             '<select name="newcross_'.$i.'_'.$title.'">'."\n".
                                             ' <option value="" selected="selected">'.
                                             &mt('Select').'</option>'."\n";
                                foreach my $item (@{$cat_order{$title}}) {
                                    my $longitem = $item;
                                    if (ref($cat_titles{$title}) eq 'HASH') {
                                        if ($cat_titles{$title}{$item} ne '') {
                                            $longitem = $cat_titles{$title}{$item};
                                        }
                                    }
                                    $response .= '<option value="'.$item.'">'.$longitem.
                                                 '</option>'."\n";
                                }
                                $response .= '</select></td>'."\n";
                            }
                        }
                    }
                    $response .= '<td align="center">'.
                                 '<input type="text" size="5" name="newcross_'.$i.'_'.$lastitem.'" />'.
                                 '</td>'."\n".'<td align="center">'.
                                 '<input type="text" size="10" name="newcross_'.$i.'_instsec" />'.
                                 '</td>'."\n".'<td align="center">'.
                                 '<input type="text" size="10" name="newlcsec_'.$i.'" /></td>'.
                                 &Apache::loncommon::end_data_table_row()."\n";
                }
                $response .= &Apache::loncommon::end_data_table()."\n";
            } else {
                $response .=              
                    &mt('For each new crosslisting enter the institutional course section code (e.g., fs03zol101001, for section 001 of zol101 for fs03 semester), and the LON-CAPA section ID you wish to assign to students who will be enrolled in your LON-CAPA class as a result of their registration in the crosslisted course section.').' '.
                    &mt('The LON-CAPA section ID can be left blank, if you do not wish to tie a section ID to this crosslisting.').' '.
                    &mt("The institutional course section code should only contain letters and/or numbers, and must be consistent with the scheme adopted by your Domain Coordinator to map course codes (and section numbers) to your institution's student information system.").
                    '<br /><br />'.
                    '<form name="enter" method="post" action="">'."\n".
                    &Apache::loncommon::start_data_table()."\n".
                    &Apache::loncommon::start_data_table_row()."\n".
                    '<th>'.&mt('Crosslisting').'</th>'."\n".
                    '<th>'.&mt('LON-CAPA section ID').'</th>'."\n".
                    &Apache::loncommon::end_data_table_row();
	       for (my $i=0; $i<$numcross; $i++) {
                   $response .= 
                       &Apache::loncommon::start_data_table_row().'
                       <td><input type="text" size="15" name="newcross_'.$i.'" /></td>
                       <td align="right"><input type="text" size="10" name="newlcsec_'.$i.'" /></td>'.
                       &Apache::loncommon::end_data_table_row();
	        }
                $response .= &Apache::loncommon::end_data_table();
            }
            $response .= '
              </td>
             </tr>
             <tr>
              <td align="right">
               <input type="button" name="newcross" value="'.&mt('Go').'" onclick="'."process('newcross')".'" />
              </td>
             </tr>
            </table>
            <input type="hidden" name="numcross" value="'.$numcross.'" />
            <input type="hidden" name="action" value="newcross" />
            <input type="hidden" name="state" value="process" />
            </form>'."\n";
        }
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub print_crosslistings_response {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my %settings = 
        &Apache::lonnet::get('environment',
                             ['internal.crosslistings','internal.coursecode',
                              'internal.courseowner','internal.co-owners'],
                             $dom,$crs);
    my (@currxlists,@xlists,@allxlists,@badxlists,@badowner,@reserved,
        @matchgroup,$response,$warning,$warn_prefix);
    my $numcross = 0;
    my $xliststr =  $settings{'internal.crosslistings'};
    my $coursecode = $settings{'internal.coursecode'};
    my $owner = $settings{'internal.courseowner'};
    my $coowners = $settings{'internal.co-owners'};
    if ($xliststr ne '') {
	@allxlists = split(/,/,$xliststr);
    }
    if ( exists($env{'form.numcross'}) ) {
	$numcross = $env{'form.numcross'};
    }
    if ($numcross) {
        my %curr_groups = &Apache::longroup::coursegroups();
        my (@codetitles,%cat_titles,%cat_order,@code_order);
        &Apache::lonnet::auto_possible_instcodes($dom,\@codetitles,\%cat_titles,
                                                 \%cat_order,\@code_order);
        my $lastitem = $codetitles[-1];
	for (my $i=0; $i<$numcross; $i++) {
	    my $xl = '';
            if (@code_order > 0) {
                foreach my $item (@code_order) {
                    my $possval = $env{'form.newcross_'.$i.'_'.$item};
                    if ($item eq $lastitem) {
                        $xl .= $possval;
                    } else {
                        my $possval = $env{'form.newcross_'.$i.'_'.$item};
                        if (ref($cat_order{$item}) eq 'ARRAY') {
                            if (grep(/^\Q$possval\E$/,@{$cat_order{$item}})) {
                                $xl .= $possval;
                            }
                        }
                    }
                }
                if ($xl ne '') {
                    my $crskey = $crs.':'.$xl;
                    if ($env{'form.newcross_'.$i.'_instsec'} ne '') {
                        my $poss_sec = $env{'form.newcross_'.$i.'_instsec'};
                        my %formatted = &Apache::lonnet::auto_instsec_reformat($dom,'clutter',
                                                                               {$crskey => [$poss_sec]});
                        if (ref($formatted{$crskey}) eq 'ARRAY') {
                            $xl .= $formatted{$crskey}->[0];
                        }
                    }
                }
            } else {
                $xl = $env{'form.newcross_'.$i};
            }
	    my $lc_sec = "newlcsec_".$i;
	    if ($xl ne '') {
                if (exists($env{"form.$lc_sec"})) {
                    my $lc_sec_check = &validate_lcsec(\%curr_groups,
                                                    $env{"form.$lc_sec"});
                    if ($lc_sec_check eq 'reserved') {
                        push(@reserved,$xl.':'.$env{"form.$lc_sec"});
                        next;
                    } elsif ($lc_sec_check eq 'group') {
                        push(@matchgroup,$xl.':'.$env{"form.$lc_sec"});
                        next;
                    }
                }
		my $coursecheck =
                    &Apache::lonnet::auto_validate_courseID($crs,$dom,$xl);
		if ($coursecheck eq 'ok') {
		    my $addcheck = '';
		    $addcheck = &Apache::lonnet::auto_new_course($crs,$dom,$xl,$owner,$coowners);
		    unless ($addcheck eq 'ok') {
                        if ($coowners) {
                            foreach my $user (split(/,/,$coowners)) {
                                if ($user =~ /^($match_username):($match_domain)$/) {
                                    if (&Apache::lonnet::auto_validate_inst_crosslist($crs,$dom,$coursecode,
                                                                                      $xl,$user) eq 'valid') {
                                        $addcheck = 'ok';
                                        last;
                                    }
                                }
                            }
                        }
                    }
                    if ($addcheck eq 'ok') {
                        push(@xlists,$xl.':'.$env{"form.$lc_sec"});
                    } else { 
			push(@badowner,$xl.':'.$env{"form.$lc_sec"});
		    }
		} else {
		    push(@badxlists,$xl.':'.$env{"form.$lc_sec"}.":".$coursecheck);
		}
	    }
	}
	push(@allxlists,@xlists);
    }
    
    if (@xlists > 0 ) {
	unless ($xliststr eq '') { $xliststr .= ","; }
	$xliststr .= join(",",@xlists);

	my %cenv = ('internal.crosslistings' => $xliststr);
	my $reply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
	if ($reply ne 'ok') {
	    $response = 
                &mt('There was a problem processing your requested changes.').' '.
                &mt('The automated enrollment settings for this course have been left unchanged.').
                '<br /><br />';
	} else {
	    $response = &mt('The courses listed below are now crosslisted with this LON-CAPA course, and students enrolling in these course sections will be automatically added to the class roster for the course, if you have chosen to enable a nightly automated enrollment update.').'<br /><ul>'."\n";
            my @showable;
            &reformat_xlists($dom,$crs,$coursecode,\@allxlists,\@showable);
            foreach my $item (@showable) {
		my ($xlist,$lc_sec) = split(/:/,$item);
		$response .= '<li>'.&mt('[_1] - ID: [_2]',$xlist,$lc_sec).'</li>'.
                              "\n";
	    }
	    $response .= '</ul><br /><br />'."\n";
	}
    } else {
	if ($xliststr =~ /:/) {
	    my @oldxlists = split(/,/,$xliststr);
	    $response .= &mt('Although no new crosslistings were added, the courses listed below continue to be crosslisted with your LON-CAPA course.').
                         '<br /><ul>'."\n";
            my @showable;
            &reformat_xlists($dom,$crs,$coursecode,\@oldxlists,\@showable);
            foreach my $item (@showable) {
		my ($xlist,$lc_sec) = split(/:/,$item);
		$response .= '<li>'.&mt('[_1] - ID: [_2]',$xlist,$lc_sec).'</li>'.
                             "\n";
	    }
	    $response .= '</ul><br /><br />'."\n";
	}
    }
    if (@badxlists > 0) {
	$response .= &mt("The courses listed below could not be included in the crosslistings for this LON-CAPA course, because they are not valid courses according to your institution's official schedule of classes and sections.").
                     '<br /><ul>'."\n";
        my @showable;
        &reformat_xlists($dom,$crs,$coursecode,\@badxlists,\@showable);
        foreach my $item (@showable) {
	    my ($xlist,$lc_sec,$prob) = split(/:/,$item);
	    $response .= '<li>'.
                         &mt('[_1] - ID: [_2] - Error: [_3]',
                             $xlist,$lc_sec,$prob).
                         '</li>'."\n";
	}
	$response .= '</ul><br /><br />'."\n";
    }
    if (@badowner > 0) {
	$response .= &mt("The courses listed below could not be included in the crosslistings for this LON-CAPA course, because the owner of this course - [_1] - does not have rights to view enrollment in those classes, as determined by your instititution's policies on access to official classlists.",$owner).
                     '<br /><ul>'."\n";
        my @showable;
        &reformat_xlists($dom,$crs,$coursecode,\@badowner,\@showable);
        foreach my $item (@showable) {
	    my ($xlist,$lc_sec) = split(/:/,$item);
	    $response .= '<li>'.&mt('[_1] - ID: [_2]',$xlist,$lc_sec).'</li>'.
                         "\n";
	}
	$response .= '</ul><br /><br />'."\n";
    }
    if (@reserved > 0) {
        $response .= &mt('The courses listed below could not be included in the crosslistings for this LON-CAPA course, because the section ID associated with the crosslisted course is a reserved word.').' '.
                     &mt('Please [_1]go back[_2]</a> and change the section ID for each of these courses.',
                         '<a href="javascript:history(-1)">','>/a>').
                     '<br /><ul>'."\n";  
        my @showable;
        &reformat_xlists($dom,$crs,$coursecode,\@reserved,\@showable);
        foreach my $item (@showable) {
            my ($xlist,$lc_sec) = split(/:/,$item);
            $response .= '<li>'.&mt('[_1] - ID: [_2]',$xlist,$lc_sec).'</li>'.
                         "\n";
        }
        $response .= '</ul><br /><br />'."\n";
    }

    if (@matchgroup > 0) {
        $response .= &mt('The courses listed below could not be included in the crosslistings for this LON-CAPA course, because the section ID associated with the crosslisted course is the name of a group in this course.').' '.
                     &mt('Please [_1]go back[_2] and change the section ID for each of these courses.','<a href="javascript:history(-1)">','</a>').
                     '<br /><ul>'."\n";
        my @showable;
        &reformat_xlists($dom,$crs,$coursecode,\@matchgroup,\@showable);
        foreach my $item (@showable) {
            my ($xlist,$lc_sec) = split(/:/,$item);
            $response .= '<li>'.&mt('[_1] - ID: [_2]',$xlist,$lc_sec).'</li>'.
                         "\n";
        }
        $response .= '</ul><br /><br />'."\n";
    }
    if (@allxlists > 0) {
	$warning = &warning_message($dom,$crs,$action);
        unless ($warning eq '') {
	    $response .= '<br /><span class="LC_warning"><b>'.
                         &mt('Warning.').'</b> '.
                         &mt('Although you have selected crosslisted courses to contribute enrollment to this course, additional action is required.').
                         '</span><br />'.$warning;
	}
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub reformat_xlists {
    my ($dom,$crs,$coursecode,$xlistsref,$showxlistsref) = @_;
    return unless ((ref($xlistsref) eq 'ARRAY') && (ref($showxlistsref) eq 'ARRAY'));
    my $crskey = $crs.':'.$coursecode;
    my (@xlcodes,@lcsecs,@extras);
    foreach my $xl (@{$xlistsref}) {
        my ($instcodesec,$lc_sec,$extra) = split(/:/,$xl);
        push(@xlcodes,$instcodesec);
        push(@lcsecs,$lc_sec);
        push(@extras,$extra);
    }
    my %reformatted =
        &Apache::lonnet::auto_instsec_reformat($dom,'declutter',
                                               {$crskey => \@xlcodes});
    if (ref($reformatted{$crskey}) eq 'ARRAY') {
        @xlcodes = @{$reformatted{$crskey}};
        for (my $i=0; $i<@xlcodes; $i++) {
            my $value = $xlcodes[$i].':'.$lcsecs[$i];
            if ($extras[$i] ne '') {
                $value .= ':'.$extras[$i];
            }
            push(@{$showxlistsref},$value);
        }
    }
    return;
}

sub print_sections_menu {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my %settings = 
        &Apache::lonnet::get('environment',
                             ['internal.sectionnums','internal.coursecode',
                              'internal.courseowner','internal.co-owners'],
                             $dom,$crs);
    my (@currsections,@sections,@badowner,@badsections,$secstr,$response,
        $warning,$warn_prefix); 
    my $seccount = 0;
    my $removecount = 0;
    my $addcount = 0;
    my $coursecode = $settings{'internal.coursecode'};
    my $owner = $settings{'internal.courseowner'};
    my $coowners = $settings{'internal.co-owners'};
    if ($settings{'internal.sectionnums'} ne '') {
	@currsections = split(/,/,$settings{'internal.sectionnums'});
    }
    if ( exists($env{'form.secshow'}) ) {
	for (my $i=0; $i<$env{'form.secshow'}; $i++) {
	    my $lc_sec = "loncapasec_".$i;
	    my $secnum = "secnum_".$i;
	    my $sec = "sec_".$i;
	    if ( exists( $env{"form.$sec"} ) ) {
		my $secentry;
		if ( exists( $env{"form.$secnum"} ) ) { 
		    $secentry = $env{"form.$secnum"}.':';
		}
		if ( exists( $env{"form.$lc_sec"} ) ) {
		    $secentry .= $env{"form.$lc_sec"};
		}
		if ( grep/\Q$env{"form.$secnum"}:\E/,@currsections) {
		    push(@sections,$secentry);
		    $seccount ++;
		} else {
                    my $newsec;
                    my $crskey = $crs.':'.$coursecode;
                    my %formattedsec = &Apache::lonnet::auto_instsec_reformat($dom,'clutter',
                                                                  {$crskey => [$env{"form.$secnum"}]});
                    if (ref($formattedsec{$crskey}) eq 'ARRAY') {
                        $newsec = $coursecode.$formattedsec{$crskey}->[0];
                    } else {
                        $newsec = $coursecode.$env{"form.$secnum"};
                    }
		    my $coursecheck = &Apache::lonnet::auto_validate_courseID($crs,$dom,$newsec);
		    if ($coursecheck eq 'ok') {
			my $addcheck = &Apache::lonnet::auto_new_course($crs,$dom,$newsec,$owner,$coowners);
			if ($addcheck eq 'ok') {
			    push(@sections,$env{"form.$secnum"}.":".$env{"form.$lc_sec"});
			    $seccount ++;
			    $addcount ++;
			} else {
			    push(@badowner,$env{"form.$secnum"}.":".$env{"form.$lc_sec"});
			}
		    } else {
			push(@badsections,$env{"form.$secnum"}.":".$env{"form.$lc_sec"}.":".$coursecheck);
		    }
		}
	    }
	}
	if (@currsections > 0) {
	    for (my $i=0; $i<@currsections; $i++) {
		if ($currsections[$i] =~ /^(\w+:)/) {
		    my $oldsec  = $1;
		    unless (grep/^$oldsec/,@sections) {
			$removecount ++;
		    }
		}
	    }
	}
    } elsif (@currsections > 0) {
	for (my $i=0; $i<@currsections; $i++) {
	    my $sec = "sec_".$i;
	    my $lc_sec = "lcsec_".$i;
	    if ( exists($env{"form.$sec"}) ) {
		my $secentry = '';
		if ($currsections[$i] =~ /^(\w+:)/) {
		    $secentry = $1;
		}
		if ( exists($env{"form.$lc_sec"}) ) {
		    $secentry .= $env{"form.$lc_sec"};
		}
		push(@sections,$secentry);
		$seccount ++;
	    } else {
		$removecount ++;
	    }
	}
    }
    
    $secstr = join(',',@sections);

    my %cenv = ('internal.sectionnums' => $secstr);
    my $reply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
    if ($reply ne 'ok') {
	$response = &mt('There was a problem processing your requested changes.').' '.
                     &mt('The automated enrollment settings for this course have been left unchanged.').'<br />';
    } else {
	if ($removecount) {
	    $response = &mt('A total of [quant,_1,section] have been removed from the list of sections which contribute to enrollment in LON-CAPA course: [_2].',$removecount,"$realm ($coursecode)").
                        '<br /><br />';
	}
	if ($addcount) {
	    $response .= &mt('A total of [quant,_1,section] have been added to the list of sections which contribute to enrollment in LON-CAPA course: [_2].',
                             $addcount,"$realm ($coursecode)").
                             '<br /><br />';
	}
	if ($seccount) { 
	    $response .= &mt('Students enrolling in the [quant,_1,section] listed below will be automatically added to the class roster for the course, if you have chosen to enable a nightly automated enrollment update.',$seccount).
                         '<br /><ul>'."\n";
	    foreach my $section (@sections) {
		my ($sec,$lc_sec) = split(/:/,$section);
		$response .= '<li>'.&mt('[_1] - ID: [_2]',$sec,$lc_sec).'</li>'
.
                              "\n";
	    }
	    $response .= '</ul><br />'."\n";
	}
    }
    if (@badsections > 0) {
	$response .= &mt("The sections listed below could not be included in the sections for this LON-CAPA course, because they are not valid section numbers according to your institution's official schedule of classes and sections.").
                     '<br /><ul>'."\n";
	foreach my $section (@badsections) {
	    my ($secnum,$lc_sec,$prob) = split(/:/,$section);
	    $response .= '<li>'.&mt('[_1] - ID: [_2] - Error: [_3]',
                                    $secnum,$lc_sec,$prob).'</li>'."\n";
	}
	$response .= "</ul><br /><br />\n";
    }
    
    if (@badowner > 0) {
	$response .= &mt("The sections listed below could not be included in the sections for this LON-CAPA course, because the owner of this course - [_1] - does not have rights to view enrollment in those classes as determined by your instititution's policies on access to official classlists.",$owner).
                     '<br /><ul>'."\n";
	foreach my $section (@badowner) {
	    my ($secnum,$lc_sec) = split(/:/,$section);
	    $response .= '<li>'.&mt('[_1] - ID: [_2]',$secnum,$lc_sec).'</li>'.
                         "\n";
	}
	$response .= '</ul><br /><br />'."\n";
    }
    
    if ($seccount > 0) {
	$warning = &warning_message($dom,$crs,$action);
        unless ($warning eq '') { 
	    $response .= '<br /><span class="LC_warning">'.
                         '<b>'.&mt('Warning.').'</b> '.
                         &mt('Although you have selected sections to contribute enrollment to this course, additional action is required.').
                         '</span><br />'.$warning;
	}
    }
    if ( exists($env{'form.numsec'}) ) {
	my $numsec = $env{'form.numsec'};
	if ($numsec > 0) {
	    $response .= 
                &mt('You indicated that you wish to incorporate student enrollment in your LON-CAPA course from an additional [quant,_1,section].',$numsec).' '.
               &mt('For each new section enter the institutional section code (e.g., 004), and the LON-CAPA section ID you wish to assign to students who will be enrolled in your LON-CAPA class as a result of their registration in this particular section.').' '.
               &mt('The LON-CAPA section ID can be left blank, if you do not wish to designate a section ID for this course section.').' '.
               &mt("The institutional section code should only contain letters and/or numbers, and must be consistent with the scheme adopted by your Domain Coordinator to map course section numbers to your institution's student information system.").'
               <br /><br />
           <form name="enter" method="post" action="">
           <table border="0" cellpadding="2" cellspacing="2" width="100%">
             <tr>
              <td>'.
            &Apache::loncommon::start_data_table().
            &Apache::loncommon::start_data_table_row().'
                 <th>'.&mt('Section number').'</th>
                 <th>'.&mt('LON-CAPA section ID').'</th>'.
            &Apache::loncommon::end_data_table_row();
	    for (my $i=0; $i<$numsec; $i++) {
                $response .= &Apache::loncommon::start_data_table_row().'
                 <td><input type="text" size="10" name="newsec_'.$i.'" /></td>
                 <td align="right">
                   <input type="text" size="10" name="newlcsec_'.$i.'" />
                 </td>
                '.&Apache::loncommon::end_data_table_row();
	    }
            $response .= &Apache::loncommon::end_data_table().'
              </td>
             </tr>
             <tr>
              <td align="right">
               <input type="button" name="newsections" value="'.&mt('Go').'" onclick="'."process('newsections')".'" />
              </td>
             </tr>
            </table>
            <input type="hidden" name="numsec" value="'.$numsec.'" />
            <input type="hidden" name="action" value="newsections" />
            <input type="hidden" name="state" value="process" />
            </form>
	    ';
	}
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub print_sections_response {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my %settings = &Apache::lonnet::get('environment',
                       ['internal.sectionnums','internal.coursecode',
                        'internal.courseowner','internal.co-owners'],
                       $dom,$crs);
    my (@currsections,@sections,@allsections,@badowner,@badsections,
        @reserved,@matchgroup,$response,$putreply,$warning,$warn_prefix); 
    my $numsec = 0;
    my $secstr =  $settings{'internal.sectionnums'};
    my $coursecode = $settings{'internal.coursecode'};
    my $owner = $settings{'internal.courseowner'};
    my $coowners = $settings{'internal.co-owners'};
    if ($secstr ne '') {
	@allsections = split(/,/,$secstr);
    }
    if ( exists($env{'form.numsec'}) ) {
	$numsec = $env{'form.numsec'};
    }
    if ($numsec > 0) {
        my %curr_groups = &Apache::longroup::coursegroups();
	for (my $i=0; $i<$numsec; $i++) {
	    my $sec = "newsec_".$i;
	    my $lc_sec = "newlcsec_".$i;
	    if ( exists($env{"form.$sec"}) ) {
		unless ( (grep/^\Q$env{"form.$sec"}:\E/,@allsections) || 
                         (grep/^\Q$env{"form.$sec"}:\E/,@sections) ) {
                    my $lc_sec_check = &validate_lcsec(\%curr_groups,                                                     $env{"form.$lc_sec"});
                    if ($lc_sec_check eq 'reserved') {
                        push(@reserved,$env{"form.$sec"}.":".$env{"form.$lc_sec"});
                        next;
                    } elsif ($lc_sec_check eq 'group') {
                        push(@matchgroup,$env{"form.$sec"}.":".$env{"form.$lc_sec"});
                        next;
                    }
                    my $newsec;
                    my $crskey = $crs.':'.$coursecode;
                    my %formattedsec = &Apache::lonnet::auto_instsec_reformat($dom,'clutter',
                                                                  {$crskey => [$env{"form.$sec"}]});
                    if (ref($formattedsec{$crskey}) eq 'ARRAY') {
                        $newsec = $coursecode.$formattedsec{$crskey}->[0];
                    } else {
                        $newsec = $coursecode.$env{"form.$sec"};
                    }
		    my $coursecheck = &Apache::lonnet::auto_validate_courseID($crs,$dom,$newsec);
		    if ($coursecheck eq 'ok') {
			my $addcheck = &Apache::lonnet::auto_new_course($crs,$dom,$newsec,$owner,$coowners);
			if ($addcheck eq 'ok') {
			    push(@sections,$env{"form.$sec"}.":".$env{"form.$lc_sec"});
			} else {
			    push(@badowner,$env{"form.$sec"}.":".$env{"form.$lc_sec"});
			}
		    } else {
			push(@badsections,$env{"form.$sec"}.":".$env{"form.$lc_sec"}.":".$coursecheck);
		    }
		}
	    }
	}
	push(@allsections,@sections);
    }
    
    if (@sections > 0) {
	unless ($secstr eq '') { $secstr .= ","; } 
	$secstr .= join(',',@sections);
	my %cenv = ('internal.sectionnums' => $secstr);
	$putreply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
	if ($putreply ne 'ok') {
	    $response = &mt('There was a problem processing your requested changes.').' '.
                        &mt('The automated enrollment settings for this course have been left unchanged.').
                        '<br /><br />';
	}
    }

    if ($putreply eq 'ok') {
	$response = &mt('Students enrolling in the sections listed below will be automatically added to the class roster for LON-CAPA course [_1], if you have chosen to enable a nightly automated enrollment update.',
                        "$realm ($coursecode)").'<br /><ul>'."\n";
	foreach my $section (@allsections) {
	    my ($sec,$lc_sec) = split(/:/,$section);
	    $response .= '<li>'.&mt('[_1] - ID: [_2]',$sec,$lc_sec).'</li>'.
                         "\n";
	}
	$response .= '</ul><br /><br />'."\n";
    }

    if (@badsections > 0) {
	$response .= &mt("The sections listed below could not be included in the sections for this LON-CAPA course, because they are not valid section numbers according to your institution's official schedule of classes and sections.").
                     '<br /><ul>'."\n";
	foreach my $item (@badsections) {
	    my ($secnum,$lc_sec,$prob) = split(/:/,$item);
	    $response .= '<li>'.
                         &mt('[_1] - ID: [_2] - Error: [_3]',
                             $secnum,$lc_sec,$prob).
                         '</li>'."\n";
	}
	$response .= '</ul><br /><br />'."\n";
    }

    if (@badowner > 0) {
	$response .= &mt("The sections listed below could not be included in the sections for this LON-CAPA course, because the owner of this course - [_1] - does not have rights to view enrollment in those classes as determined by your instititution's policies on access to official classlists.",$owner).
                     '<br /><ul>'."\n";
	foreach my $item (@badowner) {
	    my ($secnum,$lc_sec) = split(/:/,$item);
	    $response .= '<li>'.&mt('[_1] - ID: [_2]',$secnum,$lc_sec).'</li>'.
                         "\n";
	}
	$response .= '</ul><br /><br />'."\n";
    }

    if (@reserved > 0) {
        $response .= &mt('The sections listed below could not be included in the sections for this LON-CAPA course, because the section ID associated with the institutional section is a reserved word.').' '.
                     &mt('Please [_1]go back[_2] and change the section ID for each of these sections.',
                        '<a href="javascript:history.go(-1)">','</a>').
                     '<br /><ul>'."\n";
        foreach my $xl (@reserved) {
            my ($xlist,$lc_sec) = split(/:/,$xl);
            $response .= '<li>'.
                         &mt('[_1] - ID: [_2]',$xlist,$lc_sec).
                         '</li>'."\n";
        }
        $response .= "</ul><br /><br />\n";
    }
                                                                                 
    if (@matchgroup > 0) {
        $response .= &mt('The sections listed below could not be included in the sections for this LON-CAPA course, because the section ID associated with the institutional section is the name of a group in this course.').' '.
                     &mt('Please [_1]go back[_2] and change the section ID for each of these sections.','<a href="javascript:history.go(-1)">','</a>').
                     '<br /><ul>'."\n";
        foreach my $section (@matchgroup) {
            my ($xlist,$lc_sec) = split(/:/,$section);
            $response .= '<li>'.&mt('[_1] - ID: [_2]',$xlist,$lc_sec).
                         '</li>'."\n";
        }
        $response .= '</ul><br /><br />'."\n";
    }
    if (@allsections > 0) {
	$warning = &warning_message($dom,$crs,$action);
        unless ($warning eq '') {
	    '<br />'.
            '<span class="LC_warning"><b>'.&mt('Warning.').'</b> '."\n".
            &mt('Although you have selected sections to contribute enrollment to this course, additional action is required.').'<span><br />'.$warning;
	}
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub photo_permission {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my %settings = &Apache::lonnet::get('environment',
					['internal.courseowner',
					 'internal.photopermission',
					 'internal.showphoto'],
					$dom,$crs);
    my ($showphotos,$response);
    if (exists($env{'form.cancel_agreement'})) {
        if (&user_is_courseowner($settings{'internal.courseowner'})) {
            my %cenv = (
                'internal.photopermission' => 'no',
            );
            my $reply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
            if ($reply ne 'ok') {
                $response = 
                    &mt('There was a problem processing the record of your agreement to the conditions of use.').' '.
                    &mt('Settings for this course have been left unchanged.').'<br />'."\n";
                &print_reply($r,$response,$$tasktitleref{$action});
            } else {
                &print_photos_response($r,$realm,$dom,$crs,$action,
                       $tasktitleref,$showphotos,'no',\%cenv);
            }
            return;            
        }
    } 
    if (exists($env{'form.showphotos'})) {
        $showphotos=$env{'form.showphotos'};
    }
    if ($showphotos) {
        if ($env{'form.photopermission'}) {
            my %cenv = (
                'internal.photopermission' => $env{'form.photopermission'},
            );
            my $reply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
            if ($reply ne 'ok') {
                $response = 
                    &mt('There was a problem processing the record of your agreement to the conditions of use.').' '.
                    &mt('Settings for this course have been left unchanged.').'<br />'."\n";
            } else {
                &print_photos_response($r,$realm,$dom,$crs,$action,
				       $tasktitleref,$showphotos,
				       $env{'form.photopermission'},\%cenv);
            }
        } else {
            my ($result,$perm_reqd,$conditions) = 
		&Apache::lonnet::auto_photo_permission($crs,$dom);
            my $permcheck;
            if ($result eq 'ok') { 
                if ($perm_reqd eq 'yes') {
                    if ($settings{'internal.photopermission'} eq 'yes') {
                        &print_photos_response($r,$realm,$dom,$crs,$action,
					       $tasktitleref,$showphotos);
                    } else {
                        return(&print_photo_agreement($r,$realm,$dom,$crs,
						      $action,$tasktitleref,
						      $conditions,
						      $settings{'internal.courseowner'}));
                    }
                } elsif ($perm_reqd eq 'no') {
                    &print_photos_response($r,$realm,$dom,$crs,$action,
					   $tasktitleref,$showphotos);
                } else {
                    $permcheck = 'fail';
                }
            } else {
                $permcheck = 'fail';
            }
            if ($permcheck eq 'fail') {
                my $response = 
                    &mt('There was a problem processing your requested change, because it could not be determined whether course owner permission is required in order for a course coordinator to have access to student photos in this domain.').' '.
                    &mt('The student photo import setting for this course has been left unchanged.').'<br />';
                &print_reply($r,$response,$$tasktitleref{$action});
            }
        }
    } else {
        &print_photos_response($r,$realm,$dom,$crs,$action,$tasktitleref);
    }
    return;
}

sub print_photo_agreement {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref,$conditions,$courseowner)=@_;
    my $response;
    my $institution = &Apache::lonnet::domain($dom,'description');
    if (&user_is_courseowner($courseowner)) {
        $response = '
<script type="text/javascript" language="JavaScript">
function agreement_result(caller) {
    document.permission.photopermission.value = caller;
    if (caller == 0) {
        document.location.href="/adm/populate";
    } else {
        document.permission.submit();
    }
    return;
}
</script>
  <form name="permission" method="post" action="">
   <table width="100%" border="0" cellpadding="2" cellspacing="2">
    <tr>
     <td align="left"><b>'.&mt('Use of student photos').'</b><br />'."\n".
      &mt('Acceptance by the course owner of the conditions of use of photos is currently [_1]not[_2] set.','<b>','</b>').'<br />'.
      &mt('Please indicate your acceptance of the conditions of use of digital photos of registered students in courses at [_1].',$institution).'
     </td>
    </tr>
   </table>
   <table border="0" cellpadding="3" cellspacing="3">
    <tr>
     <td colspan="2">
      <textarea rows="20" cols="80">'.$conditions.'</textarea>
     </td>
     <tr>
      <td align="left">  
       <input type="button" name="disagree" value="'.&mt('I do not agree').'" onclick="javascript:agreement_result('."'no'".');" />
      </td>
      <td align="right">
       <input type="button" name="agree" value="'.&mt('I agree').'" onclick="javscript:agreement_result('."'yes'".');" />
      </td>
    </tr>
   </table>
   <input type="hidden" name="action" value="'.$action.'" />
   <input type="hidden" name="state" value="process" />
   <input type="hidden" name="showphotos" value="1" />
   <input type="hidden" name="photopermission" value="" />
  </form>
';
    } else {
        my ($ownername,$owneremail) = &get_ownerinfo($dom,$courseowner);
        my $emailstr;
        if ($owneremail) {
            $emailstr = &mt('(e-mail: [_1])',$owneremail);
        }
        $response = &mt('The policies of your institution [_1] require that the course owner [_2] must indicate acceptance of the conditions of use of digital photos of registered students, before they may be made available for use in a course.',$institution,$ownername)
                   .'<br /><br />'
                   .&mt('Please direct the course owner [_1] to visit the "Student photos" page in the Automated Enrollment Manager to indicate acceptance of these conditions of use.',$emailstr);
    }
    &print_reply($r,$response,$$tasktitleref{$action});
}

sub print_photos_response {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref,$showphotos,$photopermission,
	$permissionenv)=@_;
    my %newenv;
    if (defined($permissionenv)) {
        foreach my $key (keys(%{$permissionenv})) {
            if (exists($env{'request.course.id'})) {
                $newenv{$env{'request.course.id'}.'.'.$key} =
		    $$permissionenv{$key};
            }
        }
    }
    my %settings = &Apache::lonnet::get('environment',['internal.showphoto'],
					$dom,$crs);
    my $currphotos = $settings{'internal.showphoto'};
    my $response = "";
    if (defined($photopermission)) {
        if ($photopermission eq 'yes') {
            $response = &mt('Acceptance of photo use policy recorded.').'<br />'."\n";
        } else {
            $response = &mt('Rejection of photo use policy recorded.').'<br />'."\n";
            $showphotos = 0;
        }
    }
    my %cenv = ('internal.showphoto' => $showphotos);
    my $reply = &Apache::lonnet::put('environment',\%cenv,$dom,$crs);
    if ($reply ne 'ok') {
	$response .= &mt('There was a problem processing your requested change.').' '.
                     &mt('The student photo retrieval setting for this course has been left unchanged.').'<br />';
    } else {
	if ($showphotos) {
	    if ($currphotos) {
		$response .= &mt('Retrieval of student photos is still [_1]enabled[_2].','<b>','</b>').'<br />';
	    } else {
		$response .= &mt('Retrieval of student photos in now [_1]enabled[_2].','<b>','</b>').'<br />';
                my ($update,$commentary) = 
		    &Apache::lonnet::auto_photochoice($crs,$dom);
                if ($update) {
                    $response .= '<br />'.$commentary.'<br /><br />
<form name="photoupdate" method="post" action="">
<input type="button" name="retrieve" value="'.&mt('Update photo repository').'" 
onclick="javascript:document.photoupdate.submit()" /> 
<input type="hidden" name="action" value="'.$action.'" />
<input type="hidden" name="state" value="photoupdate" />
</form>';
                }
	    }
	} else {
	    if ($currphotos) {
		$response .= &mt('Retrieval of student photos is now [_1]disabled[_2].','<b>','</b>').'<br />';
	    } else {
		$response .= &mt('Retrieval of student photos is still [_1]disabled[_2].','<b>','</b>').'<br />';
	    }
	}
        foreach my $key (keys(%cenv)) {
            if (exists($env{'request.course.id'})) {
                $newenv{'course.'.$env{'request.course.id'}.'.'.$key} = 
		    $cenv{$key};
            }
        }
    }
    if (keys(%newenv) > 0) {
        &Apache::lonnet::appenv(\%newenv);
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub print_photoupdate_response {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my ($response,$outcome,%changes,@allcourses,%LC_code,%affiliates);
    my %lt = &LONCAPA::Enrollment::photo_response_types();
    my %settings = &Apache::lonnet::get('environment',
					['internal.coursecode',
					 'internal.sectionnums',
					 'internal.crosslistings'],
					$dom,$crs);
    &Apache::loncommon::get_institutional_codes($dom,$crs,\%settings,\@allcourses,\%LC_code);
    if (@allcourses > 0) {
        @{$affiliates{$crs}} = @allcourses;
        $outcome = &Apache::lonnet::auto_photoupdate(\%affiliates,$dom,$crs,\%changes);
        unless ($outcome eq 'ok') {
            &Apache::lonnet::logthis("lonpopulate::print_photoupdate_response".
				     "failed to update student photos".
				     " for ".$crs."\@".$dom." by ".
				     $env{'user.name'}." \@ ".$env{'user.domain'}.
				     ": ".$outcome);
        }
        if ($outcome eq 'ok') {
            if (keys(%changes) > 0) {
                $response = &mt('Update of photos for registered students resulted in the following ').': <br />'
                           .'<script type="text/javascript" language="JavaScript">
function photowindow(photolink) {
    var title = "Photo_Viewer";
    var options = "scrollbars=1,resizable=1,menubar=0";
    options += ",width=240,height=240";
    stdeditbrowser = open(photolink,title,options,"1");
    stdeditbrowser.focus();
}
</script>
';
                foreach my $type (sort(keys(%changes))) {
                    my @usernames = sort(split(/\&/,$changes{$type})); 
                    my $count = @usernames; 
                    $response .= '<b>'.&mt('For [quant,_1,student], photos [_2]',
					   $count,$lt{$type}).'</b><ul>';
                    foreach my $username (@usernames) {
                        $response .= '<li>'.$username;
                        if (($type eq 'new') || ($type eq 'same') || ($type eq 'update')) {
                            $response .= '&nbsp;<a href="javascript:photowindow('."'".&Apache::lonnet::studentphoto($dom,$username,'jpg')."'".')">'.&mt('View').'</a></li>';
                        }
                    }
                    $response .= '</ul><br />';
                }
            } else {
                $response = &mt('No updates of photos of registered students occurred').
                         '<br />';
            }    
        } else {
            $response = &mt('There was a problem updating student photos for registered students in this course.').'<br />';
        }
    } else {
        $response = &mt('No institutional course sections are currently associated with this course so there are no registered students for whom photos can be imported/updated.');
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub get_ownerinfo {
    my ($dom,$owner) = @_; 
    my ($ownername,$owneremail,$own_uname,$own_udom);
    if ($owner) {
        if ($owner =~ /^([^:]+):([^:]+)$/) {
            $own_uname = $1;
            $own_udom = $2; 
        } else {
            $own_uname = $owner;
            $own_udom = $dom; 
        }
        $ownername=&Apache::loncommon::plainname($own_uname,$own_udom,
                                                 'firstname');
        my %ownerinfo = &Apache::lonnet::get('environment',['permanentemail'],
					     $own_udom,$own_uname);
        $owneremail = $ownerinfo{'permanentemail'};
    }
    return ($ownername,$owneremail);
}

sub print_update_result {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my ($response,$logmsg,$newusermsg,%affiliates,%reply,@allcourses,
        %LC_code,%phototypes);
    my $updateadds = 0;
    my $updatedrops = 0;
    my $changecount = 0;
    my %settings = 
        &Apache::lonnet::get('environment',
            ['internal.coursecode','internal.sectionnums','internal.crosslistings',
             'internal.authtype','internal.autharg','internal.showphoto','internal.defaultcredits',
             'internal.autodropfailsafe','internal.autodropfailsafetype','internal.textbook'],
            $dom,$crs);
    my $coursecode = $settings{'internal.coursecode'};
    my $authtype = $settings{'internal.authtype'};
    my $autharg = $settings{'internal.autharg'};
    my $showphotos = $settings{'internal.showphoto'};
    my $textbook = $settings{'internal.textbook'};
    my ($showcredits,$defaultcredits);
    my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
    if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'} || $domdefaults{'textbookcredits'}) {
        $showcredits = 1;
        $defaultcredits = $settings{'internal.defaultcredits'};
        if ($defaultcredits eq '') {
            if ($coursecode ne '') {
                $defaultcredits = $domdefaults{'officialcredits'};   
            } elsif ($textbook ne '') {
                $defaultcredits = $domdefaults{'textbookcredits'};
            } else {
                $defaultcredits = $domdefaults{'unofficialcredits'};
            }
        }
    }
    my $failsafetype = $settings{'internal.autodropfailsafetype'};
    if ($failsafetype eq '') {
        $failsafetype = $domdefaults{'failsafe'};
    }
    my $failsafe = $settings{'internal.autodropfailsafe'};
    if ($failsafe eq '') {
        $failsafe = $domdefaults{'autofailsafe'};
    }
    my ($startaccess,$endaccess) = &get_dates_from_form();
    if ( exists($env{'form.updateadds'}) ) {
        $updateadds = $env{'form.updateadds'};
    }
    if ( exists($env{'form.updatedrops'}) ) {
        $updatedrops = $env{'form.updatedrops'};
    }
    if (($startaccess eq '') || ($endaccess eq '')) {
        $response = &mt('There was a problem processing your requested roster update because start and and access dates could not be determined.').' '.
                    &mt('No changes have been made to the class roster.').
                    '<br />'; 
    } elsif ($updateadds && (($endaccess > 0) && ($endaccess <= $startaccess))) {
        $response = &mt('The start access date/time is the same or later than the end access date/time.').' '.
                    &mt('As this means that new roles will never be active, your requested roster update has not been carried out, and the roster remains unchanged.').' '.
                    &mt('Please [_1]go back[_2] to the previous page to try your changes again.',
                        '<a href="javascript:history.go(-1)">','</a>')."\n";
    } elsif (!$updateadds && !$updatedrops) {
	$response = &mt('An update of the class roster has not been carried out because you indicated that you wanted to neither add new students, nor expire dropped students based on a comparison between the institutional class lists for the course sections and crosslisted courses that contribure enrollment to this LON-CAPA course.');
    } elsif ($coursecode eq '') {
	$response = &mt('There was a problem retrieving the course code for this LON-CAPA course.').' '.
                    &mt('An update of the class roster has not been carried out, and enrollment remains unchanged.');
    } else {
        &Apache::loncommon::get_institutional_codes($dom,$crs,\%settings,\@allcourses,\%LC_code);
	if (@allcourses > 0) {
	    @{$affiliates{$crs}} = @allcourses;
	    my $outcome = &Apache::lonnet::fetch_enrollment_query('updatenow',\%affiliates,\%reply,$dom,$crs);
            unless ($outcome eq 'ok') {
                &Apache::lonnet::logthis("lonpopulate:update roster".
                                         "failed to retrieve classlist".
                                 " data for ".$crs.':'.$dom." by ".
                                 $env{'user.name'}." \@ ".$env{'user.domain'}.
                                 ": ".$outcome);
            }
	    if ($reply{$crs} > 0) {
		($changecount,$response) = &LONCAPA::Enrollment::update_LC($dom,$crs,$updateadds,$updatedrops,$startaccess,$endaccess,$authtype,$autharg,$showcredits,$defaultcredits,$failsafe,$failsafetype,\@allcourses,\%LC_code,\$logmsg,\$newusermsg,"updatenow",\%phototypes);
	    } else {
		$response = &mt('There was a problem retrieving institutional class list data for the course sections and crosslisted courses which contribute enrollment to this course.').' '.
                            &mt('No updates have been carried out, and the roster remains unchanged.');
	    }  
	} else {
	    $response = &mt('There are currently no course sections or crosslisted courses designated as contributors to enrollment in this LON-CAPA course.').' '.
                        &mt('As a result a student roster update has not been carried out for [_1].',"$realm ($coursecode)");
	}
    }
    unless ($logmsg eq '') {
	my $loglength = length($logmsg);
	$logmsg = substr($logmsg,0,$loglength-4);
	$logmsg = '<br /><br />'.&mt('The following messages were generated by the roster update process: [_1]','<br /><ul><li>'.$logmsg.'</ul><br />');
    }
    unless ($newusermsg eq '') {
	$newusermsg = substr( $newusermsg,0,rindex($newusermsg,'<li>') );
	$newusermsg = '<br /><br />'.
                      &mt('The following new system user(s) who was/were created will be using local or internal authentication with an initial randomly generated password.').' '.
                      &mt('A valid e-mail address was not available for this/these user(s) so LON-CAPA account credentials could not be sent via e-mail.').
                      '<br /><ul><li>'.$newusermsg.'</ul><br />';
    }
    $response .= $logmsg.$newusermsg;
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub print_viewclass_response {
    my ($r,$realm,$dom,$crs,$action,$tasktitleref) = @_;
    my ($response,%chg,%nochg,%otherdom,%lockchg,%nolockchg);
    my $chgtotal = 0;
    my $chgok = 0;
    my $chgfail = 0;
    my $othdom = 0;
    my $locktotal = 0;
    my $lockok = 0;
    my $lockfail = 0;
    my $cid = $dom.'_'.$crs;
    my $classlist = &Apache::loncoursedata::get_classlist($dom,$crs);
    my $endidx = &Apache::loncoursedata::CL_END;
    my $startidx = &Apache::loncoursedata::CL_START;
    my $ididx=&Apache::loncoursedata::CL_ID;
    my $secidx=&Apache::loncoursedata::CL_SECTION;
    my $typeidx=&Apache::loncoursedata::CL_TYPE;
    my $lockedidx=&Apache::loncoursedata::CL_LOCKEDTYPE;
    my $creditsidx=&Apache::loncoursedata::CL_CREDITS;
    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                               ['chgauto','chgmanual','lockchg','unlockchg']);
    my @typechglist = (&Apache::loncommon::get_env_multiple('form.chgauto'),
		       &Apache::loncommon::get_env_multiple('form.chgmanual'));
    my @lockchglist = (&Apache::loncommon::get_env_multiple('form.lockchg'),
		       &Apache::loncommon::get_env_multiple('form.unlockchg'));

    foreach my $student (sort(@typechglist)) {
        my ($uname,$udom) = split(/:/,$student);
        my $sdata    = $classlist->{$student};
        my $section  = $sdata->[$secidx];
        my $uid       = $sdata->[$ididx];
        my $start    = $sdata->[$startidx];
        my $end      = $sdata->[$endidx];
        my $type     = $sdata->[$typeidx];
        my $lock   = $sdata->[$lockedidx];
        my $credits = $sdata->[$creditsidx];
        my $newlock = $lock;
        $chgtotal ++;
        my $newtype = 'auto';
        my $change = 'auto';
        my $oldtype = 'manual';
        if ($type eq 'auto') { 
            $oldtype = 'auto';
            $newtype = '';
            $change = 'manual';
        }
        if ($udom eq $dom) {
            if ($newtype eq 'auto') {
                $newlock = '';
            } elsif ($newtype eq '') {
                $newlock = '1';
            }
            my $modreply = 
                &Apache::lonnet::modify_student_enrollment($udom,$uname,$uid,'',
                                                           '','','',$section,$end,
                                                           $start,$newtype,
                                                           $newlock,$cid,'',
                                                           'chgtype',$credits);
            if ($modreply eq 'ok') {
                $chgok ++;
                $chg{$student} = &mt("Changed to $change");
            } else {
                $chgfail ++;
                $nochg{$student} = &mt("Still set to $oldtype");
            } 
        } else {
            $othdom ++;
            $otherdom{$student} = &mt("Still set to $oldtype"); 
        }
    }
    foreach my $student (@lockchglist) {
        my ($uname,$udom) = split(/:/,$student);
        my $sdata    = $classlist->{$student};
        my $section  = $sdata->[$secidx];
        my $uid       = $sdata->[$ididx];
        my $start    = $sdata->[$startidx];
        my $end      = $sdata->[$endidx];
        my $type     = $sdata->[$typeidx];
        my $lock   = $sdata->[$lockedidx];
        my $credits = $sdata->[$creditsidx];
        my $newlock = 1;
        my $oldlockname = &mt('unlocked');
        my $newlockname = &mt('locked');
        $locktotal++;
        unless ($type eq 'auto') {
            if ($lock) {
                $newlock = '';
                $newlockname = &mt('unlocked');
                $oldlockname = &mt('locked'); 
            }
            my $lockreply = &Apache::lonnet::modify_student_enrollment($udom,$uname,$uid,'','','','',$section,$end,$start,$type,$newlock,$cid,'','chgtype',$credits);
            if ($lockreply eq 'ok') {
                $lockok ++;
                $lockchg{$student} = &mt('Changed to [_1]',$newlockname);
            } else {
                $lockfail ++;
                $nolockchg{$student} = &mt('Still set to [_1]',$oldlockname);
            }
        }
    }
    if ($chgtotal > 0) {
        $response = &mt('You requested a change in enrollment type for [quant,_1,student].',$chgtotal).'<br /><br />'."\n";
        $classlist = &Apache::loncoursedata::get_classlist($dom,$crs);
        if ($chgok > 0) {
            $response .= &mt('The following [quant,_1,change was,changes were] successful;',$chgtotal).':<br /><br />';
            $response .= &enrolltype_result(\%chg,$classlist,$endidx,$startidx,$ididx,$secidx,$typeidx);
        }
        if ($chgfail > 0) {
            $response .= &mt('The following [quant,_1,student was,students were] not modified successfully',$chgfail).':&nbsp;<br />';
            $response .= &enrolltype_result(\%nochg,$classlist,$endidx,$startidx,$ididx,$secidx,$typeidx);
        }
        if ($othdom > 0) {
            $response .= &mt("The following [quant,_1,student was,students were] not modified because students must be in the same LON-CAPA domain as the course, in order to be set to an enrollment type of 'auto'",$othdom).':<br />'; 
            $response .= &enrolltype_result(\%otherdom,$classlist,$endidx,$startidx,$ididx,$secidx,$typeidx);
        }
        $response .= '<br /><br />';
    }
    if ($locktotal > 0) {
        $response .= &mt('You requested locking/unlocking for [quant,_1,manually enrolled student]',$locktotal).'<br /><br />'."\n";
        $classlist = &Apache::loncoursedata::get_classlist($dom,$crs);
        if ($lockok > 0) {
            $response .= &mt('The following [quant,_1,change was,changes were] successful',$lockok).':<br /><br />';
            $response .= &enrolltype_result(\%lockchg,$classlist,$endidx,$startidx,$ididx,$secidx,$typeidx,$lockedidx);
        }
        if ($lockfail > 0) {
            $response .= &mt('The following [quant,_1,student was,students were] not modified successfully',$lockfail).':&nbsp;<br />';
            $response .= &enrolltype_result(\%nolockchg,$classlist,$endidx,$startidx,$ididx,$secidx,$typeidx,$lockedidx);
        }
    }
    &print_reply($r,$response,$$tasktitleref{$action});
    return;
}

sub enrolltype_result {
    my ($changes,$classlist,$endidx,$startidx,$ididx,$secidx,$typeidx,$lockedidx) = @_;
    my $reply = &Apache::loncommon::start_data_table().
                &Apache::loncommon::start_data_table_header_row().'
              <th>'.&mt('username').'</th>
              <th>'.&mt('domain').'</th>
              <th>'.&mt('ID').'</th>
              <th>'.&mt('student name').'</th>
              <th>'.&mt('section').'</th>
              <th>'.&mt('start date').'</th>
              <th>'.&mt('end date').'</th>
              <th>'.&mt('enrollment change').'</th>'."\n".
                &Apache::loncommon::end_data_table_header_row();
    foreach my $chg (sort(keys(%{$changes}))) {
        my $sdata  = $classlist->{$chg};
        my ($uname,$udom) = split(/:/,$chg);
        my $section  = $sdata->[$secidx];
        my $uid      = $sdata->[$ididx];
        my $start    = $sdata->[$startidx];
        my $end      = $sdata->[$endidx];
        my $type     = $sdata->[$typeidx];
        if (! defined($start) || $start == 0) {
            $start = &mt('none');
        } else {
            $start = &Apache::lonlocal::locallocaltime($start);
        }
        if (! defined($end) || $end == 0) {
            $end = &mt('none');
        } else {
            $end = &Apache::lonlocal::locallocaltime($end);
        }
        if (!defined($section) || ($section eq '')) {
            $section = '&nbsp;';
        }
        if (!defined($uid) || ($uid eq '')) {
            $uid = '&nbsp;';
        }
        $reply .= &Apache::loncommon::start_data_table_row().' 
              <td>'.$uname.'</td>
              <td>'.$udom.'</td>
              <td>'.$uid.'</td>
              <td>'.&Apache::loncommon::plainname($uname,$udom).'</td>
              <td>'.$section.'</td>
              <td>'.$start.'</td>
              <td>'.$end.'</td>
              <td>'.$$changes{$chg}.'</td>'."\n".
             &Apache::loncommon::end_data_table_row();
    }
    $reply .= &Apache::loncommon::end_data_table();
    return $reply;
}

sub warning_message {
    my ($dom,$crs,$caller) = @_;
    my %settings = 
        &Apache::lonnet::get('environment',
             ['internal.autoadds','internal.autodrops','internal.sectionnums',
              'internal.crosslistings','internal.autostart','internal.autoend'],
             $dom,$crs);
    my ($currend,$currstart,$currsecs,$currxlists,$curradds,$currdrops);
    if ( defined($settings{'internal.autoadds'}) ) {
        $curradds = $settings{'internal.autoadds'};
    }
    if (defined($settings{'internal.autodrops'}) ) {
        $currdrops = $settings{'internal.autodrops'};
    }
    if ( defined($settings{'internal.autostart'}) ) {
        $currstart = $settings{'internal.autostart'};
    }
    if ( defined($settings{'internal.autoend'}) ) {
        $currend = $settings{'internal.autoend'};
    }
    if ( defined($settings{'internal.sectionnums'}) ) {
        $currsecs = $settings{'internal.sectionnums'};
    }
    if ( defined($settings{'internal.crosslistings'}) ) {
        $currxlists = $settings{'internal.crosslistings'}
    }
    my $warning = '';
    unless ($caller eq 'setdates') {
        if ( ($currstart eq '') && ($currend eq '') )  {
            $warning .= '<li>'.
                &mt("You [_1]must[_2] now use [_3]Change enrollment dates[_4] to set a start date [_5]and[_6] an end date for the enrollment (or check the 'No end date' checkbox) for the nightly adds process to actually occur.",'<b>','</b>','<a href="/adm/populate?action=setdates">','</a>'.'<i>','</i>').'</li>';
        }
    }
    unless ( ($caller eq 'sections') || ($caller eq 'crosslist') ) {
        if ( ($currsecs eq '') && ($currxlists eq '') ) {
            $warning .= '<li>'.
                &mt('You [_1]must[_2] now use [_3]Section settings[_4] and/or [_5]Change crosslistings[_4] to choose at least one section of the course, or at least one crosslisted course which will contribute enrollment to this LON-CAPA course.','<b>','</b>','<a href="/adm/populate?action=sections">','</a>','<a href="/adm/populate?action=crosslist">').' '.
                        &mt('At present there are [_1]NO[_2] sections or crosslisted courses that are affiliated with this course that are set to contribute to the automated enrollment process.','<b>','</b>').'</li>';
        }
    }
    unless ( $caller eq 'chgsettings') {
        if ( (!$curradds) && (!$currdrops) ) {
            $warning .= '<li>'.
                &mt('You [_1]must[_2] now use [_3]Automated adds/drops[_4] to enable automated adds and/or drops if you want automatic enrollment updates to occur in this course.','<b>','</b>','<a href="/adm/populate?action=chgsettings">','</a>').'</li>';
        }
    }
    if ($warning) {
        return '<p class="LC_info"><ul>'.$warning.'</ul></p>';
    }
    return;
}

sub print_reply {
  my ($r,$response,$caller) = @_;
  $r->print('
            <br /><table width="100%" border="0" cellpadding="2" cellspacing="2">
             <tr>
              <td align="left"><b>'.$caller.'</b> - '.&mt('result').'
              <br /><br />'.$response.'</td>
             </tr>
            </table>
  ');
  return;
}

sub setup_date_selectors {
    my ($starttime,$endtime,$action,$readonly) = @_;
    my $disabled;
    if ($readonly) {
        $disabled = 'disabled';
    }
    if (! defined($starttime)) {
        $starttime = time;
        if ($action eq 'setdates') {
            if (exists($env{'course.'.$env{'request.course.id'}.
                            '.default_enrollment_start_date'})) {
                $starttime = $env{'course.'.$env{'request.course.id'}.
                                  '.default_enrollment_start_date'};
            }
        }
    }
    if (! defined($endtime)) {
        $endtime = time+(6*30*24*60*60); # 6 months from now, approx
        if ($action eq 'setdates') {
            if (exists($env{'course.'.$env{'request.course.id'}.
                            '.default_enrollment_end_date'})) {
                $endtime = $env{'course.'.$env{'request.course.id'}.
                                '.default_enrollment_end_date'};
            }
        }
    }
    my $startdateform = &Apache::lonhtmlcommon::date_setter('enter',
                                                            'startdate',
                                                            $starttime,'','',$disabled);
    my $enddateform = &Apache::lonhtmlcommon::date_setter('enter',
                                                          'enddate',
                                                          $endtime,'','',$disabled);
    return ($startdateform,$enddateform);
}

sub get_dates_from_form {
    my ($startdate,$enddate);
    $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate');
    $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate');
    if ( exists ($env{'form.no_end_date'}) ) {
        $enddate = 0;
    }
    return ($startdate,$enddate);
}

sub date_setting_table {
    my ($starttime,$endtime,$action,$readonly) = @_;
    my $disabled;
    if ($readonly) {
        $disabled = ' disabled="disabled"';
    }
    my ($startform,$endform) = 
        &setup_date_selectors($starttime,$endtime,$action,$readonly);
    my $perpetual = '<span class="LC_nobreak"><label>'.
                    '<input type="checkbox" name="no_end_date"';
    if (($action eq 'setdates' && defined($endtime) && $endtime == 0) || 
        (($action eq 'setaccess' || $action eq 'updatenow') && 
         ($endtime eq '' || $endtime == 0)) ) {
        $perpetual .= ' checked="checked"';
    }
    $perpetual.= $disabled.' /> '.&mt('no end date').'</label></span>';
    my $start_table = "<table>\n".
                      '<tr><td align="right">'.&mt('Starting Date').'</td>'.
                      '<td>'.$startform.'</td>'.
                      '<td>&nbsp;</td>'."</tr>\n".
                      "</table>";
    my $end_table = "<table>\n".
                    '<tr><td align="right">'.&mt('Ending Date').'</td>'.
                    '<td>'.$endform.'</td>'.
                    '<td>'.$perpetual.'</td>'."</tr>\n".
                    "</table>\n";
    return ($start_table, $end_table);
}

sub validate_lcsec {
    my ($curr_groups,$lcsec) = @_;
    if (($lcsec eq 'all') || ($lcsec eq 'none')) {
        return 'reserved';
    } else {
        if (exists($$curr_groups{$lcsec})) {
            return 'group'; 
        }
    }
    return 'ok';
}

sub user_is_courseowner {
    my ($courseowner) = @_;
    my $user;
    if ($courseowner =~ /^[^:]+:[^:]+$/) {
	$user = $env{'user.name'}.':'.$env{'user.domain'};
    } else {
	$user = $env{'user.name'};
    }
    return ($user eq $courseowner);
}

sub get_task_text {
    my ($permref) = @_;
    my %tasklong =
        &Apache::lonlocal::texthash(
           information   => 'Task information',
           chgsettings   => 'Automated adds/drops',
           chgfailsafe   => 'View/change enrollment failsafe',
           setdates      => 'Change enrollment dates',
           setaccess     => 'Change access dates',
           notify        => 'Notification of changes',
           crosslist     => 'Change crosslistings',
           sections      => 'Section settings',
           photos        => 'Student photo settings',
           updatephotos  => 'Update student photos',
           updatenow     => 'Update roster now',
           newcross      => 'Add crosslistings',
           newsections   => 'Add sections',
           viewclass     => 'View students and change type',
    );

    my %tasktitle =
        &Apache::lonlocal::texthash(
           chgsettings  => 'Changes to nightly automated enrollments',
           chgfailsafe  => 'Changes to failsafe protection for data retrieval problems',
           setdates     => 'Changes to first and/or last automated enrollment dates',
           setaccess    => 'Changes to default start and/or end dates for student access',
           notify       => 'Notification of enrollment changes',
           crosslist    => 'Changes to crosslistings',
           sections     => 'Changes to section settings',
           photos       => 'Student photo settings',
           updatephotos => 'Update student photos',
           updatenow => "Immediate course roster update",
           newcross => "Adding new crosslisted courses",
           newsections => "Adding new course sections",
           viewclass => "Viewing class roster and enrollment type"
    );

    if ((ref($permref) eq 'HASH') && (!$permref->{'edit'})) {
        $tasklong{'chgfailsafe'} = &mt('Enrollment failsafe');
        $tasklong{'setdates'}    = &mt('Enrollment dates');
        $tasklong{'setaccess'}   = &mt('Access dates');
        $tasklong{'crosslist'}   = &mt('Crosslistings');
        $tasklong{'viewclass'}   = &mt('View students and type');
    }
    return (\%tasklong,\%tasktitle);
}

sub check_permission {
    my ($permref) = @_;
    return unless (ref($permref) eq 'HASH');
    my $hasaccess;
    if ($env{'request.course.id'}) {
        foreach my $priv ('cst','vpa','vcl') {
            my ($allowed,$section);
            if (&Apache::lonnet::allowed($priv,$env{'request.course.id'})) {
                $allowed = 1;
            } elsif ($env{'request.course.sec'} ne '') {
                if (&Apache::lonnet::allowed($priv,$env{'request.course.id'}.'/'.
                                                   $env{'request.course.sec'})) {
                    $allowed = 1;
                    $section = $env{'request.course.sec'};
                }
            }
            if ($allowed) {
                $hasaccess = 1;
                if ($priv eq 'cst') {
                    if ($section ne '') {
                        $permref->{'edit_section'} = $section;
                    } else {
                        $permref->{'edit'} = 1;
                    }
                } elsif ($priv eq 'vpa') {
                    if ($section ne '') {
                        $permref->{'view_section'} = $section;
                    } else {
                        $permref->{'view'} = 1;
                    }
                } elsif ($priv eq 'vcl') {
                    if ($section ne '') {
                        $permref->{'show_section'} = $section;
                    } else {
                        $permref->{'show'} = 1;
                    }
                }
            }
        }
    }
    return $hasaccess;
}

    
###################################################################
sub handler {
    my $r = shift;
    if ($r->header_only) {
	&Apache::loncommon::content_type($r,'text/html');
        $r->send_http_header;
        return OK;
    }
    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                                            ['action','state']);
    my %permhash;
    #  Needs to be in a course
    if (!($env{'request.course.fn'})) {
        # Not in a course
        $env{'user.error.msg'}="/adm/populate:cst:0:0:Cannot display automated enrollment";
        return HTTP_NOT_ACCEPTABLE;
    } elsif (!&check_permission(\%permhash)) {
        # Not allowed to modify students, view settings, or view classlist.
        $env{'user.error.msg'}="/adm/populate:cst:0:0:Cannot display automated enrollment";
        return HTTP_NOT_ACCEPTABLE; 
    }
    # Start page
    &Apache::loncommon::content_type($r,'text/html');
    $r->send_http_header;

    my @tasks = ('information','chgsettings','setdates','setaccess','notify','crosslist',
                 'sections','photos','updatenow','updatephotos','viewclass','chgfailsafe');
 
    my ($tasklong,$tasktitle) = &get_task_text(\%permhash);
    my $realm;
    if ( exists($env{'request.course.id'}) ) {
        $realm=$env{'course.'.$env{'request.course.id'}.'.description'};
    }
    unless ($realm) { $realm='&nbsp;'; }
    my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
    my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};

    #
    # Main switch on form.action and form.state, as appropriate
    #

    my $action = "information";
    if ( exists($env{'form.action'}) ) {
        $action = $env{'form.action'};
    }
    my $state = "choose";

    if ( exists($env{'form.state'}) ) {
        $state = $env{'form.state'};
    }

    if ($action eq "information") {
        $r->print(&header($action,\%permhash));
    } else {
        if ($state eq "choose") {
            $r->print(&choose_header($action,\%permhash,$dom));
        } else {
            if ($action eq "crosslist") {
                if ( exists($env{'form.numcross'}) ) {
                    if ( $env{'form.numcross'} > 0 ) {
                        $r->print(&choose_header($action,\%permhash,$dom));
                    } else {
                        $r->print(&header($action,\%permhash));
                    }
                } else {
                    $r->print(&header(undef,\%permhash));
                }
            } elsif ($action eq "sections") {
                if ( exists($env{'form.numsec'}) ) {
                    if ( $env{'form.numsec'} > 0 ) {
                        $r->print(&choose_header($action,\%permhash,$dom));
                    } else {
                        $r->print(&header($action,\%permhash));
                    }
                } else {
                    $r->print(&header($action,\%permhash));
                }
            } else {
                $r->print(&header($action,\%permhash));
            }
        }
    }

    my $reply = 0;
    unless ($state eq "choose") { $reply = 1; }

    &print_navmenu($r,\@tasks,$tasklong,$action,$state);

    if (($state eq "choose") || ($action eq "information")) {
        &print_main_frame($r,$realm,$dom,$crs,$tasktitle,\%permhash);
    } elsif (($action eq "chgsettings") && ($permhash{'edit'})) {
        &print_chgsettings_response($r,$realm,$dom,$crs,$action,$tasktitle);
    } elsif (($action eq "chgfailsafe") && ($permhash{'edit'})) {
        &print_chgfailsafe_response($r,$realm,$dom,$crs,$action,$tasktitle);
    } elsif (($action eq "setdates") && ($permhash{'edit'})) {
        &print_setdates_response($r,$realm,$dom,$crs,$action,$tasktitle);
    } elsif (($action eq "setaccess") && ($permhash{'edit'})) {
        &print_setaccess_response($r,$realm,$dom,$crs,$action,$tasktitle);
    } elsif (($action eq "notify") && ($permhash{'edit'})) {
        &print_notify_response($r,$realm,$dom,$crs,$action,$tasktitle);
    } elsif (($action eq "sections") && ($permhash{'edit'})) {
        &print_sections_menu($r,$realm,$dom,$crs,$action,$tasktitle);
    } elsif (($action eq "crosslist") && ($permhash{'edit'})) {
        &print_crosslistings_menu($r,$realm,$dom,$crs,$action,$tasktitle);
    } elsif (($action eq "updatenow") && ($permhash{'edit'})) {
        &print_update_result($r,$realm,$dom,$crs,$action,$tasktitle);
    } elsif (($action eq "photos") && ($permhash{'edit'})) {
        if ($state eq "photoupdate") {
            &print_photoupdate_response($r,$realm,$dom,$crs,$action,$tasktitle);
        } else {
            &photo_permission($r,$realm,$dom,$crs,$action,$tasktitle);
        }
    } elsif (($action eq "updatephotos") && ($permhash{'edit'})) {
        &print_photoupdate_response($r,$realm,$dom,$crs,$action,$tasktitle);
    } elsif (($action eq "newcross") && ($permhash{'edit'})) {
        &print_crosslistings_response($r,$realm,$dom,$crs,$action,$tasktitle);    
    } elsif (($action eq "newsections") && ($permhash{'edit'})) {
        &print_sections_response($r,$realm,$dom,$crs,$action,$tasktitle);
    } elsif (($action eq "viewclass") && ($permhash{'edit'})) {
        &print_viewclass_response($r,$realm,$dom,$crs,$action,$tasktitle);
    }
    &print_doc_base($r);  
    return OK;
}
###################################################################
1;

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