File:  [LON-CAPA] / loncom / interface / Attic / londropadd.pm
Revision 1.98: download - view: text, annotated - select for diffs
Thu Jan 15 03:18:19 2004 UTC (20 years, 5 months ago) by www
Branches: MAIN
CVS tags: HEAD
Help buttons

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

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