File:  [LON-CAPA] / loncom / interface / Attic / londropadd.pm
Revision 1.133: download - view: text, annotated - select for diffs
Mon Nov 21 19:44:14 2005 UTC (18 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: version_2_1_2, version_2_1_1, version_2_1_0, version_2_0_99_1, HEAD
- remivng course groups links

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

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