File:  [LON-CAPA] / loncom / interface / Attic / londropadd.pm
Revision 1.99: download - view: text, annotated - select for diffs
Thu Jan 15 19:27:05 2004 UTC (20 years, 6 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Bug 2140: Classlist upload should remember field choices.

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

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