File:  [LON-CAPA] / loncom / interface / Attic / londropadd.pm
Revision 1.91.2.1: download - view: text, annotated - select for diffs
Wed Jan 21 00:23:30 2004 UTC (20 years, 5 months ago) by albertel
Branches: version_1_1_X
Diff to branchpoint 1.91: preferred, unified
- adding code to hide Automated Enrollmanet manger link if not enabled on the machine

    1: # The LearningOnline Network with CAPA
    2: # Handler to drop and add students in courses 
    3: #
    4: # $Id: londropadd.pm,v 1.91.2.1 2004/01/21 00:23:30 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: # (Handler to set parameters for assessments
   29: #
   30: # (Handler to resolve ambiguous file locations
   31: #
   32: # (TeX Content Handler
   33: #
   34: ###############################################################
   35: ##############################################################
   36: 
   37: package Apache::londropadd;
   38: 
   39: use strict;
   40: use Apache::lonnet();
   41: use Apache::loncommon();
   42: use Apache::lonhtmlcommon();
   43: use Apache::Constants qw(:common :http REDIRECT);
   44: use Spreadsheet::WriteExcel;
   45: use Apache::lonlocal;
   46: use localenroll();
   47: 
   48: ###############################################################
   49: ###############################################################
   50: sub header {
   51:     my $bodytag=&Apache::loncommon::bodytag('Enrollment Manager');
   52:     my $title = &mt('LON-CAPA Enrollment Manager');
   53:     return(<<ENDHEAD);
   54: <html>
   55: <head>
   56: <title>$title</title>
   57: </head>
   58: $bodytag
   59: <form method="post" enctype="multipart/form-data"  
   60:       action="/adm/dropadd" name="studentform">
   61: ENDHEAD
   62: }
   63: 
   64: ###############################################################
   65: ###############################################################
   66: # Drop student from all sections of a course, except optional $csec
   67: sub modifystudent {
   68:     my ($udom,$unam,$courseid,$csec,$desiredhost)=@_;
   69:     # if $csec is undefined, drop the student from all the courses matching
   70:     # this one.  If $csec is defined, drop them from all other sections of 
   71:     # this course and add them to section $csec
   72:     $courseid=~s/\_/\//g;
   73:     $courseid=~s/^(\w)/\/$1/;
   74:     my %roles = &Apache::lonnet::dump('roles',$udom,$unam);
   75:     my ($tmp) = keys(%roles);
   76:     # Bail out if we were unable to get the students roles
   77:     return "$1" if ($tmp =~ /^(con_lost|error|no_such_host)/i);
   78:     # Go through the roles looking for enrollment in this course
   79:     my $result = '';
   80:     foreach my $course (keys(%roles)) {
   81:         if ($course=~/^$courseid(?:\/)*(?:\s+)*(\w+)*\_st$/) {
   82:             # We are in this course
   83:             my $section=$1;
   84:             $section='' if ($course eq $courseid.'_st');
   85:             if (defined($csec) && $section eq $csec) {
   86:                 $result .= 'ok:';
   87:             } elsif ( ((!$section) && (!$csec)) || ($section ne $csec) ) {
   88:                 my (undef,$end,$start)=split(/\_/,$roles{$course});
   89:                 my $now=time;
   90:                 # if this is an active role 
   91:                 if (!($start && ($now<$start)) || !($end && ($now>$end))) {
   92:                     my $reply=&Apache::lonnet::modifystudent
   93:                         # dom  name  id mode pass     f     m     l     g
   94:                         ($udom,$unam,'',  '',  '',undef,undef,undef,undef,
   95:                          $section,time,undef,undef,$desiredhost);
   96:                     $result .= $reply.':';
   97:                 }
   98:             }
   99:         }
  100:     }
  101:     if ($result eq '') {
  102:         $result = 'Unable to find section for this student';
  103:     } else {
  104:         $result =~ s/(ok:)+/ok/g;
  105:     }
  106:     return $result;
  107: }
  108: 
  109: ###############################################################
  110: ###############################################################
  111: # build a domain and server selection form
  112: sub domain_form {
  113:     my ($defdom) = @_;
  114:     # Set up domain and server selection forms
  115:     #
  116:     # Get the domains
  117:     my @domains = &Apache::loncommon::get_domains();
  118:     # build up the menu information to be passed to 
  119:     # &Apache::loncommon::linked_select_forms
  120:     my %select_menus;
  121:     foreach my $dom (@domains) {
  122:         # set up the text for this domain
  123:         $select_menus{$dom}->{'text'}= $dom;
  124:         # we want a choice of 'default' as the default in the second menu
  125:         $select_menus{$dom}->{'default'}= 'default';
  126:         $select_menus{$dom}->{'select2'}->{'default'} = 'default';
  127:         # Now build up the other items in the second menu
  128:         my %servers = &Apache::loncommon::get_library_servers($dom);
  129:         foreach my $server (keys(%servers)) {
  130:             $select_menus{$dom}->{'select2'}->{$server} 
  131:                                             = "$server $servers{$server}";
  132:         }
  133:     }
  134:     my $result  = &Apache::loncommon::linked_select_forms
  135:         ('studentform',' with home server ',$defdom,
  136:          'lcdomain','lcserver',\%select_menus);
  137:     return $result;
  138: }
  139: 
  140: ###############################################################
  141: ###############################################################
  142: #  Menu Phase One
  143: sub print_main_menu {
  144:     my $r=shift;
  145:     my %Text = &Apache::lonlocal::texthash
  146:         ('upload'    => 'Upload a class list',
  147:          'enrollone' => 'Enroll a single student',
  148:          'modify'    => 'Modify student data',
  149:          'view'      => 'View Class List',
  150:          'drop'      => 'Drop Students',
  151:          'populate'  => 'Automated Enrollment Manager');
  152: 
  153:     $r->print(<<END);
  154: <p>
  155: <font size="+1">
  156:     <a href="/adm/dropadd?action=upload">$Text{'upload'}</a>
  157: </font>
  158: </p><p>
  159: <font size="+1">
  160:     <a href="/adm/dropadd?action=enrollstudent">$Text{'enrollone'}</a>
  161: </font>
  162: </p><p>
  163: <font size="+1">
  164:     <a href="/adm/dropadd?action=modifystudent">$Text{'modify'}</a>
  165: </font>
  166: </p><p>
  167: <font size="+1">
  168:     <a href="/adm/dropadd?action=classlist">$Text{'view'}</a>
  169: </font>
  170: </p><p>
  171: <font size="+1">
  172:     <a href="/adm/dropadd?action=drop">$Text{'drop'}</a>
  173: </font>
  174: </p><p>
  175: END
  176:     if (&localenroll::run() ) {
  177: 	$r->print(<<END);
  178: <font size="+1">
  179:     <a href="/adm/populate">$Text{'populate'}</a>
  180: </font>
  181: END
  182:     }
  183: }
  184: 
  185: ###############################################################
  186: ###############################################################
  187: sub hidden_input {
  188:     my ($name,$value) = @_;
  189:     return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
  190: }
  191: 
  192: sub print_upload_manager_header {
  193:     my ($r,$datatoken,$distotal,$krbdefdom)=@_;
  194:     my $javascript;
  195:     if (! exists($ENV{'form.upfile_associate'})) {
  196:         $ENV{'form.upfile_associate'} = 'forward';
  197:     }
  198:     if ($ENV{'form.associate'} eq 'Reverse Association') {
  199:         if ( $ENV{'form.upfile_associate'} ne 'reverse' ) {
  200:             $ENV{'form.upfile_associate'} = 'reverse';
  201:         } else {
  202:             $ENV{'form.upfile_associate'} = 'forward';
  203:         }
  204:     }
  205:     if ($ENV{'form.upfile_associate'} eq 'reverse') {
  206: 	$javascript=&upload_manager_javascript_reverse_associate();
  207:     } else {
  208: 	$javascript=&upload_manager_javascript_forward_associate();
  209:     }
  210:     my $javascript_validations=&javascript_validations('auth',$krbdefdom);
  211:     my $checked=(($ENV{'form.noFirstLine'})?' checked="1"':'');
  212:     $r->print('<h3>'.&mt('Uploading Class List')."</h3>\n".
  213:               "<hr>\n".
  214:               '<h3>'.&mt('Identify fields')."</h3>\n");
  215:     $r->print("<p>\n".
  216:               &mt('Total number of records found in file: [_1].',$distotal).
  217:               "\n".
  218:               "</p><hr>\n");
  219:     $r->print(&mt('Enter as many fields as you can. '.
  220:                   'The system will inform you and bring you back to '.
  221:                   'this page if the data selected is insufficient to '.
  222:                   'enroll students in your class.')."<hr>\n");
  223:     $r->print(&hidden_input('action','upload').
  224:               &hidden_input('state','got_file').
  225:               &hidden_input('associate','').
  226:               &hidden_input('datatoken',$datatoken).
  227:               &hidden_input('fileupload',$ENV{'form.fileupload'}).
  228:               &hidden_input('upfiletype',$ENV{'form.upfiletype'}).
  229:               &hidden_input('upfile_associate',$ENV{'form.upfile_associate'}));
  230:     $r->print('<input type="button" value="Reverse Association" '.
  231:               'name="'.&mt('Reverse Association').'" '.
  232:               'onClick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />');
  233:     $r->print('<input type="checkbox" name="noFirstLine" $checked />'.
  234:               &mt('Ignore First Line'));
  235:     $r->print("<hr />\n".
  236:               '<script type="text/javascript" language="Javascript">'."\n".
  237:               $javascript."\n".$javascript_validations.'</script>');
  238: }
  239: 
  240: ###############################################################
  241: ###############################################################
  242: sub javascript_validations {
  243:     my ($mode,$krbdefdom)=@_;
  244:     my $authheader;
  245:     if ($mode eq 'auth') {
  246:         my %param = ( formname => 'studentform',
  247:                       kerb_def_dom => $krbdefdom );
  248:         $authheader = &Apache::loncommon::authform_header(%param);
  249:     } elsif ($mode eq 'createcourse') {
  250:         my %param = ( formname => 'ccrs',
  251:                   kerb_def_dom => $krbdefdom );
  252:         $authheader = &Apache::loncommon::authform_header(%param);
  253:     }
  254:     
  255:     my %alert = &Apache::lonlocal::texthash
  256:         (username => 'You need to specify the username field.',
  257:          authen   => 'You must choose an authentication type.',
  258:          krb      => 'You need to specify the Kerberos domain.',
  259:          ipass    => 'You need to specify the initial password.',
  260:          name     => 'The optional name field was not specified.',
  261:          snum     => 'The optional student number field was not specified.',
  262:          section  => 'The optional section or group field was not specified.', 
  263:          email    => 'The optional email address field was not specified.',
  264:          continue => 'Continue enrollment?',
  265:          );
  266:     
  267: #    my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
  268:     my $function_name =(<<END);
  269: function verify_message (vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail) {
  270: END
  271:     my $auth_checks = (<<END);
  272:     var foundatype=0;
  273: END
  274:     unless ($mode eq 'createcourse') {
  275:         $auth_checks .= (<<END);
  276:     if (founduname==0) {
  277: 	alert('$alert{'username'}');
  278:         return;
  279:     }
  280: END
  281:     }
  282:     $auth_checks .= (<<END);
  283:     // alert('current.radiovalue = '+current.radiovalue);
  284:     if (current.radiovalue == null || current.radiovalue == 'nochange') {
  285:         // They did not check any of the login radiobuttons.
  286:         alert('$alert{'authen'}');
  287:         return;
  288:     }
  289:     foundatype=1;
  290:     if (current.argfield == null || current.argfield == '') {
  291:         var alertmsg = '';
  292:         switch (current.value) {
  293:             case 'krb': 
  294:                 alertmsg = '$alert{'krb'}';
  295:                 break;
  296:             case 'loc':
  297:             case 'fsys':
  298:                 alertmsg = '$alert{'ipass'}';
  299:                 break;
  300:             case 'fsys':
  301:                 alertmsg = '';
  302:                 break;
  303:             default: 
  304:                 alertmsg = '';
  305:         }
  306:         if (alertmsg != '') {
  307:             alert(alertmsg);
  308:             return;
  309:         }
  310:     }
  311: END
  312:     my $optional_checks = '';
  313:     if ($mode eq 'createcourse') {
  314:         $optional_checks = (<<END);
  315:     vf.submit();
  316: }
  317: END
  318:     } else {
  319:         $optional_checks = (<<END);
  320:     var message='';
  321:     if (foundname==0) { 
  322:         message='$alert{'name'}';
  323:     }
  324:     if (foundid==0) { 
  325:         if (message!='') { 
  326:             message+='\\n'; 
  327:         }
  328:         message+='$alert{'snum'}';
  329:     }
  330:     if (foundsec==0) {
  331:         if (message!='') {
  332:             message+='\\n';
  333:         } 
  334:         message+='$alert{'section'}';
  335:     }
  336:     if (foundemail==0) {
  337:         if (message!='') {
  338:             message+='\\n';
  339:         }
  340:         message+='$alert{'email'}';
  341:     }
  342:     if (message!='') {
  343:         message+= '\\n$alert{'continue'}';
  344:         if (confirm(message)) {
  345:             vf.state.value='enrolling';
  346:             vf.submit();
  347:         }
  348:     } else {
  349:         vf.state.value='enrolling';
  350:         vf.submit();
  351:     }
  352: }
  353: END
  354:     }
  355:     my $result = $function_name;
  356:     if ( ($mode eq 'auth') || ($mode eq 'createcourse') ) {
  357:         $result .= $auth_checks;
  358:     }
  359:     $result .= $optional_checks;
  360:     if ( ($mode eq 'auth') || ($mode eq 'createcourse') ) {
  361:         $result .= $authheader;
  362:     }
  363:     return $result;
  364: }
  365: 
  366: ###############################################################
  367: ###############################################################
  368: sub upload_manager_javascript_forward_associate {
  369:     return(<<ENDPICK);
  370: function verify(vf) {
  371:     var founduname=0;
  372:     var foundpwd=0;
  373:     var foundname=0;
  374:     var foundid=0;
  375:     var foundsec=0;
  376:     var foundemail=0;
  377:     var tw;
  378:     for (i=0;i<=vf.nfields.value;i++) {
  379:         tw=eval('vf.f'+i+'.selectedIndex');
  380:         if (tw==1) { founduname=1; }
  381:         if ((tw>=2) && (tw<=6)) { foundname=1; }
  382:         if (tw==7) { foundid=1; }
  383:         if (tw==8) { foundsec=1; }
  384:         if (tw==9) { foundpwd=1; }
  385:         if (tw==10) { foundemail=1; }
  386:     }
  387:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail);
  388: }
  389: 
  390: //
  391: // vf = this.form
  392: // tf = column number
  393: //
  394: // values of nw
  395: //
  396: // 0 = none
  397: // 1 = username
  398: // 2 = names (lastname, firstnames)
  399: // 3 = fname (firstname)
  400: // 4 = mname (middlename)
  401: // 5 = lname (lastname)
  402: // 6 = gen   (generation)
  403: // 7 = id
  404: // 8 = section
  405: // 9 = ipwd  (password)
  406: // 10 = email address
  407: 
  408: function flip(vf,tf) {
  409:    var nw=eval('vf.f'+tf+'.selectedIndex');
  410:    var i;
  411:    // make sure no other columns are labeled the same as this one
  412:    for (i=0;i<=vf.nfields.value;i++) {
  413:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
  414:           eval('vf.f'+i+'.selectedIndex=0;')
  415:       }
  416:    }
  417:    // If we set this to 'lastname, firstnames', clear out all the ones
  418:    // set to 'fname','mname','lname','gen' (3,4,5,6) currently.
  419:    if (nw==2) {
  420:       for (i=0;i<=vf.nfields.value;i++) {
  421:          if ((eval('vf.f'+i+'.selectedIndex')>=3) &&
  422:              (eval('vf.f'+i+'.selectedIndex')<=6)) {
  423:              eval('vf.f'+i+'.selectedIndex=0;')
  424:          }
  425:       }
  426:    }
  427:    // If we set this to one of 'fname','mname','lname','gen' (3,4,5,6),
  428:    // clear out any that are set to 'lastname, firstnames' (2)
  429:    if ((nw>=3) && (nw<=6)) {
  430:       for (i=0;i<=vf.nfields.value;i++) {
  431:          if (eval('vf.f'+i+'.selectedIndex')==2) {
  432:              eval('vf.f'+i+'.selectedIndex=0;')
  433:          }
  434:       }
  435:    }
  436:    // If we set the password, make the password form below correspond to 
  437:    // the new value.
  438:    if (nw==9) {
  439:        changed_radio('int',document.studentform);
  440:        set_auth_radio_buttons('int',document.studentform);
  441:        vf.intarg.value='';
  442:        vf.krbarg.value='';
  443:        vf.locarg.value='';
  444:    }
  445: }
  446: 
  447: function clearpwd(vf) {
  448:     var i;
  449:     for (i=0;i<=vf.nfields.value;i++) {
  450:         if (eval('vf.f'+i+'.selectedIndex')==9) {
  451:             eval('vf.f'+i+'.selectedIndex=0;')
  452:         }
  453:     }
  454: }
  455: 
  456: ENDPICK
  457: }
  458: 
  459: ###############################################################
  460: ###############################################################
  461: sub upload_manager_javascript_reverse_associate {
  462:     return(<<ENDPICK);
  463: function verify(vf) {
  464:     var founduname=0;
  465:     var foundpwd=0;
  466:     var foundname=0;
  467:     var foundid=0;
  468:     var foundsec=0;
  469:     var tw;
  470:     for (i=0;i<=vf.nfields.value;i++) {
  471:         tw=eval('vf.f'+i+'.selectedIndex');
  472:         if (i==0 && tw!=0) { founduname=1; }
  473:         if (((i>=1) && (i<=5)) && tw!=0 ) { foundname=1; }
  474:         if (i==6 && tw!=0) { foundid=1; }
  475:         if (i==7 && tw!=0) { foundsec=1; }
  476:         if (i==8 && tw!=0) { foundpwd=1; }
  477:     }
  478:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec);
  479: }
  480: 
  481: function flip(vf,tf) {
  482:    var nw=eval('vf.f'+tf+'.selectedIndex');
  483:    var i;
  484:    // picked the all one one name field, reset the other name ones to blank
  485:    if (tf==1 && nw!=0) {
  486:       for (i=2;i<=5;i++) {
  487:          eval('vf.f'+i+'.selectedIndex=0;')
  488:       }
  489:    }
  490:    //picked one of the piecewise name fields, reset the all in
  491:    //one field to blank
  492:    if ((tf>=2) && (tf<=5) && (nw!=0)) {
  493:       eval('vf.f1.selectedIndex=0;')
  494:    }
  495:    // intial password specified, pick internal authentication
  496:    if (tf==8 && nw!=0) {
  497:        changed_radio('int',document.studentform);
  498:        set_auth_radio_buttons('int',document.studentform);
  499:        vf.krbarg.value='';
  500:        vf.intarg.value='';
  501:        vf.locarg.value='';
  502:    }
  503: }
  504: 
  505: function clearpwd(vf) {
  506:     var i;
  507:     if (eval('vf.f8.selectedIndex')!=0) {
  508:         eval('vf.f8.selectedIndex=0;')
  509:     }
  510: }
  511: ENDPICK
  512: }
  513: 
  514: ###############################################################
  515: ###############################################################
  516: sub print_upload_manager_footer {
  517:     my ($r,$i,$keyfields,$defdom,$today,$halfyear)=@_;
  518: 
  519:     my ($krbdef,$krbdefdom) =
  520:         &Apache::loncommon::get_kerberos_defaults($defdom);
  521:     my %param = ( formname => 'document.studentform',
  522:                   kerb_def_dom => $krbdefdom,
  523:                   kerb_def_auth => $krbdef
  524:                   );
  525:     my $krbform = &Apache::loncommon::authform_kerberos(%param);
  526:     my $intform = &Apache::loncommon::authform_internal(%param);
  527:     my $locform = &Apache::loncommon::authform_local(%param);
  528:     my $domform = &domain_form($defdom);
  529:     my $date_table = &date_setting_table();
  530:     my $Str = "</table>\n";
  531:     $Str .= &hidden_input('nfields',$i);
  532:     $Str .= &hidden_input('keyfields',$keyfields);
  533:     $Str .= '<h3>'.&mt('Login Type')."</h3>\n";
  534:     $Str .= "<p>\n".
  535:         &mt('Note: this will not take effect if the user already exists').
  536:         "</p><p>\n";
  537:     $Str .= $krbform."\n</p><p>\n".
  538:         $intform."\n</p><p>\n".
  539:         $locform."\n</p>\n";
  540:     $Str .= '<h3>'.&mt('LON-CAPA Domain for Students')."</h3>\n";
  541:     $Str .= "<p>\n".&mt('LON-CAPA domain: [_1]',$domform)."\n</p>\n";
  542:     $Str .= "<h3>".&mt('Starting and Ending Dates')."</h3>\n";
  543:     $Str .= "<p>\n".$date_table."</p>\n";
  544:     $Str .= "<h3>".&mt('Full Update')."</h3>\n";
  545:     $Str .= '<input type="checkbox" name="fullup" value="yes">'.
  546:         ' '.&mt('Full update (also print list of users not enrolled anymore)').
  547:         "</p>\n";
  548:     $Str .= "<h3>".&mt('Student Number')."</h3>\n";
  549:     $Str .= "<p>\n".'<input type="checkbox" name="forceid" value="yes">';
  550:     $Str .= &mt('Disable ID/Student Number Safeguard and Force Change '.
  551:                 'of Conflicting IDs (only do if you know what you are doing)').
  552:                 "\n</p><p>\n";
  553:     $Str .= '<input type="button" onClick="javascript:verify(this.form)" '.
  554:         'value="Update Courselist" />'."<br />\n";
  555:     $Str .= &mt('Note: for large courses, this operation may be time '.
  556:                 'consuming');
  557:     $r->print($Str);
  558:     return;
  559: }
  560: 
  561: ###############################################################
  562: ###############################################################
  563: sub print_upload_manager_form {
  564:     my $r=shift;
  565:     my $firstLine;
  566:     my $datatoken;
  567:     if (!$ENV{'form.datatoken'}) {
  568:         $datatoken=&Apache::loncommon::upfile_store($r);
  569:     } else {
  570:         $datatoken=$ENV{'form.datatoken'};
  571:         &Apache::loncommon::load_tmp_file($r);
  572:     }
  573:     my @records=&Apache::loncommon::upfile_record_sep();
  574:     if($ENV{'form.noFirstLine'}){
  575:         $firstLine=shift(@records);
  576:     }
  577:     my $total=$#records;
  578:     my $distotal=$total+1;
  579:     my $today=time;
  580:     my $halfyear=$today+15552000;
  581:     my $defdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
  582:     my ($krbdef,$krbdefdom) =
  583:         &Apache::loncommon::get_kerberos_defaults($defdom);
  584:     &print_upload_manager_header($r,$datatoken,$distotal,$krbdefdom);
  585:     my $i;
  586:     my $keyfields;
  587:     if ($total>=0) {
  588:         my @field=(['username',&mt('Username')],
  589:                    ['names',&mt('Last Name, First Names')],
  590:                    ['fname',&mt('First Name')],
  591:                    ['mname',&mt('Middle Names/Initials')],
  592:                    ['lname',&mt('Last Name')],
  593:                    ['gen',&mt('Generation')],
  594:                    ['id',&mt('ID/Student Number')],
  595:                    ['sec',&mt('Group/Section')],
  596:                    ['ipwd',&mt('Initial Password')],
  597:                    ['email',&mt('EMail Address')]);
  598: 	if ($ENV{'form.upfile_associate'} eq 'reverse') {	
  599: 	    &Apache::loncommon::csv_print_samples($r,\@records);
  600: 	    $i=&Apache::loncommon::csv_print_select_table($r,\@records,
  601:                                                           \@field);
  602: 	    foreach (@field) { 
  603:                 $keyfields.=$_->[0].','; 
  604:             }
  605: 	    chop($keyfields);
  606: 	} else {
  607: 	    unshift(@field,['none','']);
  608: 	    $i=&Apache::loncommon::csv_samples_select_table($r,\@records,
  609:                                                             \@field);
  610: 	    my %sone=&Apache::loncommon::record_sep($records[0]);
  611: 	    $keyfields=join(',',sort(keys(%sone)));
  612: 	}
  613:     }
  614:     &print_upload_manager_footer($r,$i,$keyfields,$defdom,$today,$halfyear);
  615: }
  616: 
  617: ###############################################################
  618: ###############################################################
  619: sub enroll_single_student {
  620:     my $r=shift;
  621:     # Remove non alphanumeric values from section
  622:     $ENV{'form.csec'}=~s/\W//g;
  623:     #
  624:     # We do the dates first because the action of making them the defaul
  625:     # in the course is entirely seperate from the action of enrolling the
  626:     # student.  Also, a failure in setting the dates as default is not fatal
  627:     # to the process of enrolling / modifying a student.
  628:     my ($startdate,$enddate) = &get_dates_from_form();
  629:     if ($ENV{'form.makedatesdefault'}) {
  630:         $r->print(&make_dates_default($startdate,$enddate));
  631:     }
  632: 
  633:     $r->print('<h3>Enrolling Student</h3>');
  634:     $r->print('<p>Enrolling '.$ENV{'form.cuname'}." \@ ".
  635:               $ENV{'form.lcdomain'}.'</p>');
  636:     if (($ENV{'form.cuname'})&&($ENV{'form.cuname'}!~/\W/)&&
  637:         ($ENV{'form.lcdomain'})&&($ENV{'form.lcdomain'}!~/\W/)) {
  638:         # Deal with home server selection
  639:         my $domain=$ENV{'form.lcdomain'};
  640:         my $desiredhost = $ENV{'form.lcserver'};
  641:         if (lc($desiredhost) eq 'default') {
  642:             $desiredhost = undef;
  643:         } else {
  644:             my %home_servers =&Apache::loncommon::get_library_servers($domain);
  645:             if (! exists($home_servers{$desiredhost})) {
  646:                 $r->print('<font color="#ff0000">Error:</font>'.
  647:                           'Invalid home server specified');
  648:                 return;
  649:             }
  650:         }
  651:         $r->print(" with server $desiredhost :") if (defined($desiredhost));
  652:         # End of home server selection logic
  653: 	my $amode='';
  654:         my $genpwd='';
  655:         if ($ENV{'form.login'} eq 'krb') {
  656:            $amode='krb';
  657: 	   $amode.=$ENV{'form.krbver'};
  658:            $genpwd=$ENV{'form.krbarg'};
  659:         } elsif ($ENV{'form.login'} eq 'int') {
  660:            $amode='internal';
  661:            $genpwd=$ENV{'form.intarg'};
  662:         }  elsif ($ENV{'form.login'} eq 'loc') {
  663: 	    $amode='localauth';
  664: 	    $genpwd=$ENV{'form.locarg'};
  665: 	    if (!$genpwd) { $genpwd=" "; }
  666: 	}
  667:         my $home = &Apache::lonnet::homeserver($ENV{'form.cuname'},
  668:                                                    $ENV{'form.lcdomain'});
  669:         if ((($amode) && ($genpwd)) || ($home ne 'no_host')) {
  670:             # Clean out any old roles the student has in this class.
  671:             &modifystudent($ENV{'form.lcdomain'},$ENV{'form.cuname'},
  672:                            $ENV{'request.course.id'},$ENV{'form.csec'},
  673:                             $desiredhost);
  674:             my $login_result = &Apache::lonnet::modifystudent
  675:                 ($ENV{'form.lcdomain'},$ENV{'form.cuname'},
  676:                  $ENV{'form.cstid'},$amode,$genpwd,
  677:                  $ENV{'form.cfirst'},$ENV{'form.cmiddle'},
  678:                  $ENV{'form.clast'},$ENV{'form.cgen'},
  679:                  $ENV{'form.csec'},$enddate,
  680:                  $startdate,$ENV{'form.forceid'},
  681:                  $desiredhost);
  682:             if ($login_result =~ /^ok/) {
  683:                 $r->print($login_result);
  684:                 $r->print("<p> If active, the new role will be available ".
  685:                           "when the student next logs in to LON-CAPA.</p>");
  686:             } else {
  687:                 $r->print("unable to enroll: ".$login_result);
  688:             }
  689: 	} else {
  690:             $r->print('<p><font color="#ff0000">ERROR</font>&nbsp;');
  691:             if ($amode =~ /^krb/) {
  692:                 $r->print('Missing Kerberos domain information.  ');
  693:             } else {
  694:                 $r->print('Invalid login mode or password.  ');
  695:             }
  696:             $r->print('<b>Unable to enroll '.$ENV{'form.cuname'}.'.</b></p>');
  697:         }
  698:     } else {
  699:         $r->print('Invalid username or domain');
  700:     }    
  701: }
  702: 
  703: sub setup_date_selectors {
  704:     my ($starttime,$endtime,$mode) = @_;
  705:     if (! defined($starttime)) {
  706:         $starttime = time;
  707:         unless ($mode eq 'createcourse') {
  708:             if (exists($ENV{'course.'.$ENV{'request.course.id'}.
  709:                             '.default_enrollment_start_date'})) {
  710:                 $starttime = $ENV{'course.'.$ENV{'request.course.id'}.
  711:                                   '.default_enrollment_start_date'};
  712:             }
  713:         }
  714:     }
  715:     if (! defined($endtime)) {
  716:         $endtime = time+(6*30*24*60*60); # 6 months from now, approx
  717:         unless ($mode eq 'createcourse') {
  718:             if (exists($ENV{'course.'.$ENV{'request.course.id'}.
  719:                             '.default_enrollment_end_date'})) {
  720:                 $endtime = $ENV{'course.'.$ENV{'request.course.id'}.
  721:                                 '.default_enrollment_end_date'};
  722:             }
  723:         }
  724:     }
  725:     my $startdateform = &Apache::lonhtmlcommon::date_setter('studentform',
  726:                                                             'startdate',
  727:                                                             $starttime);
  728:     my $enddateform = &Apache::lonhtmlcommon::date_setter('studentform',
  729:                                                           'enddate',
  730:                                                           $endtime);
  731:     if ($mode eq 'createcourse') {
  732:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
  733:                                                             'startdate',
  734:                                                             $starttime);
  735:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
  736:                                                           'enddate',
  737:                                                           $endtime);
  738:     }
  739:     return ($startdateform,$enddateform);
  740: }
  741: 
  742: sub get_dates_from_form {
  743:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate');
  744:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate');
  745:     if ($ENV{'form.no_end_date'}) {
  746:         $enddate = 0;
  747:     }
  748:     return ($startdate,$enddate);
  749: }
  750: 
  751: sub date_setting_table {
  752:     my ($starttime,$endtime,$mode) = @_;
  753:     my ($startform,$endform)=&setup_date_selectors($starttime,$endtime,$mode);
  754:     my $dateDefault = '<nobr>'.
  755:         '<input type="checkbox" name="makedatesdefault" />'.
  756:         ' make these dates the default for future enrollment';
  757:     if ($mode eq 'createcourse') {
  758:         $dateDefault = '&nbsp;';
  759:     }
  760:     my $perpetual = '<nobr><input type="checkbox" name="no_end_date"';
  761:     if (defined($endtime) && $endtime == 0) {
  762:         $perpetual .= ' checked';
  763:     }
  764:     $perpetual.= ' />'.' no ending date</nobr>';
  765:     my $result = '';
  766:     $result .= "<table>\n";
  767:     $result .= '<tr><td align="right">Starting Date</td>'.
  768:         '<td>'.$startform.'</td>'.
  769:         '<td>'.$dateDefault.'</td>'."</tr>\n";
  770:     $result .= '<tr><td align="right">Ending Date</td>'.
  771:         '<td>'.$endform.'</td>'.
  772:         '<td>'.$perpetual.'</td>'."</tr>\n";
  773:     $result .= "</table>\n";
  774:     return $result;
  775: }
  776: 
  777: sub make_dates_default {
  778:     my ($startdate,$enddate) = @_;
  779:     my $result = '';
  780:     my $dom = $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
  781:     my $crs = $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
  782:     my $put_result = &Apache::lonnet::put('environment',
  783:             {'default_enrollment_start_date'=>$startdate,
  784:              'default_enrollment_end_date'  =>$enddate},$dom,$crs);
  785:     if ($put_result eq 'ok') {
  786:         $result .= "Set default start and end dates for course<br />";
  787:         #
  788:         # Refresh the course environment
  789:         &Apache::lonnet::coursedescription($ENV{'request.course.id'});
  790:     } else {
  791:         $result .= "Unable to set default dates for course:".$put_result.
  792:             '<br />';
  793:     }
  794:     return $result;
  795: }
  796: 
  797: ##
  798: ## Single student enrollment routines (some of them)
  799: ##
  800: sub get_student_username_domain_form {
  801:     my $r = shift;
  802:     my $domform = &Apache::loncommon::select_dom_form
  803:         ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'},'cudomain',0);
  804:     $r->print(<<END);
  805: <input type="hidden" name="action" value="enrollstudent" />
  806: <input type="hidden" name="state"  value="gotusername" />
  807: <h3>Enroll One Student</h3>
  808: <table>
  809: <tr><th>Username:</th>
  810:     <td><input type="text" name="cuname"  size="15" /></td></tr>
  811: <tr><th>Domain:</th>
  812:     <td>$domform</td></tr>
  813: <tr><th>&nbsp;</th>
  814:     <td>
  815:     <input type="submit" name="Begin Enrollment" value="Begin Enrollment" />
  816:     </td></tr>
  817: </table>
  818: END
  819:     return;
  820: }
  821: 
  822: sub print_enroll_single_student_form {
  823:     my $r=shift;
  824:     $r->print("<h3>Enroll One Student</h3>");
  825:     #
  826:     my $username = $ENV{'form.cuname'};
  827:     my $domain   = $ENV{'form.cudomain'};
  828:     my $home = &Apache::lonnet::homeserver($username,$domain);
  829:     # $new_user flags whether we are creating a new user or using an old one
  830:     my $new_user = 1;
  831:     if ($home ne 'no_host') {
  832:         $new_user = 0;
  833:     }
  834:     #
  835:     my $user_data_html = '';
  836:     my $javascript_validations = '';
  837:     if ($new_user) {
  838:         my $defdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
  839:         # Set up authentication forms
  840:         my ($krbdef,$krbdefdom) =
  841:             &Apache::loncommon::get_kerberos_defaults($domain);
  842:         $javascript_validations=&javascript_validations('auth',$krbdefdom);
  843:         my %param = ( formname => 'document.studentform',
  844:                       kerb_def_dom => $krbdefdom,
  845:                       kerb_def_auth => $krbdef
  846:                       );
  847:         my $krbform = &Apache::loncommon::authform_kerberos(%param);
  848:         my $intform = &Apache::loncommon::authform_internal(%param);
  849:         my $locform = &Apache::loncommon::authform_local(%param);
  850:         #
  851:         # Set up domain selection form
  852:         my $homeserver_form = '';
  853:         my %servers = &Apache::loncommon::get_library_servers($domain);
  854:         $homeserver_form = '<select name="lcserver" size="1">'."\n".
  855:             '<option value="default" selected>default</option>'."\n";
  856:         while (my ($servername,$serverdescription) = each (%servers)) {
  857:             $homeserver_form .= '<option value="'.$servername.'">'.
  858:                 $serverdescription."</option>\n";
  859:         }
  860:         $homeserver_form .= "</select>\n";
  861:         #
  862:         #
  863:         $user_data_html = <<END;
  864: <h3>User Data for $username\@$domain</h3>
  865: <table>
  866: <tr><th>First Name:</th>
  867:     <td><input type="text" name="cfirst"  size="15"></td></tr>
  868: <tr><th>Middle Name:</th>
  869:     <td><input type="text" name="cmiddle" size="15"></td></tr>
  870: <tr><th>Last Name:</th>
  871:     <td><input type="text" name="clast"   size="15"></td></tr>
  872: <tr><th>Generation:</th>
  873:     <td><input type="text" name="cgen"    size="5"> </td></tr>
  874: <tr><th>Home Server:</th>
  875:     <td>$homeserver_form</td></tr>
  876: </table>
  877: <h3>Password</h3>
  878: Please select an authentication mechanism
  879: <table>
  880: <p>
  881: $krbform
  882: <br />
  883: $intform
  884: <br />
  885: $locform
  886: </p>
  887: END
  888:     } else {
  889:         # User already exists.  Do not worry about authentication
  890:         my %uenv = &Apache::lonnet::dump('environment',$domain,$username);
  891:         $javascript_validations = &javascript_validations('noauth');
  892:         $user_data_html = <<END;
  893: <h3>User Data for $username\@$domain</h3>
  894: <input type="hidden" name="lcserver" value="default" />
  895: <table>
  896: <tr><th>First Name:</th>
  897:     <td>
  898:     <input type="text" name="cfirst" value="$uenv{'firstname'}" size="15" />
  899:     </td></tr>
  900: <tr><th>Middle Name:</th>
  901:     <td>
  902:     <input type="text" name="cmiddle" value="$uenv{'middlename'}" size="15" />
  903:     </td></tr>
  904: <tr><th>Last Name:</th>
  905:     <td>
  906:     <input type="text" name="clast"value="$uenv{'lastname'}" size="15" />
  907:     </td></tr>
  908: <tr><th>Generation:</th>
  909:     <td>
  910:     <input type="text" name="cgen" value="$uenv{'generation'}" size="5" />
  911:     </td></tr>
  912: </table>
  913: END
  914:     }
  915:     my $date_table = &date_setting_table();
  916:         # Print it all out
  917:     $r->print(<<END);
  918: <input type="hidden" name="action" value="enrollstudent" />
  919: <input type="hidden" name="state"  value="done" />
  920: <input type="hidden" name="cuname" value="$username" />
  921: <input type="hidden" name="lcdomain" value="$domain" />
  922: <script type="text/javascript" language="Javascript">
  923: function verify(vf) {
  924:     var founduname=0;
  925:     var foundpwd=0;
  926:     var foundname=0;
  927:     var foundid=0;
  928:     var foundsec=0;
  929:     var tw;
  930:     if ((typeof(vf.cuname.value) !="undefined") && (vf.cuname.value!='') && 
  931: 	(typeof(vf.lcdomain.value)!="undefined") && (vf.lcdomain.value!='')) {
  932:         founduname=1;
  933:     }
  934:     if ((typeof(vf.cfirst.value)!="undefined") && (vf.cfirst.value!='') &&
  935: 	(typeof(vf.clast.value) !="undefined") && (vf.clast.value!='')) {
  936:         foundname=1;
  937:     }
  938:     if ((typeof(vf.csec.value)!="undefined") && (vf.csec.value!='')) {
  939:         foundsec=1;
  940:     }
  941:     if ((typeof(vf.cstid.value)!="undefined") && (vf.cstid.value!='')) {
  942: 	foundid=1;
  943:     }
  944:     if (founduname==0) {
  945: 	alert('You need to specify at least the username and domain fields');
  946:         return;
  947:     }
  948:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec);
  949: }
  950: 
  951: $javascript_validations
  952: 
  953: function clearpwd(vf) {
  954:     //nothing else needs clearing
  955: }
  956: 
  957: </script>
  958: 
  959: $user_data_html
  960: 
  961: <h3>Course Data</h3>
  962: 
  963: <p>Group/Section: <input type="text" name="csec" size="5" />
  964: <p>
  965: $date_table
  966: </p>
  967: <h3>ID/Student Number</h3>
  968: <p>
  969: ID/Student Number: <input type="text" name="cstid" size="10">
  970: </p><p>
  971: <input type="checkbox" name="forceid" value="yes"> 
  972: Disable ID/Student Number Safeguard and Force Change of Conflicting IDs
  973: (only do if you know what you are doing)
  974: </p><p>
  975: <input type="button" onClick="verify(this.form)" value="Enroll as student">
  976: </p>
  977: END
  978:     return;
  979: }
  980: 
  981: # ========================================================= Menu Phase Two Drop
  982: sub print_drop_menu {
  983:     my $r=shift;
  984:     $r->print("<h3>Drop Students</h3>");
  985:     my $cid=$ENV{'request.course.id'};
  986:     my ($classlist,$keylist) = &Apache::loncoursedata::get_classlist();
  987:     if (! defined($classlist)) {
  988:         $r->print("There are no students currently enrolled.\n");
  989:         return;
  990:     }
  991:     # Print out the available choices
  992:     &show_drop_list($r,$classlist,$keylist);
  993:     return;
  994: }
  995: 
  996: # ============================================== view classlist
  997: sub print_html_classlist {
  998:     my $r=shift;
  999:     if (! exists($ENV{'form.sortby'})) {
 1000:         $ENV{'form.sortby'} = 'username';
 1001:     }
 1002:     if ($ENV{'form.Status'} !~ /^(Any|Expired|Active)$/) {
 1003:         $ENV{'form.Status'} = 'Active';
 1004:     }
 1005:     my $status_select = &Apache::lonhtmlcommon::StatusOptions
 1006:         ($ENV{'form.Status'},'studentform');
 1007:     $r->print(<<END);
 1008: <input type="hidden" name="action" value="$ENV{'form.action'}" />
 1009: <input type="hidden" name="state"  value="" />
 1010: <p>
 1011: <font size="+1">Current Class List</font>
 1012: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 1013: END
 1014:     if ($ENV{'form.action'} ne 'modifystudent') {
 1015:         $r->print(<<END);
 1016: <font size="+1">
 1017: <a href="javascript:document.studentform.state.value='csv';document.studentform.submit();">CSV format</a>
 1018: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 1019: <a href="javascript:document.studentform.state.value='excel';document.studentform.submit();">Excel format</a>
 1020: </font>
 1021: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 1022: Student Status:
 1023: END
 1024:     }
 1025:     $r->print($status_select."</p>\n");
 1026:     my $cid=$ENV{'request.course.id'};
 1027:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
 1028:     if (! defined($classlist)) {
 1029:         $r->print("There are no students currently enrolled.\n");
 1030:     } else {
 1031:         # Print out the available choices
 1032:         if ($ENV{'form.action'} eq 'modifystudent') {
 1033:             &show_class_list($r,'view','modify','modifystudent',
 1034:                              $ENV{'form.Status'},$classlist,$keylist);
 1035:         } else {
 1036:             &show_class_list($r,'view','aboutme','classlist',
 1037:                              $ENV{'form.Status'},$classlist,$keylist);
 1038:         }
 1039:     }
 1040: }
 1041: 
 1042: # ============================================== view classlist
 1043: sub print_formatted_classlist {
 1044:     my $r=shift;
 1045:     my $mode = shift;
 1046:     my $cid=$ENV{'request.course.id'};
 1047:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
 1048:     if (! defined($classlist)) {
 1049:         $r->print("There are no students currently enrolled.\n");
 1050:     } else {
 1051:         &show_class_list($r,$mode,'nolink','csv',
 1052:                          $ENV{'form.Status'},$classlist,$keylist);
 1053:     }
 1054: }
 1055: 
 1056: # =================================================== Show student list to drop
 1057: sub show_class_list {
 1058:     my ($r,$mode,$linkto,$action,$statusmode,$classlist,$keylist)=@_;
 1059:     my $cid=$ENV{'request.course.id'};
 1060:     #
 1061:     # Variables for excel output
 1062:     my ($excel_workbook, $excel_sheet, $excel_filename,$row);
 1063:     #
 1064:     my $sortby = $ENV{'form.sortby'};
 1065:     if ($sortby !~ /^(username|domain|section|fullname|id)$/) {
 1066:         $sortby = 'username';
 1067:     }
 1068:     # Print out header 
 1069:     if ($mode eq 'view') {
 1070:         if ($linkto eq 'aboutme') {
 1071:             $r->print('Select a user name to view the users personal page.');
 1072:         } elsif ($linkto eq 'modify') {
 1073:             $r->print('Select a user name to modify the students information');
 1074:         }
 1075:         $r->print(<<END);
 1076: 
 1077: <input type="hidden" name="sortby" value="$sortby" />
 1078: <input type="hidden" name="sname"  value="" />
 1079: <input type="hidden" name="sdom"   value="" />
 1080: <p>
 1081: <table border=2>
 1082: <tr><th>
 1083:        <a href="javascript:document.studentform.sortby.value='username';document.studentform.submit();">username</a>
 1084:     </th><th>
 1085:        <a href="javascript:document.studentform.sortby.value='domain';document.studentform.submit();">domain</a>
 1086:     </th><th>
 1087:        <a href="javascript:document.studentform.sortby.value='id';document.studentform.submit();">ID</a>
 1088:     </th><th>
 1089:        <a href="javascript:document.studentform.sortby.value='fullname';document.studentform.submit();">student name</a>
 1090:     </th><th>
 1091:        <a href="javascript:document.studentform.sortby.value='section';document.studentform.submit();">section</a>
 1092:     </th>
 1093: </tr>
 1094: END
 1095:     } elsif ($mode eq 'csv') {
 1096:         if($statusmode eq 'Expired') {
 1097:             $r->print('"Students with expired roles"');
 1098:         }
 1099:         if ($statusmode eq 'Any') {
 1100:             $r->print('"'.join('","',("username","domain","ID","student name",
 1101:                                       "section","status")).'"'."\n");
 1102:         } else {
 1103:             $r->print('"'.join('","',("username","domain","ID","student name",
 1104:                                       "section")).'"'."\n");
 1105:         }
 1106:     } elsif ($mode eq 'excel') {
 1107:         # Create the excel spreadsheet
 1108:         $excel_filename = '/prtspool/'.
 1109:             $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
 1110:                 time.'_'.rand(1000000000).'.xls';
 1111:         $excel_workbook = Spreadsheet::WriteExcel->new('/home/httpd'.
 1112:                                                        $excel_filename);
 1113:         $excel_workbook->set_tempdir('/home/httpd/perl/tmp');
 1114:         $excel_sheet = $excel_workbook->addworksheet('classlist');
 1115:         #
 1116:         my $description = 'Class List for '.
 1117:             $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 1118:         $excel_sheet->write($row++,0,$description);
 1119:         #
 1120:         $excel_sheet->write($row++,0,["username","domain","ID",
 1121:                                       "student name","section","status"]);
 1122:     }
 1123:     #
 1124:     # Sort the students
 1125:     my %index;
 1126:     my $i;
 1127:     foreach (@$keylist) {
 1128:         $index{$_} = $i++;
 1129:     }
 1130:     my $index  = $index{$sortby};
 1131:     my $second = $index{'username'};
 1132:     my $third  = $index{'domain'};
 1133:     my @Sorted_Students = sort {
 1134:         lc($classlist->{$a}->[$index])  cmp lc($classlist->{$b}->[$index])
 1135:             ||
 1136:         lc($classlist->{$a}->[$second]) cmp lc($classlist->{$b}->[$second])
 1137:             ||
 1138:         lc($classlist->{$a}->[$third]) cmp lc($classlist->{$b}->[$third])
 1139:         } (keys(%$classlist));
 1140:     foreach my $student (@Sorted_Students) {
 1141:         my $username = $classlist->{$student}->[$index{'username'}];
 1142:         my $domain   = $classlist->{$student}->[$index{'domain'}];
 1143:         my $section  = $classlist->{$student}->[$index{'section'}];
 1144:         my $name     = $classlist->{$student}->[$index{'fullname'}];
 1145:         my $id       = $classlist->{$student}->[$index{'id'}];
 1146:         my $status   = $classlist->{$student}->[$index{'status'}];
 1147:         next if (($statusmode ne 'Any') && ($status ne $statusmode));
 1148:         if ($mode eq 'view') {
 1149:             $r->print("<tr>\n    <td>\n        ");
 1150:             if ($linkto eq 'nothing') {
 1151:                 $r->print($username);
 1152:             } elsif ($linkto eq 'aboutme') {
 1153:                 $r->print(&Apache::loncommon::aboutmewrapper($username,
 1154:                                                              $username,
 1155:                                                              $domain));
 1156:             } elsif ($linkto eq 'modify') {
 1157:                 $r->print('<a href="'.
 1158:                           "javascript:document.studentform.sname.value='".
 1159:                           $username.
 1160:                           "';document.studentform.sdom.value='".$domain.
 1161:                           "';document.studentform.state.value='selected".
 1162:                           "';document.studentform.submit();".'">'.
 1163:                           $username."</a>\n");
 1164:             }
 1165:             $r->print(<<"END");
 1166:     </td>
 1167:     <td>$domain</td>
 1168:     <td>$id</td>
 1169:     <td>$name</td>
 1170:     <td>$section</td>
 1171: </tr>
 1172: END
 1173:         } elsif ($mode eq 'csv') {
 1174:             # no need to bother with $linkto
 1175:             my @line = ();
 1176:             foreach ($username,$domain,$id,$name,$section) {
 1177:                 push @line,&Apache::loncommon::csv_translate($_);
 1178:             }
 1179:             if ($statusmode eq 'Any') {
 1180:                 push @line,&Apache::loncommon::csv_translate($status);
 1181:             }
 1182:             my $tmp = $";
 1183:             $" = '","';
 1184:             $r->print("\"@line\"\n");
 1185:             $" = $tmp;
 1186:         } elsif ($mode eq 'excel') {
 1187:             $excel_sheet->write($row++,0,[$username,$domain,$id,
 1188:                                           $name,$section,$status]);
 1189:         }
 1190:     }
 1191:     if ($mode eq 'view') {
 1192:         $r->print('</table><br>');
 1193:     } elsif ($mode eq 'excel') {
 1194:         $excel_workbook->close();
 1195:         $r->print('<p><a href="'.$excel_filename.'">'.
 1196:                   'Your Excel spreadsheet</a> is ready for download.</p>'."\n");
 1197:     }
 1198: }
 1199: 
 1200: 
 1201: #
 1202: # print out form for modification of a single students data
 1203: #
 1204: sub print_modify_student_form {
 1205:     my $r = shift();
 1206:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1207:                                             ['sdom','sname']);    
 1208:     my $sname  = $ENV{'form.sname'};
 1209:     my $sdom   = $ENV{'form.sdom'};
 1210:     my $sortby = $ENV{'form.sortby'};
 1211:     # determine the students name information
 1212:     my %info=&Apache::lonnet::get('environment',
 1213:                                   ['firstname','middlename',
 1214:                                    'lastname','generation','id'],
 1215:                                   $sdom, $sname);
 1216:     my ($tmp) = keys(%info);
 1217:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1218:         $r->print('<font color="#ff0000" size="+2">Error</font>'.
 1219:                   '<p>'.
 1220:                   'Unable to retrieve environment data for '.$sname.
 1221:                   'in domain '.$sdom.'</p><p>'.
 1222:                   'Please contact your LON-CAPA administrator '.
 1223:                   'regarding this situation.</p></body></html>');
 1224:         return;
 1225:     }
 1226:     # determine the students starting and ending times and section
 1227:     my ($starttime,$endtime,$section) = &get_enrollment_data($sname,$sdom);
 1228:     if ($starttime =~ /^error/) {
 1229:         $r->print('<h2>Error</h2>');
 1230:         $r->print('<p>'.$starttime.'</p>');
 1231:         return;
 1232:     }
 1233:     # Deal with date forms
 1234:     my $date_table = &date_setting_table($starttime,$endtime);
 1235:     #
 1236:     if (! exists($ENV{'form.Status'}) || 
 1237:         $ENV{'form.Status'} !~ /^(Any|Expired|Active)$/) {
 1238:         $ENV{'form.Status'} = 'crap';
 1239:     }
 1240:     # Make sure student is enrolled in course    
 1241:     $r->print(<<END);
 1242: <p>
 1243: <font size="+1">
 1244: Only domain coordinators can change a users password.
 1245: </font>
 1246: </p>
 1247: <input type="hidden" name="slogin"  value="$sname"  />
 1248: <input type="hidden" name="sdomain" value="$sdom" />
 1249: <input type="hidden" name="action"  value="modifystudent" />
 1250: <input type="hidden" name="state"   value="done" />
 1251: <input type="hidden" name="sortby"  value="$sortby" />
 1252: <input type="hidden" name="Status"  value="$ENV{'form.Status'}" />
 1253: 
 1254: <h2>Modify Enrollment for $info{'firstname'} $info{'middlename'} 
 1255: $info{'lastname'} $info{'generation'}, $sname\@$sdom</h2>
 1256: <p>
 1257: <b>Student Name</b>
 1258: <table>
 1259: <tr><th>First</th><th>Middle</th><th>Last</th><th>Generation</th></tr>
 1260: <tr><td>
 1261: <input type="text" name="firstname"  value="$info{'firstname'}"  /></td><td>
 1262: <input type="text" name="middlename" value="$info{'middlename'}" /></td><td>
 1263: <input type="text" name="lastname"   value="$info{'lastname'}"   /></td><td>
 1264: <input type="text" name="generation" value="$info{'generation'}" /></td></tr>
 1265: </table>
 1266: </p><p>
 1267: <b>Student ID</b>: <input type="text" name="id" value="$info{'id'}" size="12"/>
 1268: </p><p>
 1269: <input type="checkbox" name="forceid" > 
 1270: Disable ID/Student Number Safeguard and Force Change of Conflicting IDs
 1271: (only do if you know what you are doing)
 1272: </p><p>
 1273: <b>Section</b>: <input type="text" name="section" value="$section" size="4"/>
 1274: </p>
 1275: <p>$date_table</p>
 1276: <input type="submit" value="Submit Modifications" />
 1277: </body></html>
 1278: END
 1279:     return;
 1280: }
 1281: 
 1282: #
 1283: # modify a single students section 
 1284: #
 1285: sub modify_single_student {
 1286:     my $r = shift;
 1287:     #
 1288:     # Remove non alphanumeric values from the section
 1289:     $ENV{'form.section'} =~ s/\W//g;
 1290:     #
 1291:     # Do the date defaults first
 1292:     my ($starttime,$endtime) = &get_dates_from_form();
 1293:     if ($ENV{'form.makedatesdefault'}) {
 1294:         $r->print(&make_dates_default($starttime,$endtime));
 1295:     }
 1296:     # Get the 'sortby' and 'Status' variables so the user goes back to their
 1297:     # previous screen
 1298:     my $sortby = $ENV{'form.sortby'};
 1299:     my $status = $ENV{'form.Status'};
 1300:     #
 1301:     # We always need this information
 1302:     my $slogin     = $ENV{'form.slogin'};
 1303:     my $sdom       = $ENV{'form.sdomain'};
 1304:     #
 1305:     # Get the old data
 1306:     my %old=&Apache::lonnet::get('environment',
 1307:                                  ['firstname','middlename',
 1308:                                   'lastname','generation','id'],
 1309:                                  $sdom, $slogin);
 1310:     $old{'section'} = &Apache::lonnet::getsection($sdom,$slogin,
 1311:                                                   $ENV{'request.course.id'});
 1312:     my ($tmp) = keys(%old);
 1313:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1314:         $r->print("There was an error determining the environment values ".
 1315:                   " for $slogin \@ $sdom.");
 1316:         return;
 1317:     }
 1318:     undef $tmp;
 1319:     #
 1320:     # Get the new data
 1321:     my $firstname  = $ENV{'form.firstname'};
 1322:     my $middlename = $ENV{'form.middlename'};
 1323:     my $lastname   = $ENV{'form.lastname'};
 1324:     my $generation = $ENV{'form.generation'};
 1325:     my $section    = $ENV{'form.section'};
 1326:     my $courseid   = $ENV{'request.course.id'};
 1327:     my $sid        = $ENV{'form.id'};
 1328:     my $displayable_starttime = localtime($starttime);
 1329:     my $displayable_endtime   = localtime($endtime);
 1330:     # 
 1331:     # check for forceid override
 1332:     if ((defined($old{'id'})) && ($old{'id'} ne '') && 
 1333:         ($sid ne $old{'id'}) && (! exists($ENV{'form.forceid'}))) {
 1334:         $r->print("<font color=\"ff0000\">You changed the students id ".
 1335:                   " but did not disable the ID change safeguard.".
 1336:                   "  The students id will not be changed.</font>");
 1337:         $sid = $old{'id'};
 1338:     }
 1339:     #
 1340:     # talk to the user about what we are going to do
 1341:     $r->print(<<END);
 1342:     <h2>Modifying data for user $slogin \@ $sdom </h2>
 1343: <h3>Student Information</h3>
 1344: <table rules="rows" border="1" cellpadding="3" >
 1345: <tr>
 1346:     <th> Field </th>
 1347:     <th> Old Value </th>
 1348:     <th> New Value </th>
 1349: </tr>
 1350: <tr>
 1351:     <td> <b>First name</b> </td>
 1352:     <td> $old{'firstname'} </td>
 1353:     <td> $firstname </td>
 1354: </tr><tr>
 1355:     <td> <b>Middle name</b> </td>
 1356:     <td> $old{'middlename'} </td>
 1357:     <td> $middlename </td>
 1358: </tr><tr>
 1359:     <td> <b>Last name</b> </td>
 1360:     <td> $old{'lastname'} </td>
 1361:     <td> $lastname </td>
 1362: </tr><tr>
 1363:     <td> <b>Generation</b> </td>
 1364:     <td> $old{'generation'} </td>
 1365:     <td> $generation </td>
 1366: </tr><tr>
 1367:     <td> <b>ID</b> </td>
 1368:     <td> $old{'id'} </td>
 1369:     <td> $sid </td>
 1370: </tr><tr>
 1371:     <td> <b>Section</b> </td>
 1372:     <td> $old{'section'} </td>
 1373:     <td> $section</td>
 1374: </tr>
 1375: </table>
 1376: <h3>Role Information</h3>
 1377: <table>
 1378: <tr><td align="right"><b>Start Time:</b></td><td> $displayable_starttime </td></tr>
 1379: <tr><td align="right"><b>End Time:</b></td><td> $displayable_endtime   </td></tr>
 1380: </table>
 1381: <p>
 1382: END
 1383:     #
 1384:     # Send request(s) to modify data (final undef is for 'desiredhost',
 1385:     # which is a moot point because the student already has an account.
 1386:     my $modify_section_results = &modifystudent($sdom,$slogin,
 1387:                                                 $ENV{'request.course.id'},
 1388:                                                 $section,undef);
 1389:     if ($modify_section_results !~ /^ok/) {
 1390:         $r->print("An error occured during the attempt to change the ".
 1391:                   "section for this student.<br />");
 1392:     }
 1393:     my $roleresults = &Apache::lonnet::modifystudent
 1394:         ($sdom,$slogin,$sid,undef,undef,$firstname,$middlename,$lastname,
 1395:          $generation,$section,$endtime,$starttime,$ENV{'form.forceid'});
 1396:     if ($roleresults eq 'refused' ) {
 1397:         $r->print("Your request to change the role information for this ".
 1398:                   "student was refused.  You do not appear to have ".
 1399:                   "sufficient authority to change student information.");
 1400:     } elsif ($roleresults !~ /ok/) {
 1401:         $r->print("An error occurred during the attempt to change the role".
 1402:                   " information for this student.  <br />".
 1403:                   "The error reported was ".
 1404:                   $roleresults);
 1405:         &Apache::lonnet::logthis("londropadd:failed attempt to modify student".
 1406:                                  " data for ".$slogin." \@ ".$sdom." by ".
 1407:                                  $ENV{'user.name'}." \@ ".$ENV{'user.domain'}.
 1408:                                  ":".$roleresults);
 1409:     } else { # everything is okay!
 1410:         $r->print("Student information updated successfully. <br />".
 1411:                   "The student must log out and log in again to see ".
 1412:                   "these changes.");
 1413:     }
 1414:     $r->print(<<END);
 1415: </p><p>
 1416: <input type="hidden" name="action" value="modifystudent" />
 1417: <input type="hidden" name="sortby" value="$sortby" />
 1418: <input type="hidden" name="Status" value="$status" />
 1419: <a href="javascript:document.studentform.submit();">Modify another students data</a>
 1420: </body></html>
 1421: END
 1422:     return;
 1423: }
 1424: 
 1425: sub get_enrollment_data {
 1426:     my ($sname,$sdomain) = @_;
 1427:     my $courseid = $ENV{'request.course.id'};
 1428:     $courseid =~ s:_:/:g;
 1429:     my %roles = &Apache::lonnet::dump('roles',$sdomain,$sname);
 1430:     my ($tmp) = keys(%roles);
 1431:     # Bail out if we were unable to get the students roles
 1432:     return ('error'.$tmp) if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 1433:     # Go through the roles looking for enrollment in this course
 1434:     my ($end,$start) = (undef,undef);
 1435:     my $section = '';
 1436:     my $count = scalar(keys(%roles));
 1437:     while (my ($course,$role) = each(%roles)) {
 1438:         if ($course=~ /^\/$courseid\/*\s*(\w+)*_st$/ ) {
 1439:             #
 1440:             # Get active role
 1441:             $section=$1;
 1442:             (undef,$end,$start)=split(/\_/,$role);
 1443:             my $now=time;
 1444:             my $notactive=0;
 1445:             if ($start) {
 1446:                 if ($now<$start) { $notactive=1; }
 1447:             }
 1448:             if ($end) {
 1449:                 if ($now>$end) { $notactive=1; }
 1450:             } 
 1451:             unless ($notactive) { return ($start,$end,$section); }
 1452:         }
 1453:     }
 1454:     return ($start,$end,$section);
 1455: }
 1456: 
 1457: #################################################
 1458: #################################################
 1459: 
 1460: =pod
 1461: 
 1462: =item show_drop_list
 1463: 
 1464: Display a list of students to drop
 1465: Inputs: 
 1466: 
 1467: =over 4
 1468: 
 1469: =item $r, Apache request
 1470: 
 1471: =item $classlist, hash pointer returned from loncoursedata::get_classlist();
 1472: 
 1473: =item $keylist, array pointer returned from loncoursedata::get_classlist() 
 1474: which describes the order elements are stored in the %$classlist values.
 1475: 
 1476: =item $nosort, if true, sorting links are omitted.
 1477: 
 1478: =back
 1479: 
 1480: =cut
 1481: 
 1482: #################################################
 1483: #################################################
 1484: sub show_drop_list {
 1485:     my ($r,$classlist,$keylist,$nosort)=@_;
 1486:     my $cid=$ENV{'request.course.id'};
 1487:     if (! exists($ENV{'form.sortby'})) {
 1488:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1489:                                                 ['sortby']);
 1490:     }
 1491:     my $sortby = $ENV{'form.sortby'};
 1492:     if ($sortby !~ /^(username|domain|section|fullname|id)$/) {
 1493:         $sortby = 'username';
 1494:     }
 1495:     #
 1496:     my $action = "drop";
 1497:     $r->print(<<END);
 1498: <input type="hidden" name="sortby" value="$sortby" />
 1499: <input type="hidden" name="action" value="$action" />
 1500: <input type="hidden" name="state"  value="done" />
 1501: <script>
 1502: function checkAll(field) {
 1503:     for (i = 0; i < field.length; i++)
 1504:         field[i].checked = true ;
 1505: }
 1506: 
 1507: function uncheckAll(field) {
 1508:     for (i = 0; i < field.length; i++)
 1509:         field[i].checked = false ;
 1510: }
 1511: </script>
 1512: <p>
 1513: <input type="hidden" name="phase" value="four">
 1514: END
 1515: 
 1516:     if ($nosort) {
 1517:         $r->print(<<END);
 1518: <table border=2>
 1519: <tr>
 1520:     <th>&nbsp;</th>
 1521:     <th>username</th>
 1522:     <th>domain</th>
 1523:     <th>ID</th>
 1524:     <th>student name</th>
 1525:     <th>section</th>
 1526: </tr>
 1527: END
 1528: 
 1529:     } else  {
 1530:         $r->print(<<END);
 1531: <table border=2>
 1532: <tr><th>&nbsp;</th>
 1533:     <th>
 1534:        <a href="/adm/dropadd?action=$action&sortby=username">username</a>
 1535:     </th><th>
 1536:        <a href="/adm/dropadd?action=$action&sortby=domain">domain</a>
 1537:     </th><th>
 1538:        <a href="/adm/dropadd?action=$action&sortby=id">ID</a>
 1539:     </th><th>
 1540:        <a href="/adm/dropadd?action=$action&sortby=fullname">student name</a>
 1541:     </th><th>
 1542:        <a href="/adm/dropadd?action=$action&sortby=section">section</a>
 1543:     </th>
 1544: </tr>
 1545: END
 1546:     }
 1547:     #
 1548:     # Sort the students
 1549:     my %index;
 1550:     my $i;
 1551:     foreach (@$keylist) {
 1552:         $index{$_} = $i++;
 1553:     }
 1554:     my $index  = $index{$sortby};
 1555:     my $second = $index{'username'};
 1556:     my $third  = $index{'domain'};
 1557:     my @Sorted_Students = sort {
 1558:         lc($classlist->{$a}->[$index])  cmp lc($classlist->{$b}->[$index])
 1559:             ||
 1560:         lc($classlist->{$a}->[$second]) cmp lc($classlist->{$b}->[$second])
 1561:             ||
 1562:         lc($classlist->{$a}->[$third]) cmp lc($classlist->{$b}->[$third])
 1563:         } (keys(%$classlist));
 1564:     foreach my $student (@Sorted_Students) {
 1565:         my $error;
 1566:         my $username = $classlist->{$student}->[$index{'username'}];
 1567:         my $domain   = $classlist->{$student}->[$index{'domain'}];
 1568:         my $section  = $classlist->{$student}->[$index{'section'}];
 1569:         my $name     = $classlist->{$student}->[$index{'fullname'}];
 1570:         my $id       = $classlist->{$student}->[$index{'id'}];
 1571:         my $status   = $classlist->{$student}->[$index{'status'}];
 1572:         next if ($status ne 'Active');
 1573:         #
 1574:         $r->print(<<"END");
 1575: <tr>
 1576:     <td><input type="checkbox" name="droplist" value="$student"></td>
 1577:     <td>$username</td>
 1578:     <td>$domain</td>
 1579:     <td>$id</td>
 1580:     <td>$name</td>
 1581:     <td>$section</td>
 1582: </tr>
 1583: END
 1584:     }
 1585:     $r->print('</table><br>');
 1586:     $r->print(<<"END");
 1587: </p><p>
 1588: <input type="button" value="check all" onclick="javascript:checkAll(document.studentform.droplist)"> &nbsp;
 1589: <input type="button" value="uncheck all" onclick="javascript:uncheckAll(document.studentform.droplist)"> 
 1590: <p><input type=submit value="Drop Students"></p>
 1591: END
 1592:     return;
 1593: }
 1594: 
 1595: #
 1596: # Print out the initial form to get the courselist file
 1597: #
 1598: sub print_first_courselist_upload_form {
 1599:     my $r=shift;
 1600:     my $str;
 1601:     $str  = '<input type="hidden" name="phase" value="two">';
 1602:     $str .= '<input type="hidden" name="action" value="upload" />';
 1603:     $str .= '<input type="hidden"   name="state"  value="got_file" />';
 1604:     $str .= "<h3>".&mt('Upload a class list')."</h3>\n";
 1605:     $str .= &Apache::loncommon::upfile_select_html();
 1606:     $str .= "<p>\n";
 1607:     $str .= '<input type="submit" name="fileupload" value="'.
 1608:         &mt('Upload class list').'">'."\n";
 1609:     $str .= '<input type="checkbox" name="noFirstLine" /> '.
 1610:         &mt('Ignore First Line')."</p>\n";
 1611:     $str .= &Apache::loncommon::help_open_topic("Course_Create_Class_List",
 1612:                          "How do I create a class list from a spreadsheet").
 1613:                              "<br />\n";
 1614:     $str .= &Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 1615:                            "How do I create a CSV file from a spreadsheet").
 1616:                                "<br />\n";
 1617:     $str .= "</body>\n</html>\n";
 1618:     $r->print($str);
 1619:     return;
 1620: }
 1621: 
 1622: # ================================================= Drop/Add from uploaded file
 1623: sub upfile_drop_add {
 1624:     my $r=shift;
 1625:     &Apache::loncommon::load_tmp_file($r);
 1626:     my @studentdata=&Apache::loncommon::upfile_record_sep();
 1627:     if($ENV{'form.noFirstLine'}){shift(@studentdata);}
 1628:     my @keyfields = split(/\,/,$ENV{'form.keyfields'});
 1629:     my $cid = $ENV{'request.course.id'};
 1630:     my %fields=();
 1631:     for (my $i=0; $i<=$ENV{'form.nfields'}; $i++) {
 1632:         if ($ENV{'form.upfile_associate'} eq 'reverse') {
 1633:             if ($ENV{'form.f'.$i} ne 'none') {
 1634:                 $fields{$keyfields[$i]}=$ENV{'form.f'.$i};
 1635:             }
 1636:         } else {
 1637:             $fields{$ENV{'form.f'.$i}}=$keyfields[$i];
 1638:         }
 1639:     }
 1640:     #
 1641:     my ($startdate,$enddate) = &get_dates_from_form();
 1642:     if ($ENV{'form.makedatesdefault'}) {
 1643:         $r->print(&make_dates_default($startdate,$enddate));
 1644:     }
 1645:     # Determine domain and desired host (home server)
 1646:     my $domain=$ENV{'form.lcdomain'};
 1647:     my $desiredhost = $ENV{'form.lcserver'};
 1648:     if (lc($desiredhost) eq 'default') {
 1649:         $desiredhost = undef;
 1650:     } else {
 1651:         my %home_servers = &Apache::loncommon::get_library_servers($domain);
 1652:         if (! exists($home_servers{$desiredhost})) {
 1653:             $r->print('<font color="#ff0000">'.&mt('Error').'</font>'.
 1654:                       &mt('Invalid home server specified'));
 1655:             $r->print("</body>\n</html>\n");
 1656:             return;
 1657:         }
 1658:     }
 1659:     # Determine authentication mechanism
 1660:     my $amode  = '';
 1661:     my $genpwd = '';
 1662:     if ($ENV{'form.login'} eq 'krb') {
 1663:         $amode='krb';
 1664: 	$amode.=$ENV{'form.krbver'};
 1665:         $genpwd=$ENV{'form.krbarg'};
 1666:     } elsif ($ENV{'form.login'} eq 'int') {
 1667:         $amode='internal';
 1668:         if ((defined($ENV{'form.intarg'})) && ($ENV{'form.intarg'})) {
 1669:             $genpwd=$ENV{'form.intarg'};
 1670:         }
 1671:     } elsif ($ENV{'form.login'} eq 'loc') {
 1672:         $amode='localauth';
 1673:         if ((defined($ENV{'form.locarg'})) && ($ENV{'form.locarg'})) {
 1674:             $genpwd=$ENV{'form.locarg'};
 1675:         }
 1676:     }
 1677:     if ($amode =~ /^krb/) {
 1678:         if (! defined($genpwd) || $genpwd eq '') {
 1679:             $r->print('<font color="red" size="+1">'.
 1680:                       &mt('Unable to enroll students').'</font>  '.
 1681:                       &mt('No Kerberos domain was specified.').'</p>');
 1682:             $amode = ''; # This causes the loop below to be skipped
 1683:         }
 1684:     }
 1685:     unless (($domain=~/\W/) || ($amode eq '')) {
 1686:         #######################################
 1687:         ##         Enroll Students           ##
 1688:         #######################################
 1689:         $r->print('<h3>'.&mt('Enrolling Students')."</h3>\n<p>\n");
 1690:         my $count=0;
 1691:         my $flushc=0;
 1692:         my %student=();
 1693:         # Get new classlist
 1694:         foreach (@studentdata) {
 1695:             my %entries=&Apache::loncommon::record_sep($_);
 1696:             # Determine student name
 1697:             unless (($entries{$fields{'username'}} eq '') ||
 1698:                     (!defined($entries{$fields{'username'}}))) {
 1699:                 my ($fname, $mname, $lname,$gen) = ('','','','');
 1700:                 if (defined($fields{'names'})) {
 1701:                     ($lname,$fname,$mname)=($entries{$fields{'names'}}=~
 1702:                                             /([^\,]+)\,\s*(\w+)\s*(.*)$/);
 1703:                 } else {
 1704:                     if (defined($fields{'fname'})) {
 1705:                         $fname=$entries{$fields{'fname'}};
 1706:                     }
 1707:                     if (defined($fields{'mname'})) {
 1708:                         $mname=$entries{$fields{'mname'}};
 1709:                     }
 1710:                     if (defined($fields{'lname'})) {
 1711:                         $lname=$entries{$fields{'lname'}};
 1712:                     }
 1713:                     if (defined($fields{'gen'})) {
 1714:                         $gen=$entries{$fields{'gen'}};
 1715:                     }
 1716:                 }
 1717:                 if ($entries{$fields{'username'}}=~/\W/) {
 1718:                     $r->print('<br />'.
 1719:       &mt('<b>[_1]</b>: Unacceptable username for user [_2] [_3] [_4] [_5]',
 1720:           $entries{$fields{'username'}},$fname,$mname,$lname,$gen).
 1721:                               '</b>');
 1722:                 } else {
 1723:                     # determine section number
 1724:                     my $sec='';
 1725:                     my $username=$entries{$fields{'username'}};
 1726:                     if (defined($fields{'sec'})) {
 1727:                         if (defined($entries{$fields{'sec'}})) {
 1728:                             $sec=$entries{$fields{'sec'}};
 1729:                         }
 1730:                     }
 1731:                     # remove non alphanumeric values from section
 1732:                     $sec =~ s/\W//g;
 1733:                     # determine student id number
 1734:                     my $id='';
 1735:                     if (defined($fields{'id'})) {
 1736:                         if (defined($entries{$fields{'id'}})) {
 1737:                             $id=$entries{$fields{'id'}};
 1738:                         }
 1739:                         $id=~tr/A-Z/a-z/;
 1740:                     }
 1741:                     # determine email address
 1742:                     my $email='';
 1743:                     if (defined($fields{'email'})) {
 1744:                         if (defined($entries{$fields{'email'}})) {
 1745:                             $email=$entries{$fields{'email'}};
 1746:                             unless ($email=~/^[^\@]+\@[^\@]+$/) { $email=''; }
 1747:                         }
 1748:                     }
 1749:                     # determine student password
 1750:                     my $password='';
 1751:                     if ($genpwd) { 
 1752:                         $password=$genpwd; 
 1753:                     } else {
 1754:                         if (defined($fields{'ipwd'})) {
 1755:                             if ($entries{$fields{'ipwd'}}) {
 1756:                                 $password=$entries{$fields{'ipwd'}};
 1757:                             }
 1758:                         }
 1759:                     }
 1760:                     # Clean up whitespace
 1761:                     foreach (\$domain,\$username,\$id,\$fname,\$mname,
 1762:                              \$lname,\$gen,\$sec) {
 1763:                         $$_ =~ s/(\s+$|^\s+)//g;
 1764:                     }
 1765:                     if ($password || $ENV{'form.login'} eq 'loc') {
 1766:                         &modifystudent($domain,$username,$cid,$sec,
 1767:                                        $desiredhost);
 1768:                         my $reply=&Apache::lonnet::modifystudent
 1769:                             ($domain,$username,$id,$amode,$password,
 1770:                              $fname,$mname,$lname,$gen,$sec,$enddate,
 1771:                              $startdate,$ENV{'form.forceid'},$desiredhost,
 1772:                              $email);
 1773:                         if ($reply ne 'ok') {
 1774:                             $reply =~ s/^error://;
 1775:                             $r->print('<br />'.
 1776:                 &mt('<b>[_1]</b>:  Unable to enroll: [_2]',$username,$reply));
 1777:          		} else {
 1778:                             $count++; $flushc++;
 1779:                             $student{$username}=1;
 1780:                             $r->print('. ');
 1781:                             if ($flushc>15) {
 1782: 				$r->rflush;
 1783:                                 $flushc=0;
 1784:                             }
 1785:                         }
 1786:                     } else {
 1787:                         $r->print('<br />'.
 1788:       &mt('<b>[_1]</b>: Unable to enroll.  No password specified.',$username)
 1789:                                   );
 1790:                     }
 1791:                 }
 1792:             }
 1793:         } # end of foreach (@studentdata)
 1794:         $r->print("</p>\n<p>\n".&mt('Processed [_1] student(s).',$count).
 1795:                   "</p>\n");
 1796:         $r->print("<p>\n".
 1797:                   &mt('If active, the new role will be available when the '.
 1798:                   'students next log in to LON-CAPA.')."</p>\n");
 1799:         #####################################
 1800:         #           Drop students           #
 1801:         #####################################
 1802:         if ($ENV{'form.fullup'} eq 'yes') {
 1803:             $r->print('<h3>'.&mt('Dropping Students')."</h3>\n");
 1804:             #  Get current classlist
 1805:             my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
 1806:             if (! defined($classlist)) {
 1807:                 $r->print(&mt('There are no students currently enrolled.').
 1808:                           "\n");
 1809:             } else {
 1810:                 # Remove the students we just added from the list of students.
 1811:                 foreach (@studentdata) {
 1812:                     my %entries=&Apache::loncommon::record_sep($_);
 1813:                     unless (($entries{$fields{'username'}} eq '') ||
 1814:                             (!defined($entries{$fields{'username'}}))) {
 1815:                         delete($classlist->{$entries{$fields{'username'}}.
 1816:                                                 ':'.$domain});
 1817:                     }
 1818:                 }
 1819:                 # Print out list of dropped students.
 1820:                 &show_drop_list($r,$classlist,$keylist,'nosort');
 1821:             }
 1822:         }
 1823:     } # end of unless
 1824: }
 1825: 
 1826: # ================================================================== Phase four
 1827: sub drop_student_list {
 1828:     my $r=shift;
 1829:     my $count=0;
 1830:     my @droplist;
 1831:     if (ref($ENV{'form.droplist'})) {
 1832:         @droplist = @{$ENV{'form.droplist'}};
 1833:     } else {
 1834:         @droplist = ($ENV{'form.droplist'});
 1835:     }
 1836:     foreach (@droplist) {
 1837:         my ($uname,$udom)=split(/\:/,$_);
 1838:         # drop student
 1839:         my $result = &modifystudent($udom,$uname,$ENV{'request.course.id'});
 1840:         if ($result eq 'ok' || $result eq 'ok:') {
 1841:             $r->print(&mt('Dropped [_1]',$uname.'@'.$udom).'<br>');
 1842:             $count++;
 1843:         } else {
 1844:             $r->print(
 1845:           &mt('Error dropping [_1]:[_2]',$uname.'@'.$udom,$result).
 1846:                       '<br />');
 1847:         }
 1848:     }
 1849:     $r->print('<p><b>'.&mt('Dropped [_1] student(s).',$count).'</b></p>');
 1850:     $r->print('<p>'.&mt('Re-enrollment will re-activate data.')) if ($count);
 1851: }
 1852: 
 1853: ###################################################################
 1854: ###################################################################
 1855: 
 1856: =pod
 1857: 
 1858: =item &handler
 1859: 
 1860: The typical handler you see in all these modules.  Takes $r, the
 1861: http request, as an argument.  
 1862: 
 1863: The response to the request is governed by two form variables
 1864: 
 1865:  form.action      form.state     response
 1866:  ---------------------------------------------------
 1867:  undefined        undefined      print main menu
 1868:  upload           undefined      print courselist upload menu
 1869:  upload           got_file       deal with uploaded file,
 1870:                                  print the upload managing menu
 1871:  upload           enrolling      enroll students based on upload
 1872:  drop             undefined      print the classlist ready to drop
 1873:  drop             done           drop the selected students
 1874:  enrollstudent    undefined      print student username domain form
 1875:  enrollstudent    gotusername    print single student enroll menu
 1876:  enrollstudent    enrolling      enroll student
 1877:  classlist        undefined      print html classlist
 1878:  classlist        csv            print csv classlist
 1879:  modifystudent    undefined      print classlist to select student to modify
 1880:  modifystudent    selected       print modify student menu
 1881:  modifystudent    done           make modifications to student record
 1882: 
 1883: =cut
 1884: 
 1885: ###################################################################
 1886: ###################################################################
 1887: sub handler {
 1888:     my $r=shift;
 1889:     if ($r->header_only) {
 1890:         &Apache::loncommon::content_type($r,'text/html');
 1891:         $r->send_http_header;
 1892:         return OK;
 1893:     }
 1894:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 1895:                                             ['action','state']);
 1896:     #  Needs to be in a course
 1897:     if (! (($ENV{'request.course.fn'}) &&
 1898:           (&Apache::lonnet::allowed('cst',$ENV{'request.course.id'})))) {
 1899:         # Not in a course, or not allowed to modify parms
 1900:         $ENV{'user.error.msg'}=
 1901:             "/adm/dropadd:cst:0:0:Cannot drop or add students";
 1902:         return HTTP_NOT_ACCEPTABLE; 
 1903:     }
 1904:     #
 1905:     # Only output the header information if they did not request csv format
 1906:     #
 1907:     if (exists($ENV{'form.state'}) && ($ENV{'form.state'} eq 'csv')) {
 1908:         $r->content_type('text/csv');
 1909:     } else {
 1910:         # Start page
 1911:         &Apache::loncommon::content_type($r,'text/html');
 1912:         $r->send_http_header;
 1913:         $r->print(&header());
 1914:     }
 1915:     #
 1916:     # Main switch on form.action and form.state, as appropriate
 1917:     if (! exists($ENV{'form.action'})) {
 1918:         &print_main_menu($r);
 1919:     } elsif ($ENV{'form.action'} eq 'upload') {
 1920:         if (! exists($ENV{'form.state'})) {
 1921:             &print_first_courselist_upload_form($r);            
 1922:         } elsif ($ENV{'form.state'} eq 'got_file') {
 1923:             &print_upload_manager_form($r);
 1924:         } elsif ($ENV{'form.state'} eq 'enrolling') {
 1925:             if ($ENV{'form.datatoken'}) {
 1926:                 &upfile_drop_add($r);
 1927:             } else {
 1928:                 # Hmmm, this is an error
 1929:             }
 1930:         } else {
 1931:             &print_first_courselist_upload_form($r);            
 1932:         }
 1933:     } elsif ($ENV{'form.action'} eq 'drop') {
 1934:         if (! exists($ENV{'form.state'})) {
 1935:             &print_drop_menu($r);
 1936:         } elsif ($ENV{'form.state'} eq 'done') {
 1937:             &drop_student_list($r);
 1938:         } else {
 1939:             &print_drop_menu($r);
 1940:         }
 1941:     } elsif ($ENV{'form.action'} eq 'enrollstudent') {
 1942:         if (! exists($ENV{'form.state'})) {
 1943:             &get_student_username_domain_form($r);
 1944:         } elsif ($ENV{'form.state'} eq 'gotusername') {
 1945:             &print_enroll_single_student_form($r);
 1946:         } elsif ($ENV{'form.state'} eq 'enrolling') {
 1947:             &enroll_single_student($r);
 1948:         } else {
 1949:             &get_student_username_domain_form($r);
 1950:         }
 1951:     } elsif ($ENV{'form.action'} eq 'classlist') {
 1952:         if (! exists($ENV{'form.state'})) {
 1953:             &print_html_classlist($r);
 1954:         } elsif ($ENV{'form.state'} eq 'csv') {
 1955:             &print_formatted_classlist($r,'csv');
 1956:         } elsif ($ENV{'form.state'} eq 'excel') {
 1957:             &print_formatted_classlist($r,'excel');
 1958:         } else {
 1959:             &print_html_classlist($r);
 1960:         }
 1961:     } elsif ($ENV{'form.action'} eq 'modifystudent') {
 1962:         if (! exists($ENV{'form.state'})) {
 1963:             &print_html_classlist($r);
 1964:         } elsif ($ENV{'form.state'} eq 'selected') {
 1965:             &print_modify_student_form($r);
 1966:         } elsif ($ENV{'form.state'} eq 'done') {
 1967:             &modify_single_student($r);
 1968:         } else {
 1969:             &print_html_classlist($r);
 1970:         }        
 1971:     } else {
 1972:         # We should not end up here, but I guess it is possible
 1973:         &Apache::lonnet::logthis("Undetermined state in londropadd.pm.  ".
 1974:                                  "form.action = ".$ENV{'form.action'}.
 1975:                                  "Someone should fix this.");
 1976:         &print_main_menu($r);
 1977:     }
 1978:     #
 1979:     # Finish up
 1980:     if (exists($ENV{'form.state'}) && ($ENV{'form.state'} eq 'csv')) {
 1981:         $r->print("\n");
 1982:     } else {
 1983:         $r->print('</form></body></html>');
 1984:     }
 1985:     return OK;
 1986: }
 1987: 
 1988: ###################################################################
 1989: ###################################################################
 1990: 
 1991: 1;
 1992: __END__
 1993: 
 1994: 

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