Annotation of loncom/interface/lonuserutils.pm, revision 1.2

1.1       raeburn     1: # The LearningOnline Network with CAPA
                      2: # Utility functions for managing LON-CAPA user accounts
                      3: #
1.2     ! raeburn     4: # $Id: lonuserutils.pm,v 1.1 2007/10/22 22:16:38 raeburn Exp $
1.1       raeburn     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: # /home/httpd/html/adm/gpl.txt
                     24: #
                     25: # http://www.lon-capa.org/
                     26: #
                     27: #
                     28: ###############################################################
                     29: ###############################################################
                     30: 
                     31: package Apache::lonuserutils;
                     32: 
                     33: use strict;
                     34: use Apache::lonnet;
                     35: use Apache::loncommon();
                     36: use Apache::lonhtmlcommon;
                     37: use Apache::lonlocal;
                     38: use LONCAPA();
                     39: 
                     40: ###############################################################
                     41: ###############################################################
                     42: # Drop student from all sections of a course, except optional $csec
                     43: sub modifystudent {
                     44:     my ($udom,$unam,$courseid,$csec,$desiredhost)=@_;
                     45:     # if $csec is undefined, drop the student from all the courses matching
                     46:     # this one.  If $csec is defined, drop them from all other sections of
                     47:     # this course and add them to section $csec
                     48:     my $cdom = $env{'course.'.$courseid.'.domain'};
                     49:     my $cnum = $env{'course.'.$courseid.'.num'};
                     50:     my %roles = &Apache::lonnet::dump('roles',$udom,$unam);
                     51:     my ($tmp) = keys(%roles);
                     52:     # Bail out if we were unable to get the students roles
                     53:     return "$1" if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                     54:     # Go through the roles looking for enrollment in this course
                     55:     my $result = '';
                     56:     foreach my $course (keys(%roles)) {
                     57:         if ($course=~m{^/\Q$cdom\E/\Q$cnum\E(?:\/)*(?:\s+)*(\w+)*\_st$}) {
                     58:             # We are in this course
                     59:             my $section=$1;
                     60:             $section='' if ($course eq "/$cdom/$cnum".'_st');
                     61:             if (defined($csec) && $section eq $csec) {
                     62:                 $result .= 'ok:';
                     63:             } elsif ( ((!$section) && (!$csec)) || ($section ne $csec) ) {
                     64:                 my (undef,$end,$start)=split(/\_/,$roles{$course});
                     65:                 my $now=time;
                     66:                 # if this is an active role
                     67:                 if (!($start && ($now<$start)) || !($end && ($now>$end))) {
                     68:                     my $reply=&Apache::lonnet::modifystudent
                     69:                         # dom  name  id mode pass     f     m     l     g
                     70:                         ($udom,$unam,'',  '',  '',undef,undef,undef,undef,
                     71:                          $section,time,undef,undef,$desiredhost);
                     72:                     $result .= $reply.':';
                     73:                 }
                     74:             }
                     75:         }
                     76:     }
                     77:     if ($result eq '') {
                     78:         $result = 'Unable to find section for this student';
                     79:     } else {
                     80:         $result =~ s/(ok:)+/ok/g;
                     81:     }
                     82:     return $result;
                     83: }
                     84: 
                     85: sub modifyuserrole {
                     86:     my ($context,$setting,$changeauth,$cid,$udom,$uname,$uid,$umode,$upass,
                     87:         $first,$middle,$last,$gene,$sec,$forceid,$desiredhome,$email,$role,
                     88:         $end,$start) = @_;
                     89:     my ($scope,$userresult,$authresult,$roleresult);
                     90:     if ($setting eq 'course' || $context eq 'course') {
                     91:         $scope = '/'.$cid;
                     92:         $scope =~ s/\_/\//g;
                     93:         if ($role ne 'cc' && $sec ne '') {
                     94:             $scope .='/'.$sec;
                     95:         }
                     96:     } elsif ($setting eq 'domain') {
                     97:         $scope = '/'.$env{'request.role.domain'}.'/';
                     98:     } elsif ($setting eq 'construction_space') {
                     99:         $scope =  '/'.$env{'user.domain'}.'/'.$env{'user.name'};
                    100:     }
                    101:     if ($context eq 'domain') {
                    102:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
                    103:         if ($uhome ne 'no_host') {
                    104:             if (($changeauth) && (&Apache::lonnet::allowed('mau',$udom))) {
                    105:                 if ((($umode =~ /^krb4|krb5|internal$/) && $upass ne '') ||
                    106:                     ($umode eq 'localauth')) {
                    107:                     $authresult = &Apache::lonnet::modifyuserauth($udom,$uname,$umode,$upass);
                    108:                 }
                    109:             }
                    110:         }
                    111:     }
                    112:     $userresult =
                    113:         &Apache::lonnet::modifyuser($udom,$uname,$uid,$umode,$upass,$first,
                    114:                                     $middle,$last,$gene,$forceid,$desiredhome,
                    115:                                     $email,$role,$start,$end);
                    116:     if ($userresult eq 'ok') {
                    117:         if ($role ne '') { 
                    118:             $roleresult = &Apache::lonnet::assignrole($udom,$uname,$scope,
                    119:                                                       $role,$end,$start);
                    120:         }
                    121:     }
                    122:     return ($userresult,$authresult,$roleresult);
                    123: }
                    124: 
                    125: ###############################################################
                    126: ###############################################################
1.2     ! raeburn   127: # build a role type and role selection form
        !           128: sub domain_roles_select {
        !           129:     # Set up the role type and role selection boxes when in 
        !           130:     # domain context   
        !           131:     #
        !           132:     # Role types
        !           133:     my @roletypes = ('domain','construction_space','course');
        !           134:     my %lt = &role_type_names();
1.1       raeburn   135:     #
                    136:     # build up the menu information to be passed to
                    137:     # &Apache::loncommon::linked_select_forms
                    138:     my %select_menus;
1.2     ! raeburn   139:     if ($env{'form.roletype'} eq '') {
        !           140:         $env{'form.roletype'} = 'domain';
        !           141:     }
        !           142:     foreach my $roletype (@roletypes) {
1.1       raeburn   143:         # set up the text for this domain
1.2     ! raeburn   144:         $select_menus{$roletype}->{'text'}= $lt{$roletype};
1.1       raeburn   145:         # we want a choice of 'default' as the default in the second menu
1.2     ! raeburn   146:         if ($env{'form.roletype'} ne '') {
        !           147:             $select_menus{$roletype}->{'default'} = $env{'form.showrole'};
        !           148:         } else { 
        !           149:             $select_menus{$roletype}->{'default'} = 'Any';
        !           150:         }
1.1       raeburn   151:         # Now build up the other items in the second menu
1.2     ! raeburn   152:         my @roles;
        !           153:         if ($roletype eq 'domain') {
        !           154:             @roles = &domain_roles();
        !           155:         } elsif ($roletype eq 'construction_space') {
        !           156:             @roles = &construction_space_roles();
        !           157:         } else {
        !           158:             @roles = &course_roles('domain');
1.1       raeburn   159:         }
1.2     ! raeburn   160:         my $order = ['Any',@roles];
        !           161:         $select_menus{$roletype}->{'order'} = $order; 
        !           162:         foreach my $role (@roles) {
        !           163:             $select_menus{$roletype}->{'select2'}->{$role} = 
        !           164:                           &Apache::lonnet::plaintext($role);
        !           165:         }
        !           166:         $select_menus{$roletype}->{'select2'}->{'Any'} = &mt('Any');
1.1       raeburn   167:     }
1.2     ! raeburn   168:     my $result = &Apache::loncommon::linked_select_forms
        !           169:         ('studentform',('&nbsp;'x3).&mt('Role: '),$env{'form.roletype'},
        !           170:          'roletype','showrole',\%select_menus,['domain','construction_space','course']);
1.1       raeburn   171:     return $result;
                    172: }
                    173: 
                    174: ###############################################################
                    175: ###############################################################
                    176: sub hidden_input {
                    177:     my ($name,$value) = @_;
                    178:     return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
                    179: }
                    180: 
                    181: sub print_upload_manager_header {
                    182:     my ($r,$datatoken,$distotal,$krbdefdom,$context)=@_;
                    183:     my $javascript;
                    184:     #
                    185:     if (! exists($env{'form.upfile_associate'})) {
                    186:         $env{'form.upfile_associate'} = 'forward';
                    187:     }
                    188:     if ($env{'form.associate'} eq 'Reverse Association') {
                    189:         if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                    190:             $env{'form.upfile_associate'} = 'reverse';
                    191:         } else {
                    192:             $env{'form.upfile_associate'} = 'forward';
                    193:         }
                    194:     }
                    195:     if ($env{'form.upfile_associate'} eq 'reverse') {
                    196:         $javascript=&upload_manager_javascript_reverse_associate();
                    197:     } else {
                    198:         $javascript=&upload_manager_javascript_forward_associate();
                    199:     }
                    200:     #
                    201:     # Deal with restored settings
                    202:     my $password_choice = '';
                    203:     if (exists($env{'form.ipwd_choice'}) &&
                    204:         $env{'form.ipwd_choice'} ne '') {
                    205:         # If a column was specified for password, assume it is for an
                    206:         # internal password.  This is a bug waiting to be filed (could be
                    207:         # local or krb auth instead of internal) but I do not have the
                    208:         # time to mess around with this now.
                    209:         $password_choice = 'int';
                    210:     }
                    211:     #
                    212:     my $javascript_validations =
                    213:         &javascript_validations('auth',$krbdefdom,$password_choice,undef,
                    214:                                 $env{'request.role.domain'});
                    215:     my $checked=(($env{'form.noFirstLine'})?' checked="checked" ':'');
                    216:     $r->print(&mt('Total number of records found in file: <b>[_1]</b>.',$distotal).
                    217:               "<br />\n");
                    218:     $r->print('<div class="LC_left_float"><h3>'.
                    219:               &mt('Identify fields in uploaded list')."</h3>\n");
                    220:     $r->print(&mt('Enter as many fields as you can.<br /> The system will inform you and bring you back to this page, <br /> if the data selected are insufficient to add users.')."<br />\n");
                    221:     $r->print(&hidden_input('action','upload').
                    222:               &hidden_input('state','got_file').
                    223:               &hidden_input('associate','').
                    224:               &hidden_input('datatoken',$datatoken).
                    225:               &hidden_input('fileupload',$env{'form.fileupload'}).
                    226:               &hidden_input('upfiletype',$env{'form.upfiletype'}).
                    227:               &hidden_input('upfile_associate',$env{'form.upfile_associate'}));
                    228:     $r->print('<br /><input type="button" value="Reverse Association" '.
                    229:               'name="'.&mt('Reverse Association').'" '.
                    230:               'onClick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />');
                    231:     $r->print('<label><input type="checkbox" name="noFirstLine"'.$checked.'/>'.
                    232:               &mt('Ignore First Line').'</label>');
                    233:     $r->print("<br /><br />\n".
                    234:               '<script type="text/javascript" language="Javascript">'."\n".
                    235:               $javascript."\n".$javascript_validations.'</script>');
                    236: }
                    237: 
                    238: ###############################################################
                    239: ###############################################################
                    240: sub javascript_validations {
                    241:     my ($mode,$krbdefdom,$curr_authtype,$curr_authfield,$domain)=@_;
                    242:     my $authheader;
                    243:     if ($mode eq 'auth') {
                    244:         my %param = ( formname => 'studentform',
                    245:                       kerb_def_dom => $krbdefdom,
                    246:                       curr_authtype => $curr_authtype);
                    247:         $authheader = &Apache::loncommon::authform_header(%param);
                    248:     } elsif ($mode eq 'createcourse') {
                    249:         my %param = ( formname => 'ccrs',
                    250:                       kerb_def_dom => $krbdefdom,
                    251:                       curr_authtype => $curr_authtype );
                    252:         $authheader = &Apache::loncommon::authform_header(%param);
                    253:     } elsif ($mode eq 'modifycourse') {
                    254:         my %param = ( formname => 'cmod',
                    255:                   kerb_def_dom => $krbdefdom,
                    256:                   mode => 'modifycourse',
                    257:                   curr_authtype => $curr_authtype,
                    258:                   curr_autharg => $curr_authfield );
                    259:         $authheader = &Apache::loncommon::authform_header(%param);
                    260:     }
                    261: 
                    262:     my %alert = &Apache::lonlocal::texthash
                    263:         (username => 'You need to specify the username field.',
                    264:          authen   => 'You must choose an authentication type.',
                    265:          krb      => 'You need to specify the Kerberos domain.',
                    266:          ipass    => 'You need to specify the initial password.',
                    267:          name     => 'The optional name field was not specified.',
                    268:          snum     => 'The optional ID number field was not specified.',
                    269:          section  => 'The optional section field was not specified.',
                    270:          email    => 'The optional email address field was not specified.',
                    271:          role     => 'The optional role field was not specified.',
                    272:          continue => 'Continue adding users?',
                    273:          );
                    274: 
                    275: #    my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
                    276:     my $function_name =(<<END);
                    277: function verify_message (vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail) {
                    278: END
                    279:     my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($domain);
                    280:     my $auth_checks;
                    281:     if ($mode eq 'createcourse') {
                    282:         $auth_checks .= (<<END);
                    283:     if (vf.autoadds[0].checked == true) {
                    284:         if (current.radiovalue == null || current.radiovalue == 'nochange') {
                    285:             alert('$alert{'authen'}');
                    286:             return;
                    287:         }
                    288:     }
                    289: END
                    290:     } else {
                    291:         $auth_checks .= (<<END);
                    292:     var foundatype=0;
                    293:     if (founduname==0) {
                    294:         alert('$alert{'username'}');
                    295:         return;
                    296:     }
                    297: 
                    298: END
                    299:         if ($authnum > 1) {
                    300:             $auth_checks .= (<<END);
                    301:     if (current.radiovalue == null || current.radiovalue == '' || current.radiovalue == 'nochange') {
                    302:         // They did not check any of the login radiobuttons.
                    303:         alert('$alert{'authen'}');
                    304:         return;
                    305:     }
                    306: END
                    307:         }
                    308:     }
                    309:     if ($mode eq 'createcourse') {
                    310:         $auth_checks .= "
                    311:     if ( (vf.autoadds[0].checked == true) &&
                    312:          (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') ) {
                    313: ";
                    314:     } elsif ($mode eq 'modifycourse') {
                    315:         $auth_checks .= "
                    316:     if (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') {
                    317: ";
                    318:     }
                    319:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
                    320:         $auth_checks .= (<<END);
                    321:         var alertmsg = '';
                    322:         switch (current.radiovalue) {
                    323:             case 'krb':
                    324:                 alertmsg = '$alert{'krb'}';
                    325:                 break;
                    326:             default:
                    327:                 alertmsg = '';
                    328:         }
                    329:         if (alertmsg != '') {
                    330:             alert(alertmsg);
                    331:             return;
                    332:         }
                    333:     }
                    334: END
                    335:     } else {
                    336:         $auth_checks .= (<<END);
                    337:     foundatype=1;
                    338:     if (current.argfield == null || current.argfield == '') {
                    339:         var alertmsg = '';
                    340:         switch (current.value) {
                    341:             case 'krb':
                    342:                 alertmsg = '$alert{'krb'}';
                    343:                 break;
                    344:             case 'loc':
                    345:             case 'fsys':
                    346:                 alertmsg = '$alert{'ipass'}';
                    347:                 break;
                    348:             case 'fsys':
                    349:                 alertmsg = '';
                    350:                 break;
                    351:             default:
                    352:                 alertmsg = '';
                    353:         }
                    354:         if (alertmsg != '') {
                    355:             alert(alertmsg);
                    356:             return;
                    357:         }
                    358:     }
                    359: END
                    360:     }
                    361:     my $section_checks;
                    362:     my $optional_checks = '';
                    363:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
                    364:         $optional_checks = (<<END);
                    365:     vf.submit();
                    366: }
                    367: END
                    368:     } else {
                    369:         $section_checks = &section_check_js();
                    370:         $optional_checks = (<<END);
                    371:     var message='';
                    372:     if (foundname==0) {
                    373:         message='$alert{'name'}';
                    374:     }
                    375:     if (foundid==0) {
                    376:         if (message!='') {
                    377:             message+='\\n';
                    378:         }
                    379:         message+='$alert{'snum'}';
                    380:     }
                    381:     if (foundsec==0) {
                    382:         if (message!='') {
                    383:             message+='\\n';
                    384:         }
                    385:     }
                    386:     if (foundemail==0) {
                    387:         if (message!='') {
                    388:             message+='\\n';
                    389:         }
                    390:         message+='$alert{'email'}';
                    391:     }
                    392:     if (message!='') {
                    393:         message+= '\\n$alert{'continue'}';
                    394:         if (confirm(message)) {
                    395:             vf.state.value='enrolling';
                    396:             vf.submit();
                    397:         }
                    398:     } else {
                    399:         vf.state.value='enrolling';
                    400:         vf.submit();
                    401:     }
                    402: }
                    403: END
                    404:     }
                    405:     my $result = $function_name;
                    406:     if ( ($mode eq 'auth') || ($mode eq 'createcourse') || ($mode eq 'modifycourse')  ) {
                    407:         $result .= $auth_checks;
                    408:     }
                    409:     $result .= $optional_checks."\n".$section_checks;
                    410:     if ( ($mode eq 'auth') || ($mode eq 'createcourse') || ($mode eq 'modifycourse')  ) {
                    411:         $result .= $authheader;
                    412:     }
                    413:     return $result;
                    414: }
                    415: ###############################################################
                    416: ###############################################################
                    417: sub upload_manager_javascript_forward_associate {
                    418:     return(<<ENDPICK);
                    419: function verify(vf,sec_caller) {
                    420:     var founduname=0;
                    421:     var foundpwd=0;
                    422:     var foundname=0;
                    423:     var foundid=0;
                    424:     var foundsec=0;
                    425:     var foundemail=0;
                    426:     var foundrole=0;
                    427:     var tw;
                    428:     for (i=0;i<=vf.nfields.value;i++) {
                    429:         tw=eval('vf.f'+i+'.selectedIndex');
                    430:         if (tw==1) { founduname=1; }
                    431:         if ((tw>=2) && (tw<=6)) { foundname=1; }
                    432:         if (tw==7) { foundid=1; }
                    433:         if (tw==8) { foundsec=1; }
                    434:         if (tw==9) { foundpwd=1; }
                    435:         if (tw==10) { foundemail=1; }
                    436:         if (tw==11) { foundrole=1; }
                    437:     }
                    438:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole);
                    439: }
                    440: 
                    441: //
                    442: // vf = this.form
                    443: // tf = column number
                    444: //
                    445: // values of nw
                    446: //
                    447: // 0 = none
                    448: // 1 = username
                    449: // 2 = names (lastname, firstnames)
                    450: // 3 = fname (firstname)
                    451: // 4 = mname (middlename)
                    452: // 5 = lname (lastname)
                    453: // 6 = gen   (generation)
                    454: // 7 = id
                    455: // 8 = section
                    456: // 9 = ipwd  (password)
                    457: // 10 = email address
                    458: // 11 = role
                    459: 
                    460: function flip(vf,tf) {
                    461:    var nw=eval('vf.f'+tf+'.selectedIndex');
                    462:    var i;
                    463:    // make sure no other columns are labeled the same as this one
                    464:    for (i=0;i<=vf.nfields.value;i++) {
                    465:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                    466:           eval('vf.f'+i+'.selectedIndex=0;')
                    467:       }
                    468:    }
                    469:    // If we set this to 'lastname, firstnames', clear out all the ones
                    470:    // set to 'fname','mname','lname','gen' (3,4,5,6) currently.
                    471:    if (nw==2) {
                    472:       for (i=0;i<=vf.nfields.value;i++) {
                    473:          if ((eval('vf.f'+i+'.selectedIndex')>=3) &&
                    474:              (eval('vf.f'+i+'.selectedIndex')<=6)) {
                    475:              eval('vf.f'+i+'.selectedIndex=0;')
                    476:          }
                    477:       }
                    478:    }
                    479:    // If we set this to one of 'fname','mname','lname','gen' (3,4,5,6),
                    480:    // clear out any that are set to 'lastname, firstnames' (2)
                    481:    if ((nw>=3) && (nw<=6)) {
                    482:       for (i=0;i<=vf.nfields.value;i++) {
                    483:          if (eval('vf.f'+i+'.selectedIndex')==2) {
                    484:              eval('vf.f'+i+'.selectedIndex=0;')
                    485:          }
                    486:       }
                    487:    }
                    488:    // If we set the password, make the password form below correspond to
                    489:    // the new value.
                    490:    if (nw==9) {
                    491:        changed_radio('int',document.studentform);
                    492:        set_auth_radio_buttons('int',document.studentform);
                    493:        vf.intarg.value='';
                    494:        vf.krbarg.value='';
                    495:        vf.locarg.value='';
                    496:    }
                    497: }
                    498: 
                    499: function clearpwd(vf) {
                    500:     var i;
                    501:     for (i=0;i<=vf.nfields.value;i++) {
                    502:         if (eval('vf.f'+i+'.selectedIndex')==9) {
                    503:             eval('vf.f'+i+'.selectedIndex=0;')
                    504:         }
                    505:     }
                    506: }
                    507: 
                    508: ENDPICK
                    509: }
                    510: 
                    511: ###############################################################
                    512: ###############################################################
                    513: sub upload_manager_javascript_reverse_associate {
                    514:     return(<<ENDPICK);
                    515: function verify(vf,sec_caller) {
                    516:     var founduname=0;
                    517:     var foundpwd=0;
                    518:     var foundname=0;
                    519:     var foundid=0;
                    520:     var foundsec=0;
                    521:     var foundrole=0;
                    522:     var tw;
                    523:     for (i=0;i<=vf.nfields.value;i++) {
                    524:         tw=eval('vf.f'+i+'.selectedIndex');
                    525:         if (i==0 && tw!=0) { founduname=1; }
                    526:         if (((i>=1) && (i<=5)) && tw!=0 ) { foundname=1; }
                    527:         if (i==6 && tw!=0) { foundid=1; }
                    528:         if (i==7 && tw!=0) { foundsec=1; }
                    529:         if (i==8 && tw!=0) { foundpwd=1; }
                    530:         if (i==9 && tw!=0) { foundrole=1; }
                    531:     }
                    532:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundrole);
                    533: }
                    534: 
                    535: function flip(vf,tf) {
                    536:    var nw=eval('vf.f'+tf+'.selectedIndex');
                    537:    var i;
                    538:    // picked the all one name field, reset the other name ones to blank
                    539:    if (tf==1 && nw!=0) {
                    540:       for (i=2;i<=5;i++) {
                    541:          eval('vf.f'+i+'.selectedIndex=0;')
                    542:       }
                    543:    }
                    544:    //picked one of the piecewise name fields, reset the all in
                    545:    //one field to blank
                    546:    if ((tf>=2) && (tf<=5) && (nw!=0)) {
                    547:       eval('vf.f1.selectedIndex=0;')
                    548:    }
                    549:    // intial password specified, pick internal authentication
                    550:    if (tf==8 && nw!=0) {
                    551:        changed_radio('int',document.studentform);
                    552:        set_auth_radio_buttons('int',document.studentform);
                    553:        vf.krbarg.value='';
                    554:        vf.intarg.value='';
                    555:        vf.locarg.value='';
                    556:    }
                    557: }
                    558: 
                    559: function clearpwd(vf) {
                    560:     var i;
                    561:     if (eval('vf.f8.selectedIndex')!=0) {
                    562:         eval('vf.f8.selectedIndex=0;')
                    563:     }
                    564: }
                    565: ENDPICK
                    566: }
                    567: 
                    568: ###############################################################
                    569: ###############################################################
                    570: sub print_upload_manager_footer {
                    571:     my ($r,$i,$keyfields,$defdom,$today,$halfyear,$context)=@_;
                    572:     my $formname;
                    573:     if ($context eq 'course') {
                    574:         $formname = 'document.studentform';
                    575:     } elsif ($context eq 'construction_space') {
                    576:         $formname = 'document.studentform';
                    577:     } elsif ($context eq 'domain') {
                    578:         $formname = 'document.studentform';
                    579:     }
                    580:     my ($krbdef,$krbdefdom) =
                    581:         &Apache::loncommon::get_kerberos_defaults($defdom);
                    582:     my %param = ( formname => $formname,
                    583:                   kerb_def_dom => $krbdefdom,
                    584:                   kerb_def_auth => $krbdef
                    585:                   );
                    586:     if (exists($env{'form.ipwd_choice'}) &&
                    587:         defined($env{'form.ipwd_choice'}) &&
                    588:         $env{'form.ipwd_choice'} ne '') {
                    589:         $param{'curr_authtype'} = 'int';
                    590:     }
                    591:     my $krbform = &Apache::loncommon::authform_kerberos(%param);
                    592:     my $intform = &Apache::loncommon::authform_internal(%param);
                    593:     my $locform = &Apache::loncommon::authform_local(%param);
                    594:     my $date_table = &date_setting_table(undef,undef,$context);
                    595: 
                    596:     my $Str = "\n".'<div class="LC_left_float">';
                    597:     $Str .= &hidden_input('nfields',$i);
                    598:     $Str .= &hidden_input('keyfields',$keyfields);
                    599:     $Str .= "<h3>".&mt('Login Type')."</h3>\n";
                    600:     if ($context eq 'domain') {
                    601:         $Str .= '<p>'.&mt('Change authentication for existing users to these settings?').'&nbsp;<span class="LC_nobreak"><label><input type="radio" name="changeauth" value="No" checked="checked" />'.&mt('No').'</label>&nbsp;&nbsp;<label><input type="radio" name="changeauth" value="Yes" />'.&mt('Yes').'</label></span></p>'; 
                    602:     } else {
                    603:         $Str .= "<p>\n".
                    604:             &mt('Note: this will not take effect if the user already exists').
                    605:             &Apache::loncommon::help_open_topic('Auth_Options').
                    606:             "</p>\n";
                    607:     }
                    608:     $Str .= &set_login($defdom,$krbform,$intform,$locform);
                    609:     my ($home_server_pick,$numlib) =
                    610:         &Apache::loncommon::home_server_form_item($defdom,'lcserver',
                    611:                                                   'default','hide');
                    612:     if ($numlib > 1) {
                    613:         $Str .= '<h3>'.&mt('LON-CAPA Home Server for New Users')."</h3>\n".
                    614:                 &mt('LON-CAPA domain: [_1] with home server: [_2]',$defdom,
                    615:                 $home_server_pick).'<br />';
                    616:     } else {
                    617:         $Str .= $home_server_pick;
                    618:     }
                    619:     $Str .= '<h3>'.&mt('Starting and Ending Dates').
                    620:             "</h3>\n";
                    621:     $Str .= "<p>\n".$date_table."</p>\n";
                    622:     if ($context eq 'domain') {
                    623:         $Str .= '<h3>'.&mt('Settings for assigning roles:').'</h3>'."\n".
                    624:                 &mt('Pick the action to take on roles for these users:').'<br /><span class="LC_nobreak"><label><input type="radio" name="roleaction" value="norole" checked="checked" />&nbsp;'.&mt('No role changes').'</label>&nbsp;&nbsp;&nbsp;<label><input type="radio" name="roleaction" value="domain" />&nbsp;'.&mt('Add a domain role').'</label>&nbsp;&nbsp;&nbsp;<label><input type="radio" name="roleaction" value="course" />&nbsp;'.&mt('Add a course role').'</label></span>';
                    625:     }
                    626:     if ($context eq 'construction_space') {
                    627:         $Str .= '<h3>'.&mt('Default role')."</h3>\n".
                    628:                 &mt('Choose the role to assign to users without one specified in the uploaded file');
                    629:     } elsif ($context eq 'course') {
                    630:         $Str .= '<h3>'.&mt('Default role and section')."</h3>\n".
                    631:                 &mt('Choose the role and/or section to assign to users without one specified in the uploaded file');
                    632:     } else {
                    633:         $Str .= '<br /><br /><b>'.&mt('Default role and/or section')."</b><br />\n".
                    634:                 &mt('Role and/or section for users without one in the uploaded file.');
                    635:     }
                    636:     $Str .= '<br /><br />';
1.2     ! raeburn   637:     my ($options,$cb_script,$coursepick) = &default_role_selector($context,'defaultrole',1);
1.1       raeburn   638:     if ($context eq 'domain') {
                    639:         $Str .= '<span class="LC_role_level">'.&mt('Domain Level').'</span><br />'.$options.'<br /><br /><span class="LC_role_level">'.&mt('Course Level').'</span><br />'.$cb_script.$coursepick;
                    640:     } else {
                    641:         $Str .= $options;
                    642:     }
                    643:     if ($context eq 'course') {
                    644:         $Str .= "<h3>".&mt('Full Update')."</h3>\n".
                    645:                 '<label><input type="checkbox" name="fullup" value="yes">'.
                    646:                 ' '.&mt('Full update (also print list of users not enrolled anymore)').
                    647:                 "</label></p>\n";
                    648:     }
                    649:     $Str .= "<h3>".&mt('ID/Student Number')."</h3>\n";
                    650:     $Str .= "<p>\n".'<label><input type="checkbox" name="forceid" value="yes">';
                    651:     $Str .= &mt('Disable ID/Student Number Safeguard and Force Change '.
                    652:                 'of Conflicting IDs').
                    653:                 '</label><br />'."\n".
                    654:                 &mt('(only do if you know what you are doing.)')."</p><p>\n";
                    655:     $Str .= '</div><div class="LC_clear_float_footer"><br /><input type="button"'.
                    656:               'onClick="javascript:verify(this.form,this.form.csec)" '.
                    657:         'value="Update Users" />'."<br />\n";
                    658:     if ($context eq 'course') {
                    659:         $Str .= &mt('Note: for large courses, this operation may be time '.
                    660:                     'consuming');
                    661:     }
                    662:     $Str .= '</div>';
                    663:     $r->print($Str);
                    664:     return;
                    665: }
                    666: 
                    667: ###############################################################
                    668: ###############################################################
                    669: sub print_upload_manager_form {
                    670:     my ($r,$context) = @_;
                    671:     my $firstLine;
                    672:     my $datatoken;
                    673:     if (!$env{'form.datatoken'}) {
                    674:         $datatoken=&Apache::loncommon::upfile_store($r);
                    675:     } else {
                    676:         $datatoken=$env{'form.datatoken'};
                    677:         &Apache::loncommon::load_tmp_file($r);
                    678:     }
                    679:     my @records=&Apache::loncommon::upfile_record_sep();
                    680:     if($env{'form.noFirstLine'}){
                    681:         $firstLine=shift(@records);
                    682:     }
                    683:     my $total=$#records;
                    684:     my $distotal=$total+1;
                    685:     my $today=time;
                    686:     my $halfyear=$today+15552000;
                    687:     #
                    688:     # Restore memorized settings
                    689:     my $col_setting_names =  { 'username_choice' => 'scalar', # column settings
                    690:                                'names_choice' => 'scalar',
                    691:                                'fname_choice' => 'scalar',
                    692:                                'mname_choice' => 'scalar',
                    693:                                'lname_choice' => 'scalar',
                    694:                                'gen_choice' => 'scalar',
                    695:                                'id_choice' => 'scalar',
                    696:                                'sec_choice' => 'scalar',
                    697:                                'ipwd_choice' => 'scalar',
                    698:                                'email_choice' => 'scalar',
                    699:                                'role_choice' => 'scalar',
                    700:                              };
                    701:     my $defdom = $env{'request.role.domain'};
                    702:     if ($context eq 'course') {
                    703:         &Apache::loncommon::restore_course_settings('enrollment_upload',
                    704:                                                     $col_setting_names);
                    705:     } else {
                    706:         &Apache::loncommon::restore_settings($context,'user_upload',
                    707:                                              $col_setting_names);
                    708:     }
                    709:     #
                    710:     # Determine kerberos parameters as appropriate
                    711:     my ($krbdef,$krbdefdom) =
                    712:         &Apache::loncommon::get_kerberos_defaults($defdom);
                    713:     #
                    714:     &print_upload_manager_header($r,$datatoken,$distotal,$krbdefdom,$context);
                    715:     my $i;
                    716:     my $keyfields;
                    717:     if ($total>=0) {
                    718:         my @field=
                    719:             (['username',&mt('Username'),     $env{'form.username_choice'}],
                    720:              ['names',&mt('Last Name, First Names'),$env{'form.names_choice'}],
                    721:              ['fname',&mt('First Name'),      $env{'form.fname_choice'}],
                    722:              ['mname',&mt('Middle Names/Initials'),$env{'form.mname_choice'}],
                    723:              ['lname',&mt('Last Name'),       $env{'form.lname_choice'}],
                    724:              ['gen',  &mt('Generation'),      $env{'form.gen_choice'}],
                    725:              ['id',   &mt('ID/Student Number'),$env{'form.id_choice'}],
                    726:              ['sec',  &mt('Section'),          $env{'form.sec_choice'}],
                    727:              ['ipwd', &mt('Initial Password'),$env{'form.ipwd_choice'}],
                    728:              ['email',&mt('E-mail Address'),   $env{'form.email_choice'}],
                    729:              ['role',&mt('Role'),             $env{'form.role_choice'}]);
                    730:         if ($env{'form.upfile_associate'} eq 'reverse') {
                    731:             &Apache::loncommon::csv_print_samples($r,\@records);
                    732:             $i=&Apache::loncommon::csv_print_select_table($r,\@records,
                    733:                                                           \@field);
                    734:             foreach (@field) {
                    735:                 $keyfields.=$_->[0].',';
                    736:             }
                    737:             chop($keyfields);
                    738:         } else {
                    739:             unshift(@field,['none','']);
                    740:             $i=&Apache::loncommon::csv_samples_select_table($r,\@records,
                    741:                                                             \@field);
                    742:             my %sone=&Apache::loncommon::record_sep($records[0]);
                    743:             $keyfields=join(',',sort(keys(%sone)));
                    744:         }
                    745:     }
                    746:     $r->print('</div>');
                    747:     &print_upload_manager_footer($r,$i,$keyfields,$defdom,$today,$halfyear,
                    748:                                  $context);
                    749: }
                    750: 
                    751: sub setup_date_selectors {
                    752:     my ($starttime,$endtime,$mode) = @_;
                    753:     if (! defined($starttime)) {
                    754:         $starttime = time;
                    755:         unless ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
                    756:             if (exists($env{'course.'.$env{'request.course.id'}.
                    757:                             '.default_enrollment_start_date'})) {
                    758:                 $starttime = $env{'course.'.$env{'request.course.id'}.
                    759:                                   '.default_enrollment_start_date'};
                    760:             }
                    761:         }
                    762:     }
                    763:     if (! defined($endtime)) {
                    764:         $endtime = time+(6*30*24*60*60); # 6 months from now, approx
                    765:         unless ($mode eq 'createcourse') {
                    766:             if (exists($env{'course.'.$env{'request.course.id'}.
                    767:                             '.default_enrollment_end_date'})) {
                    768:                 $endtime = $env{'course.'.$env{'request.course.id'}.
                    769:                                 '.default_enrollment_end_date'};
                    770:             }
                    771:         }
                    772:     }
                    773:     my $startdateform = &Apache::lonhtmlcommon::date_setter('studentform',
                    774:                                                             'startdate',
                    775:                                                             $starttime);
                    776:     my $enddateform = &Apache::lonhtmlcommon::date_setter('studentform',
                    777:                                                           'enddate',
                    778:                                                           $endtime);
                    779:     if ($mode eq 'create_enrolldates') {
                    780:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    781:                                                             'startenroll',
                    782:                                                             $starttime);
                    783:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    784:                                                           'endenroll',
                    785:                                                           $endtime);
                    786:     }
                    787:     if ($mode eq 'create_defaultdates') {
                    788:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    789:                                                             'startaccess',
                    790:                                                             $starttime);
                    791:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    792:                                                           'endaccess',
                    793:                                                           $endtime);
                    794:     }
                    795:     return ($startdateform,$enddateform);
                    796: }
                    797: 
                    798: 
                    799: sub get_dates_from_form {
                    800:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate');
                    801:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate');
                    802:     if ($env{'form.no_end_date'}) {
                    803:         $enddate = 0;
                    804:     }
                    805:     return ($startdate,$enddate);
                    806: }
                    807: 
                    808: sub date_setting_table {
                    809:     my ($starttime,$endtime,$mode) = @_;
                    810:     my ($startform,$endform)=&setup_date_selectors($starttime,$endtime,$mode);
                    811:     my $dateDefault;
                    812:     if ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
                    813:         $dateDefault = '&nbsp;';
                    814:     } elsif ($mode ne 'construction_space' && $mode ne 'domain') {
                    815:         $dateDefault = '<nobr>'.
                    816:         '<label><input type="checkbox" name="makedatesdefault" /> '.
                    817:         &mt('make these dates the default for future enrollment').
                    818:         '</label></nobr>';
                    819:     }
                    820:     my $perpetual = '<nobr><label><input type="checkbox" name="no_end_date"';
                    821:     if (defined($endtime) && $endtime == 0) {
                    822:         $perpetual .= ' checked';
                    823:     }
                    824:     $perpetual.= ' /> '.&mt('no ending date').'</label></nobr>';
                    825:     if ($mode eq 'create_enrolldates') {
                    826:         $perpetual = '&nbsp;';
                    827:     }
                    828:     my $result = &Apache::lonhtmlcommon::start_pick_box()."\n".
                    829:                  &Apache::lonhtmlcommon::row_title(&mt('Starting Date'),
                    830:                                                    'LC_oddrow_value')."\n".
                    831:                  $startform."\n".
                    832:                  &Apache::lonhtmlcommon::row_closure(1).
                    833:                  &Apache::lonhtmlcommon::row_title(&mt('Ending Date'),
                    834:                                                    'LC_oddrow_value')."\n".
                    835:                  $endform.'&nbsp;'.$perpetual.
                    836:                  &Apache::lonhtmlcommon::row_closure(1).
                    837:                  &Apache::lonhtmlcommon::end_pick_box().'<br />';
                    838:     if ($dateDefault) {
                    839:         $result .=  $dateDefault.'<br />'."\n";
                    840:     }
                    841:     return $result;
                    842: }
                    843: 
                    844: sub make_dates_default {
                    845:     my ($startdate,$enddate,$context) = @_;
                    846:     my $result = '';
                    847:     if ($context eq 'course') {
                    848:         my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    849:         my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
                    850:         my $put_result = &Apache::lonnet::put('environment',
                    851:                 {'default_enrollment_start_date'=>$startdate,
                    852:                  'default_enrollment_end_date'  =>$enddate},$dom,$crs);
                    853:         if ($put_result eq 'ok') {
                    854:             $result .= "Set default start and end dates for course<br />";
                    855:             #
                    856:             # Refresh the course environment
                    857:             &Apache::lonnet::coursedescription($env{'request.course.id'},
                    858:                                                {'freshen_cache' => 1});
                    859:         } else {
                    860:             $result .= &mt('Unable to set default dates for course').":".$put_result.
                    861:                        '<br />';
                    862:         }
                    863:     }
                    864:     return $result;
                    865: }
                    866: 
                    867: sub default_role_selector {
1.2     ! raeburn   868:     my ($context,$checkpriv) = @_;
1.1       raeburn   869:     my %customroles;
                    870:     my ($options,$coursepick,$cb_jscript);
                    871:     if ($context ne 'construction_space') {
                    872:         %customroles = &my_custom_roles();
                    873:     }
                    874: 
                    875:     my %lt=&Apache::lonlocal::texthash(
                    876:                     'rol'  => "Role",
                    877:                     'grs'  => "Section",
                    878:                     'exs'  => "Existing sections",
                    879:                     'new'  => "New section",
                    880:                   );
                    881:     $options = '<select name="defaultrole">'."\n".
                    882:                ' <option value="">'.&mt('Please select').'</option>'."\n"; 
                    883:     if ($context eq 'course') {
1.2     ! raeburn   884:         $options .= &default_course_roles($context,$checkpriv,%customroles);
1.1       raeburn   885:     } elsif ($context eq 'construction_space') {
1.2     ! raeburn   886:         my @roles = &construction_space_roles($checkpriv);
1.1       raeburn   887:         foreach my $role (@roles) {
                    888:            my $plrole=&Apache::lonnet::plaintext($role);
                    889:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>'."\n";
                    890:         }
                    891:     } elsif ($context eq 'domain') {
1.2     ! raeburn   892:         my @roles = &domain_roles($checkpriv);
1.1       raeburn   893:         foreach my $role (@roles) {
                    894:            my $plrole=&Apache::lonnet::plaintext($role);
                    895:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>';
                    896:         }
                    897:         my $courseform = &Apache::loncommon::selectcourse_link
                    898:             ('studentform','defaultcourse','defaultdomain','defaultdesc',"$env{'request.role.domain'}",undef,'Course');
                    899:         $cb_jscript = 
                    900:             &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'},'defaultsec','studentform');
                    901:         $coursepick = &Apache::loncommon::start_data_table().
                    902:                       &Apache::loncommon::start_data_table_header_row().
                    903:                       '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th>'.
                    904:                       '<th>'.$lt{'grs'}.'</th>'.
                    905:                       &Apache::loncommon::end_data_table_header_row().
                    906:                       &Apache::loncommon::start_data_table_row()."\n".
                    907:                       '<td><input type="text" name="defaultdesc" value="" onFocus="this.blur();opencrsbrowser('."'studentform','defcourse','defdomain','coursedesc',''".')" /></td>'."\n".
                    908:                       '<td><select name="courserole">'."\n".
1.2     ! raeburn   909:                       &default_course_roles($context,$checkpriv,%customroles)."\n".
1.1       raeburn   910:                       '</select></td><td>'.
                    911:                       '<table class="LC_createuser">'.
                    912:                       '<tr class="LC_section_row"><td valign"top">'.
                    913:                       $lt{'exs'}.'<br /><select name="defaultsec">'.
                    914:                       ' <option value=""><--'.&mt('Pick course first').
                    915:                       '</select></td>'.
                    916:                       '<td>&nbsp;&nbsp;</td>'.
                    917:                       '<td valign="top">'.$lt{'new'}.'<br />'.
                    918:                       '<input type="text" name="newsec" value="" size="5" />'.
                    919:                       '<input type="hidden" name="groups" value="" /></td>'.
                    920:                       '</tr></table></td>'.
                    921:                       &Apache::loncommon::end_data_table_row().
                    922:                       &Apache::loncommon::end_data_table()."\n".
                    923:                       '<input type="hidden" name="defaultcourse" value="" />'.
                    924:                       '<input type="hidden" name="defaultdomain" value="" />';
                    925:     }
                    926:     $options .= '</select>';
                    927:     return ($options,$cb_jscript,$coursepick);
                    928: }
                    929: 
                    930: sub default_course_roles {
1.2     ! raeburn   931:     my ($context,$checkpriv,%customroles) = @_;
1.1       raeburn   932:     my $output;
1.2     ! raeburn   933:     my @roles = &course_roles($context,$checkpriv);
1.1       raeburn   934:     foreach my $role (@roles) {
                    935:         my $plrole=&Apache::lonnet::plaintext($role);
                    936:         $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
                    937:     }
                    938:     if (keys(%customroles) > 0) {
1.2     ! raeburn   939:         my %customroles = &my_custom_roles();
1.1       raeburn   940:         foreach my $cust (sort(keys(%customroles))) {
                    941:             my $custrole='cr_cr_'.$env{'user.domain'}.
                    942:                 '_'.$env{'user.name'}.'_'.$cust;
                    943:             $output .= '  <option value="'.$custrole.'">'.$cust.'</option>';
                    944:         }
                    945:     }
                    946:     return $output;
                    947: }
                    948: 
                    949: sub construction_space_roles {
1.2     ! raeburn   950:     my ($checkpriv) = @_;
1.1       raeburn   951:     my @allroles = ('ca','aa');
                    952:     my @roles;
1.2     ! raeburn   953:     if ($checkpriv) {
        !           954:         foreach my $role (@allroles) {
        !           955:             if (&Apache::lonnet::allowed('c'.$role,$env{'user.domain'}.'/'.$env{'user.name'})) { 
        !           956:                 push(@roles,$role); 
        !           957:             }
1.1       raeburn   958:         }
1.2     ! raeburn   959:         return @roles;
        !           960:     } else {
        !           961:         return @allroles;
1.1       raeburn   962:     }
                    963: }
                    964: 
                    965: sub domain_roles {
1.2     ! raeburn   966:     my ($checkpriv) = @_;
1.1       raeburn   967:     my @allroles = ('dc','li','dg','au','sc');
                    968:     my @roles;
1.2     ! raeburn   969:     if ($checkpriv) {
        !           970:         foreach my $role (@allroles) {
        !           971:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
        !           972:                 push(@roles,$role);
        !           973:             }
1.1       raeburn   974:         }
1.2     ! raeburn   975:         return @roles;
        !           976:     } else {
        !           977:         return @allroles;
1.1       raeburn   978:     }
                    979: }
                    980: 
                    981: sub course_roles {
1.2     ! raeburn   982:     my ($context,$checkpriv) = @_;
1.1       raeburn   983:     my @allroles = ('st','ta','ep','in','cc');
                    984:     my @roles;
                    985:     if ($context eq 'domain') {
                    986:         @roles = @allroles;
                    987:     } elsif ($context eq 'course') {
                    988:         if ($env{'request.course.id'}) {
1.2     ! raeburn   989:             if ($checkpriv) { 
        !           990:                 foreach my $role (@allroles) {
        !           991:                     if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
        !           992:                         push(@roles,$role);
        !           993:                     } else {
        !           994:                         if ($role ne 'cc' && $env{'request.course.section'} ne '') {
        !           995:                             if (!&Apache::lonnet::allowed('c'.$role,
        !           996:                                              $env{'request.course.id'}.'/'.
        !           997:                                              $env{'request.course.section'})) {
        !           998:                                 push(@roles,$role);
        !           999:                             }
1.1       raeburn  1000:                         }
                   1001:                     }
                   1002:                 }
1.2     ! raeburn  1003:             } else {
        !          1004:                 @roles = @allroles;
1.1       raeburn  1005:             }
                   1006:         }
                   1007:     }
                   1008:     return @roles;
                   1009: }
                   1010: 
                   1011: sub curr_role_permissions {
1.2     ! raeburn  1012:     my ($context,$setting,$checkpriv) = @_; 
1.1       raeburn  1013:     my @roles;
                   1014:     if ($context eq 'construction_space') {
1.2     ! raeburn  1015:         @roles = &construction_space_roles($checkpriv);
1.1       raeburn  1016:     } elsif ($context eq 'domain') {
                   1017:         if ($setting eq 'course') {
1.2     ! raeburn  1018:             @roles = &course_roles($context,$checkpriv); 
1.1       raeburn  1019:         } else {
1.2     ! raeburn  1020:             @roles = &domain_roles($checkpriv);
1.1       raeburn  1021:         }
                   1022:     } elsif ($context eq 'course') {
1.2     ! raeburn  1023:         @roles = &course_roles($context,$checkpriv);
1.1       raeburn  1024:     }
                   1025:     return @roles;
                   1026: }
                   1027: 
                   1028: # ======================================================= Existing Custom Roles
                   1029: 
                   1030: sub my_custom_roles {
                   1031:     my %returnhash=();
                   1032:     my %rolehash=&Apache::lonnet::dump('roles');
                   1033:     foreach my $key (keys %rolehash) {
                   1034:         if ($key=~/^rolesdef\_(\w+)$/) {
                   1035:             $returnhash{$1}=$1;
                   1036:         }
                   1037:     }
                   1038:     return %returnhash;
                   1039: }
                   1040: 
1.2     ! raeburn  1041: sub print_userlist {
        !          1042:     my ($r,$mode,$permission,$context,$formname,$totcodes,$codetitles,
        !          1043:         $idlist,$idlist_titles) = @_;
        !          1044:     my $format = $env{'form.output'};
1.1       raeburn  1045:     if (! exists($env{'form.sortby'})) {
                   1046:         $env{'form.sortby'} = 'username';
                   1047:     }
1.2     ! raeburn  1048:     if ($env{'form.Status'} !~ /^(Any|Expired|Active|Future)$/) {
        !          1049:         $env{'form.Status'} = 'Active';
1.1       raeburn  1050:     }
                   1051:     my $status_select = &Apache::lonhtmlcommon::StatusOptions
1.2     ! raeburn  1052:         ($env{'form.Status'});
1.1       raeburn  1053: 
1.2     ! raeburn  1054:     if ($env{'form.showrole'} eq '') {
        !          1055:         $env{'form.showrole'} = 'Any';
        !          1056:     }
1.1       raeburn  1057:     if (! defined($env{'form.output'}) ||
                   1058:         $env{'form.output'} !~ /^(csv|excel|html)$/ ) {
                   1059:         $env{'form.output'} = 'html';
                   1060:     }
                   1061: 
1.2     ! raeburn  1062:     my @statuses;
        !          1063:     if ($env{'form.Status'} eq 'Any') {
        !          1064:         @statuses = ('previous','active','future');
        !          1065:     } elsif ($env{'form.Status'} eq 'Expired') {
        !          1066:         @statuses = ('previous');
        !          1067:     } elsif ($env{'form.Status'} eq 'Active') {
        !          1068:         @statuses = ('active');
        !          1069:     } elsif ($env{'form.Status'} eq 'Future') {
        !          1070:         @statuses = ('future');
        !          1071:     }
1.1       raeburn  1072: 
1.2     ! raeburn  1073: #    if ($context eq 'course') { 
        !          1074: #        $r->print(&display_adv_courseroles());
        !          1075: #    }
1.1       raeburn  1076:     #
                   1077:     # Interface output
1.2     ! raeburn  1078:     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n".
        !          1079:               '<input type="hidden" name="action" value="'.
1.1       raeburn  1080:               $env{'form.action'}.'" />');
                   1081:     $r->print("<p>\n");
                   1082:     if ($env{'form.action'} ne 'modifystudent') {
                   1083:         my %lt=&Apache::lonlocal::texthash('csv' => "CSV",
                   1084:                                            'excel' => "Excel",
                   1085:                                            'html'  => 'HTML');
                   1086:         my $output_selector = '<select size="1" name="output" >';
                   1087:         foreach my $outputformat ('html','csv','excel') {
                   1088:             my $option = '<option value="'.$outputformat.'" ';
                   1089:             if ($outputformat eq $env{'form.output'}) {
                   1090:                 $option .= 'selected ';
                   1091:             }
                   1092:             $option .='>'.$lt{$outputformat}.'</option>';
                   1093:             $output_selector .= "\n".$option;
                   1094:         }
                   1095:         $output_selector .= '</select>';
                   1096:         $r->print('<label>'.&mt('Output Format: [_1]',$output_selector).'</label>'.('&nbsp;'x3));
                   1097:     }
1.2     ! raeburn  1098:     $r->print('<label>'.&mt('User Status: [_1]',$status_select).'</label>'.('&nbsp;'x3)."\n");
        !          1099:     my $roleselected = '';
        !          1100:     if ($env{'form.showrole'} eq 'Any') {
        !          1101:        $roleselected = ' selected="selected" '; 
        !          1102:     }
        !          1103:     my $role_select;
        !          1104:     if ($context eq 'domain') {
        !          1105:         $role_select = &domain_roles_select();
        !          1106:         $r->print('<label>'.&mt('Role Type: [_1]',$role_select).'</label>');
        !          1107:     } else {
        !          1108:         $role_select = '<select name="showrole">'."\n".
        !          1109:                        '<option value="Any" '.$roleselected.'>'.
        !          1110:                        &mt('Any role').'</option>';
        !          1111:         my @poss_roles = &curr_role_permissions($context);
        !          1112:         foreach my $role (@poss_roles) {
        !          1113:             $roleselected = '';
        !          1114:             if ($role eq $env{'form.showrole'}) {
        !          1115:                 $roleselected = ' selected="selected" ';
        !          1116:             }
        !          1117:             my $plrole=&Apache::lonnet::plaintext($role);
        !          1118:             $role_select .= '<option value="'.$role.'"'.$roleselected.'>'.$plrole.'</option>';
        !          1119:         }
        !          1120:         $roleselected = '';
        !          1121:         if ($env{'form.showrole'} eq 'cr') {
        !          1122:             $roleselected = ' selected="selected" ';
        !          1123:         }
        !          1124:         $role_select .= '<option value="cr"'.$roleselected.'>'.&mt('Custom role').'</option>'.
        !          1125:                         '</select>';
        !          1126:         $r->print('<label>'.&mt('Role: [_1]',$role_select).'</label>');
        !          1127:     }
        !          1128:     if (!(($context eq 'domain') && ($env{'form.roletype'} eq 'course'))) {
        !          1129:         $r->print(&list_submit_button(&mt('Update Display'))."\n</p>\n");
        !          1130:     }
        !          1131:     my ($indexhash,$keylist) = &make_keylist_array();
        !          1132:     my (%userlist,%userinfo);
1.1       raeburn  1133:     if ($context eq 'course') {
                   1134:         #
1.2     ! raeburn  1135:         # Print the userlist
        !          1136:         $r->print('<h2>'.&mt('Current User List').'</h2>');
        !          1137:         (my $classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.1       raeburn  1138: 
                   1139:         if (exists($permission->{'view_section'})) {
                   1140:             my $sec = &Apache::loncoursedata::CL_SECTION();
                   1141:             foreach my $student (keys(%{$classlist})) {
1.2     ! raeburn  1142:                 if ($userlist{$student}[$sec] ne $permission->{'view_section'}) {
        !          1143:                     delete($userlist{$student});
1.1       raeburn  1144:                 }
                   1145:             }
                   1146:         }
1.2     ! raeburn  1147:         foreach my $item (keys(%{$classlist})) {
        !          1148:             $userlist{$item} = $classlist->{$item};
        !          1149:         }
        !          1150:         my $cid =$env{'request.course.id'};
        !          1151:         my $cdom=$env{'course.'.$cid.'.domain'};
        !          1152:         my $cnum=$env{'course.'.$cid.'.num'};
        !          1153:         my $showroles;
        !          1154:         if ($env{'form.showrole'} ne 'Any') {
        !          1155:             $showroles = [$env{'form.showrole'}];
1.1       raeburn  1156:         } else {
1.2     ! raeburn  1157:             $showroles = undef;
        !          1158:         }
        !          1159:         my %advrolehash = &Apache::lonnet::get_my_roles($cnum,$cdom,undef,
        !          1160:                                                         \@statuses,$showroles);
        !          1161:         &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
        !          1162:                          \%advrolehash);
        !          1163:     } else {
        !          1164:         my (%cstr_roles,%dom_roles);
        !          1165:         if ($context eq 'construction_space') {
        !          1166:             # List co-authors and assistant co-authors
        !          1167:             my @possroles = ('ca','aa');
        !          1168:             %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
        !          1169:                                               \@statuses,\@possroles);
        !          1170:             &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
        !          1171:                              \%cstr_roles);
        !          1172:         } elsif ($context eq 'domain') {
        !          1173:             if ($env{'form.roletype'} eq 'domain') {
        !          1174:                 %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'});
        !          1175:                 foreach my $key (keys(%dom_roles)) {
        !          1176:                     if (ref($dom_roles{$key}) eq 'HASH') {
        !          1177:                         &gather_userinfo($context,$format,\%userlist,$indexhash,
        !          1178:                                          \%userinfo,$dom_roles{$key});
        !          1179:                     }
        !          1180:                 }
        !          1181:             } elsif ($env{'form.roletype'} eq 'construction_space') {
        !          1182:                 my %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'},['au']);
        !          1183:                 my %coauthors;
        !          1184:                 foreach my $key (keys(%dom_roles)) {
        !          1185:                     if (ref($dom_roles{$key}) eq 'HASH') {
        !          1186:                         if ($env{'form.showrole'} eq 'au') {
        !          1187:                             &gather_userinfo($context,$format,\%userlist,$indexhash,
        !          1188:                                              \%userinfo,$dom_roles{$key});
        !          1189:                         } else {
        !          1190:                             my @possroles;
        !          1191:                             if ($env{'form.showrole'} eq 'Any') {
        !          1192:                                 @possroles = ('ca','aa');
        !          1193:                             } else {
        !          1194:                                 @possroles = ($env{'form.showrole'}); 
        !          1195:                             }
        !          1196:                             foreach my $author (sort(keys(%{$dom_roles{$key}}))) {
        !          1197:                                 my ($role,$authorname,$authordom) = split(/:/,$author);
        !          1198:                                 my $extent = '/'.$authordom.'/'.$authorname;
        !          1199:                                 %{$coauthors{$extent}} =
        !          1200:                                     &Apache::lonnet::get_my_roles($authorname,
        !          1201:                                        $authordom,undef,\@statuses,\@possroles);
        !          1202:                             }
        !          1203:                             &gather_userinfo($context,$format,\%userlist,
        !          1204:                                              $indexhash,\%userinfo,\%coauthors);
        !          1205:                         }
        !          1206:                     }
        !          1207:                 }
        !          1208:             } elsif ($env{'form.roletype'} eq 'course') {
        !          1209:                 my $courseform = 
        !          1210:                     &Apache::lonhtmlcommon::course_selection($formname,$totcodes,
        !          1211:                                            $codetitles,$idlist,$idlist_titles);
        !          1212:                 my $output='<p>'.&Apache::lonhtmlcommon::start_pick_box()."\n".
        !          1213:                            &Apache::lonhtmlcommon::start_pick_box()."\n".
        !          1214:                      &Apache::lonhtmlcommon::row_title(&mt('Select Course(s)'),
        !          1215:                                                        'LC_oddrow_value')."\n".
        !          1216:                            $courseform."\n".
        !          1217:                            &Apache::lonhtmlcommon::row_closure(1).
        !          1218:                            &Apache::lonhtmlcommon::end_pick_box().'</p>';
        !          1219:                 $r->print($output);
        !          1220:                 $r->print('<p>'.&list_submit_button(&mt('Update Display')).
        !          1221:                           "\n</p>\n");
        !          1222:                 if ($env{'form.coursepick'}) {
        !          1223:                     my %courses = &process_coursepick();
        !          1224:                     my %allusers; 
        !          1225:                     foreach my $cid (keys(%courses)) {
        !          1226:                         my %coursehash =
        !          1227:                             &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
        !          1228:                         my $cdom = $coursehash{'domain'};
        !          1229:                         my $cnum = $coursehash{'num'};
        !          1230:                         my $cdesc = $coursehash{'description'};
        !          1231:                         my (@roles,@sections,%access,%users,%userdata,
        !          1232:                             %users,%statushash);
        !          1233:                         if ($env{'form.showrole'} eq 'Any') {
        !          1234:                             @roles = &course_roles($context);
        !          1235:                         } else {
        !          1236:                             @roles = ($env{'form.showrole'});
        !          1237:                         }
        !          1238:                         foreach my $role (@roles) {
        !          1239:                             %{$users{$role}} = ();
        !          1240:                         }
        !          1241:                         foreach my $type (@statuses) {
        !          1242:                             $access{$type} = $type;
        !          1243:                         }
        !          1244:                         &Apache::loncommon::get_course_users($cdom,$cnum,\%access,\@roles,\@sections,\%users,\%userdata,\%statushash);
        !          1245:                         foreach my $user (keys(%userdata)) {
        !          1246:                             next if (ref($userinfo{$user}) eq 'HASH');
        !          1247:                             foreach my $item ('fullname','id') {
        !          1248:                                 $userinfo{$user}{$item} = $userdata{$user}[$indexhash->{$item}];
        !          1249:                             }
        !          1250:                         }
        !          1251:                         foreach my $role (keys(%users)) {
        !          1252:                             foreach my $user (keys(%{$users{$role}})) {
        !          1253:                                 my $uniqid = $user.':'.$role;
        !          1254:                                 $allusers{$uniqid}{$cid} = { desc => $cdesc,
        !          1255:                                                              secs  => $statushash{$user}{$role},
        !          1256:                                                            };
        !          1257:                             }
        !          1258:                         }
        !          1259:                     }
        !          1260:                     &gather_userinfo($context,$format,\%userlist,$indexhash,
        !          1261:                                      \%userinfo,\%allusers);
        !          1262:                 } else {
        !          1263:                     return;
        !          1264:                 }
1.1       raeburn  1265:             }
                   1266:         }
1.2     ! raeburn  1267:         if (keys(%userlist) == 0) {
        !          1268:             if ($context eq 'construction_space') {
        !          1269:                 $r->print(&mt('There are no co-authors to display.')."\n");
        !          1270:             } elsif ($context eq 'domain') {
        !          1271:                 if ($env{'form.roletype'} eq 'domain') {
        !          1272:                     $r->print(&mt('There are no users with domain roles to display.')."\n");
        !          1273:                 } elsif ($env{'form.roletype'} eq 'construction_space') {
        !          1274:                     $r->print(&mt('There are no authors or co-authors to display.')."\n");
        !          1275:                 } elsif ($env{'form.roletype'} eq 'course') {
        !          1276:                     $r->print(&mt('There are no course users to display')."\n"); 
        !          1277:                 }
        !          1278:             } elsif ($context eq 'course') {
        !          1279:                 $r->print(&mt('There are no course users to display.')."\n");
        !          1280:             }
1.1       raeburn  1281:         } else {
                   1282:             # Print out the available choices
                   1283:             if ($env{'form.action'} eq 'modifystudent') {
                   1284:                 &show_users_list($r,$context,'view','modify',
1.2     ! raeburn  1285:                                  $env{'form.Status'},\%userlist,$keylist);
1.1       raeburn  1286:             } else {
                   1287:                 &show_users_list($r,$context,$env{'form.output'},'aboutme',
1.2     ! raeburn  1288:                                  $env{'form.Status'},\%userlist,$keylist);
        !          1289:             }
        !          1290:         }
        !          1291:     }
        !          1292:     $r->print('</form>');
        !          1293: }
        !          1294: 
        !          1295: sub list_submit_button {
        !          1296:     my ($text) = @_;
        !          1297:     return '<input type="submit" value="'.$text.'" />';
        !          1298: }
        !          1299: 
        !          1300: sub gather_userinfo {
        !          1301:     my ($context,$format,$userlist,$indexhash,$userinfo,$rolehash) = @_;
        !          1302:     foreach my $item (keys(%{$rolehash})) {
        !          1303:         @{$userlist->{$item}} = ();
        !          1304:         my %userdata;
        !          1305:         if ($context eq 'construction_space' || $context eq 'course') { 
        !          1306:             ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
        !          1307:                 split(/:/,$item);
        !          1308:             ($userdata{'start'},$userdata{'end'})=split(/:/,$rolehash->{$item});
        !          1309:             &build_user_record(\%userdata,$userinfo,$indexhash,$item,$userlist);
        !          1310:         } elsif ($context eq 'domain') {
        !          1311:             if ($env{'form.roletype'} eq 'domain') {
        !          1312:                 ($userdata{'role'},$userdata{'username'},$userdata{'domain'}) =
        !          1313:                     split(/:/,$item);
        !          1314:                 ($userdata{'end'},$userdata{'start'})=split(/:/,$rolehash->{$item});
        !          1315:                 &build_user_record(\%userdata,$userinfo,$indexhash,$item,$userlist);
        !          1316:             } elsif ($env{'form.roletype'} eq 'construction_space') {
        !          1317:                 if (ref($rolehash->{$item}) eq 'HASH') {
        !          1318:                     $userdata{'extent'} = $item;
        !          1319:                     foreach my $key (keys(%{$rolehash->{$item}})) {
        !          1320:                         ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =  split(/:/,$key);
        !          1321:                         ($userdata{'start'},$userdata{'end'}) = 
        !          1322:                             split(/:/,$rolehash->{$item}{$key});
        !          1323:                         my $uniqid = $key.':'.$item;
        !          1324:                         &build_user_record(\%userdata,$userinfo,$indexhash,$uniqid,$userlist);
        !          1325:                     }
        !          1326:                 }
        !          1327:             } elsif ($env{'form.roletype'} eq 'course') {
        !          1328:                 ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
        !          1329:                     split(/:/,$item);
        !          1330:                 if (ref($rolehash->{$item}) eq 'HASH') {
        !          1331:                     foreach my $cid (sort(keys(%{$rolehash->{$item}}))) {
        !          1332:                         if (ref($rolehash->{$item}{$cid}) eq 'HASH') {
        !          1333:                             my $spanstart = '';
        !          1334:                             my $spanend = '; ';
        !          1335:                             my $space = ', ';
        !          1336:                             if ($format eq 'html' || $format eq 'view') {
        !          1337:                                 $spanstart = '<span class="LC_nobreak">';
        !          1338:                                 $spanend = '</span><br />';
        !          1339:                                 $space = ',&nbsp;';
        !          1340:                             }
        !          1341:                             $userdata{'extent'} .= $spanstart.
        !          1342:                                     $rolehash->{$item}{$cid}{'desc'}.$space;
        !          1343:                             if (ref($rolehash->{$item}{$cid}{'secs'}) eq 'HASH') { 
        !          1344:                                 foreach my $sec (sort(keys(%{$rolehash->{$item}{$cid}{'secs'}}))) {
        !          1345:                                     $userdata{'extent'} .= $sec.$space.$rolehash->{$item}{$cid}{'secs'}{$sec}.$spanend;
        !          1346:                                 }
        !          1347:                             }
        !          1348:                         }
        !          1349:                     }
        !          1350:                 }
        !          1351:                 &build_user_record(\%userdata,$userinfo,$indexhash,$item,$userlist);
        !          1352:             }
        !          1353:         }
        !          1354:     }
        !          1355:     return;
        !          1356: }
        !          1357: 
        !          1358: sub build_user_record {
        !          1359:     my ($userdata,$userinfo,$indexhash,$record_key,$userlist) = @_;
        !          1360:     &process_date_info($userdata);
        !          1361:     my $username = $userdata->{'username'};
        !          1362:     my $domain = $userdata->{'domain'};
        !          1363:     if (ref($userinfo->{$username.':'.$domain}) eq 'HASH') {
        !          1364:         $userdata->{'fullname'} =
        !          1365:         $userinfo->{$username.':'.$domain}{'fullname'};
        !          1366:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
        !          1367:     } else {
        !          1368:         &aggregate_user_info($domain,$username,$userinfo);
        !          1369:         $userdata->{'fullname'} = $userinfo->{$username.':'.$domain}{'fullname'};
        !          1370:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
        !          1371:     }
        !          1372:     foreach my $key (keys(%{$indexhash})) {
        !          1373:         if (defined($userdata->{$key})) {
        !          1374:             $userlist->{$record_key}[$indexhash->{$key}] = $userdata->{$key};
        !          1375:         }
        !          1376:     }
        !          1377:     return;
        !          1378: }
        !          1379: 
        !          1380: sub courses_selector {
        !          1381:     my ($cdom,$formname) = @_;
        !          1382:     my %coursecodes = ();
        !          1383:     my %codes = ();
        !          1384:     my @codetitles = ();
        !          1385:     my %cat_titles = ();
        !          1386:     my %cat_order = ();
        !          1387:     my %idlist = ();
        !          1388:     my %idnums = ();
        !          1389:     my %idlist_titles = ();
        !          1390:     my $caller = 'global';
        !          1391:     my $totcodes = 0;
        !          1392:     my $format_reply;
        !          1393:     my $jscript = '';
        !          1394: 
        !          1395:     my $totcodes =
        !          1396:         &Apache::courseclassifier::retrieve_instcodes(\%coursecodes,
        !          1397:                                                       $cdom,$totcodes);
        !          1398:     if ($totcodes > 0) {
        !          1399:         $format_reply =
        !          1400:              &Apache::lonnet::auto_instcode_format($caller,$cdom,\%coursecodes,
        !          1401:                                 \%codes,\@codetitles,\%cat_titles,\%cat_order);
        !          1402:         if ($format_reply eq 'ok') {
        !          1403:             my $numtypes = @codetitles;
        !          1404:             &Apache::courseclassifier::build_code_selections(\%codes,\@codetitles,\%cat_titles,\%cat_order,\%idlist,\%idnums,\%idlist_titles);
        !          1405:             my ($scripttext,$longtitles) = &Apache::courseclassifier::javascript_definitions(\@codetitles,\%idlist,\%idlist_titles,\%idnums,\%cat_titles);
        !          1406:             my $longtitles_str = join('","',@{$longtitles});
        !          1407:             my $allidlist = $idlist{$codetitles[0]};
        !          1408:             $jscript .= &Apache::courseclassifier::courseset_js_start($formname,$longtitles_str,$allidlist);
        !          1409:             $jscript .= $scripttext;
        !          1410:             $jscript .= &Apache::courseclassifier::javascript_code_selections($formname,@codetitles);
        !          1411:         }
        !          1412:     }
        !          1413:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($cdom);
        !          1414: 
        !          1415:     my %elements = (
        !          1416:                      Year => 'selectbox',
        !          1417:                      coursepick => 'radio',
        !          1418:                      coursetotal => 'text',
        !          1419:                      courselist => 'text',
        !          1420:                    );
        !          1421:     $jscript .= &Apache::lonhtmlcommon::set_form_elements(\%elements);
        !          1422:     if ($env{'form.coursepick'} eq 'category') {
        !          1423:         $jscript .= qq|
        !          1424: function setCourseCat(formname) {
        !          1425:     if (formname.Year.options[formname.Year.selectedIndex].value == -1) {
        !          1426:         return;
        !          1427:     }
        !          1428:     courseSet('Year');
        !          1429:     for (var j=0; j<formname.Semester.length; j++) {
        !          1430:         if (formname.Semester.options[j].value == "$env{'form.Semester'}") {
        !          1431:             formname.Semester.options[j].selected = true;
        !          1432:         }
        !          1433:     }
        !          1434:     if (formname.Semester.options[formname.Semester.selectedIndex].value == -1) {
        !          1435:         return;
        !          1436:     }
        !          1437:     courseSet('Semester');
        !          1438:     for (var j=0; j<formname.Department.length; j++) {
        !          1439:         if (formname.Department.options[j].value == "$env{'form.Department'}") {            formname.Department.options[j].selected = true;
        !          1440:         }
        !          1441:     }
        !          1442:     if (formname.Department.options[formname.Department.selectedIndex].value == -1) {
        !          1443:         return;
        !          1444:     }
        !          1445:     courseSet('Department');
        !          1446:     for (var j=0; j<formname.Number.length; j++) {
        !          1447:         if (formname.Number.options[j].value == "$env{'form.Number'}") {
        !          1448:             formname.Number.options[j].selected = true;
        !          1449:         }
        !          1450:     }
        !          1451: }
        !          1452: |;
        !          1453:     }
        !          1454:     return ($cb_jscript,$jscript,$totcodes,\@codetitles,\%idlist,
        !          1455:             \%idlist_titles);
        !          1456: }
        !          1457: 
        !          1458: sub course_selector_loadcode {
        !          1459:     my ($formname) = @_;
        !          1460:     my $loadcode;
        !          1461:     if ($env{'form.coursepick'} ne '') {
        !          1462:         $loadcode = 'javascript:setFormElements(document.'.$formname.')';
        !          1463:         if ($env{'form.coursepick'} eq 'category') {
        !          1464:             $loadcode .= ';javascript:setCourseCat(document.'.$formname.')';
        !          1465:         }
        !          1466:     }
        !          1467:     return $loadcode;
        !          1468: }
        !          1469: 
        !          1470: sub process_coursepick {
        !          1471:     my $coursefilter = $env{'form.coursepick'};
        !          1472:     my $cdom = $env{'request.role.domain'};
        !          1473:     my %courses;
        !          1474:     if ($coursefilter eq 'all') {
        !          1475:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.','.','.','.',
        !          1476:                                                  undef,undef,'Course');
        !          1477:     } elsif ($coursefilter eq 'category') {
        !          1478:         my $instcode = &instcode_from_coursefilter();
        !          1479:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.',$instcode,'.','.',
        !          1480:                                                  undef,undef,'Course');
        !          1481:     } elsif ($coursefilter eq 'specific') {
        !          1482:         if ($env{'form.coursetotal'} > 1) {
        !          1483:             my @course_ids = split(/&&/,$env{'form.courselist'});
        !          1484:             foreach my $cid (@course_ids) {
        !          1485:                 $courses{$cid} = '';
1.1       raeburn  1486:             }
1.2     ! raeburn  1487:         } else {
        !          1488:             $courses{$env{'form.courselist'}} = '';
1.1       raeburn  1489:         }
1.2     ! raeburn  1490:     }
        !          1491:     return %courses;
        !          1492: }
        !          1493: 
        !          1494: sub instcode_from_coursefilter {
        !          1495:     my $instcode = '';
        !          1496:     my @cats = ('Semester','Year','Department','Number');
        !          1497:     foreach my $category (@cats) {
        !          1498:         if (defined($env{'form.'.$category})) {
        !          1499:             unless ($env{'form.'.$category} eq '-1') {
        !          1500:                 $instcode .= $env{'form.'.$category};
        !          1501:            }
        !          1502:         }
        !          1503:     }
        !          1504:     if ($instcode eq '') {
        !          1505:         $instcode = '.';
        !          1506:     }
        !          1507:     return $instcode;
        !          1508: }
        !          1509: 
        !          1510: sub display_adv_courseroles {
        !          1511:     my $output;
        !          1512:     #
        !          1513:     # List course personnel
        !          1514:     my %coursepersonnel = 
        !          1515:        &Apache::lonnet::get_course_adv_roles($env{'request.course.id'});
        !          1516:     #
        !          1517:     $output = '<br />'.&Apache::loncommon::start_data_table();
        !          1518:     foreach my $role (sort(keys(%coursepersonnel))) {
        !          1519:         next if ($role =~ /^\s*$/);
        !          1520:         $output .= &Apache::loncommon::start_data_table_row().
        !          1521:                   '<td>'.$role.'</td><td>';
        !          1522:         foreach my $user (split(',',$coursepersonnel{$role})) {
        !          1523:             my ($puname,$pudom)=split(':',$user);
        !          1524:             $output .= ' '.&Apache::loncommon::aboutmewrapper(
        !          1525:                        &Apache::loncommon::plainname($puname,$pudom),
        !          1526:                        $puname,$pudom);
        !          1527:         }
        !          1528:         $output .= '</td>'.&Apache::loncommon::end_data_table_row();
        !          1529:     }
        !          1530:     $output .= &Apache::loncommon::end_data_table();
        !          1531: }
        !          1532: 
        !          1533: sub make_keylist_array {
        !          1534:     my ($index,$keylist);
        !          1535:     $index->{'domain'} = &Apache::loncoursedata::CL_SDOM();
        !          1536:     $index->{'username'} = &Apache::loncoursedata::CL_SNAME();
        !          1537:     $index->{'end'} = &Apache::loncoursedata::CL_END();
        !          1538:     $index->{'start'} = &Apache::loncoursedata::CL_START();
        !          1539:     $index->{'id'} = &Apache::loncoursedata::CL_ID();
        !          1540:     $index->{'section'} = &Apache::loncoursedata::CL_SECTION();
        !          1541:     $index->{'fullname'} = &Apache::loncoursedata::CL_FULLNAME();
        !          1542:     $index->{'status'} = &Apache::loncoursedata::CL_STATUS();
        !          1543:     $index->{'type'} = &Apache::loncoursedata::CL_TYPE();
        !          1544:     $index->{'lockedtype'} = &Apache::loncoursedata::CL_LOCKEDTYPE();
        !          1545:     $index->{'groups'} = &Apache::loncoursedata::CL_GROUP();
        !          1546:     $index->{'email'} = &Apache::loncoursedata::CL_PERMANENTEMAIL();
        !          1547:     $index->{'role'} = &Apache::loncoursedata::CL_ROLE();
        !          1548:     $index->{'extent'} = &Apache::loncoursedata::CL_EXTENT();
        !          1549:     foreach my $key (keys(%{$index})) {
        !          1550:         $keylist->[$index->{$key}] = $key;
        !          1551:     }
        !          1552:     return ($index,$keylist);
        !          1553: }
        !          1554: 
        !          1555: sub aggregate_user_info {
        !          1556:     my ($udom,$uname,$userinfo) = @_;
        !          1557:     my %info=&Apache::lonnet::get('environment',
        !          1558:                                   ['firstname','middlename',
        !          1559:                                    'lastname','generation','id'],
        !          1560:                                    $udom,$uname);
        !          1561:     my ($tmp) = keys(%info);
        !          1562:     my ($fullname,$id);
        !          1563:     if ($tmp =~/^(con_lost|error|no_such_host)/i) {
        !          1564:         $fullname = 'not available';
        !          1565:         $id = 'not available';
        !          1566:         &Apache::lonnet::logthis('unable to retrieve environment '.
        !          1567:                                  'for '.$uname.':'.$udom);
1.1       raeburn  1568:     } else {
1.2     ! raeburn  1569:         $fullname = &Apache::lonnet::format_name(@info{qw/firstname middlename lastname generation/},'lastname');
        !          1570:         $id = $info{'id'};
        !          1571:     }
        !          1572:     $userinfo->{$uname.':'.$udom} = { 
        !          1573:                                       fullname => $fullname,
        !          1574:                                       id       => $id,
        !          1575:                                     };
        !          1576:     return;
        !          1577: }
1.1       raeburn  1578: 
1.2     ! raeburn  1579: sub process_date_info {
        !          1580:     my ($userdata) = @_;
        !          1581:     my $now = time;
        !          1582:     $userdata->{'status'} = 'Active';
        !          1583:     if ($userdata->{'start'} > 0) {
        !          1584:         if ($now < $userdata->{'start'}) {
        !          1585:             $userdata->{'status'} = 'Future';
        !          1586:         }
1.1       raeburn  1587:     }
1.2     ! raeburn  1588:     if ($userdata->{'end'} > 0) {
        !          1589:         if ($now > $userdata->{'end'}) {
        !          1590:             $userdata->{'status'} = 'Expired';
        !          1591:         }
        !          1592:     }
        !          1593:     return;
1.1       raeburn  1594: }
                   1595: 
                   1596: sub show_users_list {
1.2     ! raeburn  1597:     my ($r,$context,$mode,$linkto,$statusmode,$userlist,$keylist)=@_;
1.1       raeburn  1598:     #
                   1599:     # Variables for excel output
                   1600:     my ($excel_workbook, $excel_sheet, $excel_filename,$row,$format);
                   1601:     #
                   1602:     # Variables for csv output
                   1603:     my ($CSVfile,$CSVfilename);
                   1604:     #
                   1605:     my $sortby = $env{'form.sortby'};
1.2     ! raeburn  1606:     if ($context eq 'course') {
        !          1607:         if ($sortby !~ /^(username|domain|section|groups|fullname|id|start|end|type)$/) {
        !          1608:             $sortby = 'username';
        !          1609:         }
        !          1610:     } else {
        !          1611:         if ($sortby !~ /^(username|domain|id|fullname|start|end|role|email|extent)$/) {
        !          1612:             $sortby = 'username';
        !          1613:         }
1.1       raeburn  1614:     }
1.2     ! raeburn  1615:     my ($cid,$cdom,$cnum,$classgroups,$displayphotos,$displayclickers);
1.1       raeburn  1616:     if ($context eq 'course') {
                   1617:         $cid=$env{'request.course.id'};
                   1618:         $cdom = $env{'course.'.$cid.'.domain'};
                   1619:         $cnum = $env{'course.'.$cid.'.num'};
1.2     ! raeburn  1620:         ($classgroups) = &Apache::loncoursedata::get_group_memberships(
        !          1621:                                      $userlist,$keylist,$cdom,$cnum);
1.1       raeburn  1622:         if (! exists($env{'form.displayphotos'})) {
                   1623:             $env{'form.displayphotos'} = 'off';
                   1624:         }
                   1625:         $displayphotos = $env{'form.displayphotos'};
                   1626:         if (! exists($env{'form.displayclickers'})) {
                   1627:             $env{'form.displayclickers'} = 'off';
                   1628:         }
                   1629:         $displayclickers = $env{'form.displayclickers'};
                   1630:         if ($env{'course.'.$cid.'.internal.showphoto'}) {
                   1631:             $r->print('
                   1632: <script type="text/javascript">
                   1633: function photowindow(photolink) {
                   1634:     var title = "Photo_Viewer";
                   1635:     var options = "scrollbars=1,resizable=1,menubar=0";
                   1636:     options += ",width=240,height=240";
                   1637:     stdeditbrowser = open(photolink,title,options,"1");
                   1638:     stdeditbrowser.focus();
                   1639: }
                   1640: </script>
                   1641:            ');
                   1642:         }
                   1643:         $r->print(<<END);
                   1644: <input type="hidden" name="displayphotos" value="$displayphotos" />
                   1645: <input type="hidden" name="displayclickers" value="$displayclickers" />
                   1646: END
                   1647:     }
                   1648:     unless ($mode eq 'autoenroll') {
                   1649:         $r->print(<<END);
                   1650: <input type="hidden" name="state" value="$env{'form.state'}" />
                   1651: END
                   1652:     }
                   1653:     $r->print(<<END);
                   1654: <input type="hidden" name="sortby" value="$sortby" />
                   1655: END
                   1656: 
                   1657:     my %lt=&Apache::lonlocal::texthash(
                   1658:                        'username'   => "username",
                   1659:                        'domain'     => "domain",
                   1660:                        'id'         => 'ID',
                   1661:                        'fullname'   => "name",
                   1662:                        'section'    => "section",
                   1663:                        'groups'     => "active groups",
                   1664:                        'start'      => "start date",
                   1665:                        'end'        => "end date",
                   1666:                        'status'     => "status",
1.2     ! raeburn  1667:                        'role'       => "role",
1.1       raeburn  1668:                        'type'       => "enroll type/action",
                   1669:                        'email'      => "email address",
                   1670:                        'clicker'    => "clicker id",
                   1671:                        'photo'      => "photo",
1.2     ! raeburn  1672:                        'extent'     => "extent",
1.1       raeburn  1673:                       );
1.2     ! raeburn  1674:     if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
        !          1675:         $lt{'extent'} = &mt('Course(s): description, section(s), status');
        !          1676:     } elsif ($context eq 'construction_space') {
        !          1677:         $lt{'extent'} = &mt('Author'); 
        !          1678:     }
1.1       raeburn  1679:     my @cols = ('username','domain','id','fullname');
                   1680:     if ($context eq 'course') {
                   1681:         push(@cols,'section');
                   1682:     }
1.2     ! raeburn  1683:     if (!($context eq 'domain' && $env{'form.roletype'} eq 'course')) { 
        !          1684:         push(@cols,('start','end'));
        !          1685:     }
        !          1686:     if ($env{'form.showrole'} eq 'Any') {
        !          1687:         push(@cols,'role');
        !          1688:     }
        !          1689:     if ($context eq 'domain' && ($env{'form.roletype'} eq 'construction_space' ||
        !          1690:                                 $env{'form.roletype'} eq 'course')) {
        !          1691:         push (@cols,'extent');
        !          1692:     }
        !          1693:     if (($statusmode eq 'Any') && 
        !          1694:         (!($context eq 'domain' && $env{'form.roletype'} eq 'course'))) {
1.1       raeburn  1695:         push(@cols,'status');
                   1696:     }
                   1697:     if ($context eq 'course') {
                   1698:         push(@cols,'groups');
                   1699:     }
                   1700:     push(@cols,'email');
                   1701: 
1.2     ! raeburn  1702:     my $rolefilter;
        !          1703:     if ($env{'form.showrole'} ne 'Any') {
        !          1704:         $rolefilter = &Apache::lonnet::plaintext($env{'form.showrole'});
        !          1705:     }
        !          1706:     my $results_description = &results_header_row($rolefilter,$statusmode,
        !          1707:                                                   $context);
        !          1708: 
1.1       raeburn  1709:     if ($mode eq 'html' || $mode eq 'view') {
1.2     ! raeburn  1710:         $r->print('<hr />'.&mt('Searching').' ...<br />&nbsp;<br />');
        !          1711:         $r->rflush();
        !          1712:         $r->print('<b>'.$results_description.'</b><br />');
1.1       raeburn  1713:         if ($linkto eq 'aboutme') {
                   1714:             $r->print(&mt("Select a user name to view the user's personal page."));
                   1715:         } elsif ($linkto eq 'modify') {
                   1716:             $r->print(&mt("Select a user name to modify the user's information"));
                   1717:         }
                   1718:         $r->print(<<END);
                   1719: <input type="hidden" name="sname"  value="" />
                   1720: <input type="hidden" name="sdom"   value="" />
                   1721: END
                   1722:         $r->print("\n<p>\n".
                   1723:                   &Apache::loncommon::start_data_table().
                   1724:                   &Apache::loncommon::start_data_table_header_row());
                   1725:         if ($mode eq 'autoenroll') {
                   1726:             $r->print("
                   1727:  <th><a href=\"javascript:document.studentform.sortby.value='type';document.studentform.submit();\">$lt{'type'}</a></th>
                   1728:             ");
                   1729:         } else {
                   1730:             $r->print("
                   1731: <th>Count</th>
                   1732:             ");
                   1733:         }
                   1734:         foreach my $item (@cols) {
1.2     ! raeburn  1735:             $r->print("<th><a href=\"javascript:document.studentform.sortby.value='$item';document.studentform.submit();\">$lt{$item}</a></th>\n");
1.1       raeburn  1736:         }
1.2     ! raeburn  1737:         my %role_types = &role_type_names();
1.1       raeburn  1738:         if ($context eq 'course') {
                   1739:             # Clicker display on or off?
                   1740:             my %clicker_options = &Apache::lonlocal::texthash(
                   1741:                                                         'on' => 'Show',
                   1742:                                                         'off' => 'Hide',
                   1743:                                                        );
                   1744:             my $clickerchg = 'on';
                   1745:             if ($displayclickers eq 'on') {
                   1746:                 $clickerchg = 'off';
                   1747:             }
                   1748:             $r->print('    <th>'."\n".'     '.
                   1749:                 '<a href="javascript:document.studentform.displayclickers.value='.
                   1750:                       "'".$clickerchg."'".';document.studentform.submit();">'.
                   1751:                       $clicker_options{$clickerchg}.'</a>&nbsp;'.$lt{'clicker'}."\n".
                   1752:                       '    </th>'."\n");
                   1753: 
                   1754:             # Photo display on or off?
                   1755:             if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
                   1756:                 my %photo_options = &Apache::lonlocal::texthash(
                   1757:                                                         'on' => 'Show',
                   1758:                                                         'off' => 'Hide',
                   1759:                                                             );
                   1760:                 my $photochg = 'on';
                   1761:                 if ($displayphotos eq 'on') {
                   1762:                     $photochg = 'off';
                   1763:                 }
                   1764:                 $r->print('    <th>'."\n".'     '.
                   1765:             '<a href="javascript:document.studentform.displayphotos.value='.
                   1766:                       "'".$photochg."'".';document.studentform.submit();">'.
                   1767:                       $photo_options{$photochg}.'</a>&nbsp;'.$lt{'photo'}."\n".
                   1768:                       '    </th>'."\n");
                   1769:             }
1.2     ! raeburn  1770:             $r->print(&Apache::loncommon::end_data_table_header_row());
1.1       raeburn  1771:         } 
                   1772: # Done with the HTML header line
                   1773:     } elsif ($mode eq 'csv') {
                   1774:         #
                   1775:         # Open a file
                   1776:         $CSVfilename = '/prtspool/'.
1.2     ! raeburn  1777:                        $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
        !          1778:                        time.'_'.rand(1000000000).'.csv';
1.1       raeburn  1779:         unless ($CSVfile = Apache::File->new('>/home/httpd'.$CSVfilename)) {
                   1780:             $r->log_error("Couldn't open $CSVfilename for output $!");
                   1781:             $r->print("Problems occured in writing the csv file.  ".
                   1782:                       "This error has been logged.  ".
                   1783:                       "Please alert your LON-CAPA administrator.");
                   1784:             $CSVfile = undef;
                   1785:         }
                   1786:         #
                   1787:         # Write headers and data to file
1.2     ! raeburn  1788:         print $CSVfile '"'.$results_description.'"'."\n"; 
1.1       raeburn  1789:         print $CSVfile '"'.join('","',map {
                   1790:             &Apache::loncommon::csv_translate($lt{$_})
                   1791:             } (@cols)).'"'."\n";
                   1792:     } elsif ($mode eq 'excel') {
                   1793:         # Create the excel spreadsheet
                   1794:         ($excel_workbook,$excel_filename,$format) =
                   1795:             &Apache::loncommon::create_workbook($r);
                   1796:         return if (! defined($excel_workbook));
                   1797:         $excel_sheet = $excel_workbook->addworksheet('userlist');
1.2     ! raeburn  1798:         $excel_sheet->write($row++,0,$results_description,$format->{'h2'});
1.1       raeburn  1799:         #
                   1800:         my @colnames = map {$lt{$_}} (@cols);
                   1801:         $excel_sheet->write($row++,0,\@colnames,$format->{'bold'});
                   1802:     }
                   1803: 
                   1804: # Done with header lines in all formats
                   1805: 
                   1806:     my %index;
                   1807:     my $i;
1.2     ! raeburn  1808:     foreach my $idx (@$keylist) {
        !          1809:         $index{$idx} = $i++;
        !          1810:     }
        !          1811:     # Get groups, role, permanent e-mail so we can sort on them if
        !          1812:     # necessary.
        !          1813:     foreach my $user (keys(%{$userlist})) {
        !          1814:         my ($uname,$udom,$role,$groups,$email);
        !          1815:         if ($context eq 'domain') {
        !          1816:             if ($env{'form.roletype'} eq 'domain') {
        !          1817:                 ($role,$uname,$udom) = split(/:/,$user);
        !          1818:                
        !          1819:             } elsif ($env{'form.roletype'} eq 'construction_space') {
        !          1820:                 ($uname,$udom,$role) = split(/:/,$user,-1);
        !          1821:             } elsif ($env{'form.roletype'} eq 'course') {
        !          1822:                 ($uname,$udom,$role) = split(/:/,$user);
        !          1823:             }
        !          1824:         } else {
        !          1825:             ($uname,$udom,$role) = split(/:/,$user,-1);
        !          1826:             if (($context eq 'course') && $role eq '') {
        !          1827:                 $role = 'st';
        !          1828:             }
        !          1829:         }
        !          1830:         $userlist->{$user}->[$index{'role'}] = $role;
        !          1831:         if (($env{'form.showrole'} ne 'Any') && (!($env{'form.showrole'}  eq 'cr' && $role =~ /^cr\//)) && ($role ne $env{'form.showrole'})) {
        !          1832:             delete($userlist->{$user});
        !          1833:             next;
        !          1834:         }
        !          1835:         if (ref($classgroups) eq 'HASH') {
        !          1836:             $groups = $classgroups->{$user};
        !          1837:         }
        !          1838:         if (ref($groups->{active}) eq 'HASH') {
        !          1839:             $userlist->{$user}->[$index{'groups'}] = join(', ',keys(%{$groups->{'active'}}));
        !          1840:         }
        !          1841:         my %emails   = &Apache::loncommon::getemails($uname,$udom);
        !          1842:         if ($emails{'permanentemail'} =~ /\S/) {
        !          1843:             $userlist->{$user}->[$index{'email'}] = $emails{'permanentemail'};
        !          1844:         }
1.1       raeburn  1845:     }
1.2     ! raeburn  1846: 
        !          1847:     #
        !          1848:     # Sort the users
1.1       raeburn  1849:     my $index  = $index{$sortby};
                   1850:     my $second = $index{'username'};
                   1851:     my $third  = $index{'domain'};
1.2     ! raeburn  1852:     my @sorted_users = sort {
        !          1853:         lc($userlist->{$a}->[$index])  cmp lc($userlist->{$b}->[$index])
1.1       raeburn  1854:             ||
1.2     ! raeburn  1855:         lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second])            ||
        !          1856:         lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
        !          1857:         } (keys(%$userlist));
        !          1858:     my $usercount = 0;
1.1       raeburn  1859:     my $autocount = 0;
                   1860:     my $manualcount = 0;
1.2     ! raeburn  1861:     my $lockcount = 0;
1.1       raeburn  1862:     my $unlockcount = 0;
1.2     ! raeburn  1863:     foreach my $user (@sorted_users) {
        !          1864:         my $sdata = $userlist->{$user};
        !          1865:         my %in;
        !          1866:         foreach my $item (@{$keylist}) {
        !          1867:             $in{$item} = $sdata->[$index{$item}];
        !          1868:         }
        !          1869:         next if (($statusmode ne 'Any') && ($in{'status'} ne $statusmode));
        !          1870:         $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}]); 
        !          1871:         if (! defined($in{'start'}) || $in{'start'} == 0) {
        !          1872:             $in{'start'} = &mt('none');
        !          1873:         } else {
        !          1874:             $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
1.1       raeburn  1875:         }
1.2     ! raeburn  1876:         if (! defined($in{'end'}) || $in{'end'} == 0) {
        !          1877:             $in{'end'} = &mt('none');
1.1       raeburn  1878:         } else {
1.2     ! raeburn  1879:             $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
1.1       raeburn  1880:         }
1.2     ! raeburn  1881:         $usercount ++;
        !          1882:         if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll') {
        !          1883:             $r->print(&Apache::loncommon::start_data_table_row());
        !          1884:             $r->print("<td>$usercount</td>\n");
        !          1885:             if ($linkto eq 'aboutme') {
        !          1886:                 $in{'username'} = 
        !          1887:                     &Apache::loncommon::aboutmewrapper($in{'username'},
        !          1888:                                                        $in{'username'},
        !          1889:                                                        $in{'domain'});
        !          1890:             } elsif ($linkto eq 'modify') {
        !          1891:                 $in{'username'} = '<a href="'.
        !          1892:                           "javascript:document.studentform.sname.value='".
        !          1893:                            $in{'username'}.
        !          1894:                            "';document.studentform.sdom.value='".$in{'domain'}.
        !          1895:                            "';document.studentform.state.value='selected".
        !          1896:                            "';document.studentform.submit();".'">'.
        !          1897:                            $in{'username'}."</a>\n";
        !          1898:             }
        !          1899:             foreach my $item (@cols) {
        !          1900:                 $r->print('<td>'.$in{$item}.'</td>'."\n");
        !          1901:             }
        !          1902:             if ($context eq 'course') {
        !          1903:                 if ($displayclickers eq 'on') {
        !          1904:                     my $clickers =
        !          1905:                    (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
        !          1906:                     if ($clickers!~/\w/) { $clickers='-'; }
        !          1907:                     $r->print('<td>'.$clickers.'</td>');
        !          1908:                 } else {
        !          1909:                     $r->print('    <td>&nbsp;</td>  ');
        !          1910:                 }
        !          1911:                 if ($displayphotos eq 'on') {
        !          1912:                     if ($env{'course.'.$env{'request.course.id'}.
        !          1913:                         '.internal.showphoto'}) {
        !          1914:                         my $imgurl =
        !          1915:                &Apache::lonnet::retrievestudentphoto($in{'domain'},$in{'username'},'gif','thumbnail');
        !          1916:                         $r->print('    <td align="right"><a href="javascript:photowindow('."'".&Apache::lonnet::studentphoto($in{'domain'},$in{'username'},'jpg')."'".')"><img src="'.$imgurl.'" border="1"></a></td>');
        !          1917:                     } else {
        !          1918:                         $r->print('    <td>&nbsp;</td>  ');
        !          1919:                     }
        !          1920:                 }
        !          1921:             }
        !          1922:             $r->print(&Apache::loncommon::end_data_table_row());
        !          1923:         } elsif ($mode eq 'csv') {
        !          1924:             next if (! defined($CSVfile));
        !          1925:             # no need to bother with $linkto
        !          1926:             if (! defined($in{'start'}) || $in{'start'} == 0) {
        !          1927:                 $in{'start'} = &mt('none');
        !          1928:             } else {
        !          1929:                 $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
        !          1930:             }
        !          1931:             if (! defined($in{'end'}) || $in{'end'} == 0) {
        !          1932:                 $in{'end'} = &mt('none');
        !          1933:             } else {
        !          1934:                 $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
        !          1935:             }
        !          1936:             my @line = ();
        !          1937:             foreach my $item (@cols) {
        !          1938:                 push @line,&Apache::loncommon::csv_translate($in{$item});
        !          1939:             }
        !          1940:             print $CSVfile '"'.join('","',@line).'"'."\n";
        !          1941:         } elsif ($mode eq 'excel') {
        !          1942:             my $col = 0;
        !          1943:             foreach my $item (@cols) {
        !          1944:                 if ($item eq 'start' || $item eq 'end') {
        !          1945:                     if (defined($item) && $item != 0) {
        !          1946:                         $excel_sheet->write($row,$col++,
        !          1947:                             &Apache::lonstathelpers::calc_serial($in{item}),
        !          1948:                                     $format->{'date'});
        !          1949:                     } else {
        !          1950:                         $excel_sheet->write($row,$col++,'none');
        !          1951:                     }
        !          1952:                 } else {
        !          1953:                     $excel_sheet->write($row,$col++,$in{$item});
        !          1954:                 }
        !          1955:             }
        !          1956:             $row++;
1.1       raeburn  1957:         }
                   1958:     }
1.2     ! raeburn  1959:     if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll') {
        !          1960:             $r->print(&Apache::loncommon::end_data_table().'<br />');
        !          1961:     } elsif ($mode eq 'excel') {
        !          1962:         $excel_workbook->close();
        !          1963:         $r->print('<p><a href="'.$excel_filename.'">'.
        !          1964:                   &mt('Your Excel spreadsheet').'</a> '.&mt('is ready for download').'.</p>'."\n");
        !          1965:     } elsif ($mode eq 'csv') {
        !          1966:         close($CSVfile);
        !          1967:         $r->print('<a href="'.$CSVfilename.'">'.
        !          1968:                   &mt('Your CSV file').'</a> is ready for download.'.
        !          1969:                   "\n");
        !          1970:         $r->rflush();
        !          1971:     }
        !          1972:     if ($mode eq 'autoenroll') {
        !          1973:         return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
        !          1974:     }
1.1       raeburn  1975:     return;
                   1976: }
                   1977: 
1.2     ! raeburn  1978: sub role_type_names {
        !          1979:     my %lt = &Apache::lonlocal::texthash (
        !          1980:                          'domain'             => 'Domain Roles',
        !          1981:                          'construction_space' => 'Co-Author Roles',
        !          1982:                          'course'             => 'Course Roles',
        !          1983:              );
        !          1984:     return %lt;
        !          1985: }
        !          1986: 
        !          1987: sub results_header_row {
        !          1988:     my ($rolefilter,$statusmode,$context) = @_;
        !          1989:     my $description;
        !          1990:     if ($context eq 'course') {
        !          1991:         $description = &mt('Course - ').$env{'course.'.env{'request.course.id'}.'.description'}.': ';
        !          1992:         if ($statusmode eq 'Expired') {
        !          1993:             $description .= &mt('Users in course with expired [_1] roles',$rolefilter);
        !          1994:         }
        !          1995:         if ($statusmode eq 'Future') {
        !          1996:             $description .= &mt('Users in course with future [_1] roles',$rolefilter);
        !          1997:         } elsif ($statusmode eq 'Active') {
        !          1998:             $description .= &mt('Users in course with active [_1] roles',$rolefilter);
        !          1999:         } else {
        !          2000:             if ($rolefilter eq 'Any') {
        !          2001:                 $description .= &mt('All users in course');
        !          2002:             } else {
        !          2003:                 $description .= &mt('All users in course with [_1] roles',$rolefilter);
        !          2004:             }
        !          2005:         }
        !          2006:     } elsif ($context eq 'construction_space') {
        !          2007:         $description = &mt('Author space for [_1].').' ';
        !          2008:         if ($statusmode eq 'Expired') {
        !          2009:             $description .= &mt('Co-authors with expired [_1] roles',$rolefilter);
        !          2010:         } elsif ($statusmode eq 'Future') {
        !          2011:             $description .= &mt('Co-authors with future [_1] roles',$rolefilter);
        !          2012:         } elsif ($statusmode eq 'Active') {
        !          2013:             $description .= &mt('Co-authors with active [_1] roles',$rolefilter);
        !          2014:         } else {
        !          2015:             if ($rolefilter eq 'Any') {
        !          2016:                 $description .= &mt('All co-authors',$rolefilter);
        !          2017:             } else {
        !          2018:                 $description .= &mt('All co-authors with [_1] roles',$rolefilter);
        !          2019:             }
        !          2020:         }
        !          2021:     } elsif ($context eq 'domain') {
        !          2022:         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
        !          2023:         $description = &mt('Domain - ').$domdesc.': ';
        !          2024:         if ($env{'form.roletype'} eq 'domain') {
        !          2025:             if ($statusmode eq 'Expired') {
        !          2026:                 $description .= &mt('Users in domain with expired [_1] roles',$rolefilter);
        !          2027:             } elsif ($statusmode eq 'Future') {
        !          2028:                 $description .= &mt('Users in domain with future [_1] roles',$rolefilter);
        !          2029:             } elsif ($statusmode eq 'Active') {
        !          2030:                 $description .= &mt('Users in domain with active [_1] roles',$rolefilter);
        !          2031:             } else {
        !          2032:                 if ($rolefilter eq 'Any') {
        !          2033:                     $description .= &mt('All users in domain',$rolefilter);
        !          2034:                 } else {
        !          2035:                     $description .= &mt('All users in domain with [_1] roles',$rolefilter);
        !          2036:                 }
        !          2037:             }
        !          2038:         } elsif ($env{'form.roletype'} eq 'construction_space') {
        !          2039:             if ($statusmode eq 'Expired') {
        !          2040:                 $description .= &mt('Co-authors in domain with expired [_1] roles',$rolefilter);
        !          2041:             } elsif ($statusmode eq 'Future') {
        !          2042:                 $description .= &mt('Co-authors in domain with future [_1] roles',$rolefilter);
        !          2043:             } elsif ($statusmode eq 'Active') {
        !          2044:                $description .= &mt('Co-authors in domain with active [_1] roles',$rolefilter);
        !          2045:             } else {
        !          2046:                 if ($rolefilter eq 'Any') {
        !          2047:                     $description .= &mt('All users with co-author roles in domain',$rolefilter);
        !          2048:                 } else {
        !          2049:                     $description .= &mt('All co-authors in domain  with [_1] roles',$rolefilter);
        !          2050:                 }
        !          2051:             }
        !          2052:         } elsif ($env{'form.roletype'} eq 'course') {
        !          2053:             my $coursefilter = $env{'form.coursepick'};
        !          2054:             if ($coursefilter eq 'category') {
        !          2055:                 my $instcode = &instcode_from_coursefilter();
        !          2056:                 if ($instcode eq '.') {
        !          2057:                     $description .= &mt('All courses in domain').' - ';
        !          2058:                 } else {
        !          2059:                     $description .= &mt('Courses in domain with institutional code: [_1]',$instcode).' - ';
        !          2060:                 }
        !          2061:             } elsif ($coursefilter eq 'selected') {
        !          2062:                 $description .= &mt('Selected courses in domain').' - ';
        !          2063:             } elsif ($coursefilter eq 'all') {
        !          2064:                 $description .= &mt('All courses in domain').' - ';
        !          2065:             }
        !          2066:             if ($statusmode eq 'Expired') {
        !          2067:                 $description .= &mt('users with expired [_1] roles',$rolefilter);
        !          2068:             } elsif ($statusmode eq 'Future') {
        !          2069:                 $description .= &mt('users with future [_1] roles',$rolefilter);
        !          2070:             } elsif ($statusmode eq 'Active') {
        !          2071:                 $description .= &mt('users with active [_1] roles',$rolefilter);
        !          2072:             } else {
        !          2073:                 if ($rolefilter eq 'Any') {
        !          2074:                     $description .= &mt('all users');
        !          2075:                 } else {
        !          2076:                     $description .= &mt('users with [_1] roles',$rolefilter);
        !          2077:                 }
        !          2078:             }
        !          2079:         }
        !          2080:     }
        !          2081:     return $description;
        !          2082: }
        !          2083:     
1.1       raeburn  2084: #################################################
                   2085: #################################################
                   2086: sub show_drop_list {
                   2087:     my ($r,$classlist,$keylist,$nosort)=@_;
                   2088:     my $cid=$env{'request.course.id'};
                   2089:     if (! exists($env{'form.sortby'})) {
                   2090:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   2091:                                                 ['sortby']);
                   2092:     }
                   2093:     my $sortby = $env{'form.sortby'};
                   2094:     if ($sortby !~ /^(username|domain|section|groups|fullname|id|start|end)$/) {
                   2095:         $sortby = 'username';
                   2096:     }
                   2097:     my $cdom = $env{'course.'.$cid.'.domain'};
                   2098:     my $cnum = $env{'course.'.$cid,'.num'};
                   2099:     my ($classgroups) = &Apache::loncoursedata::get_group_memberships(
                   2100:                                               $classlist,$keylist,$cdom,$cnum);
                   2101:     #
                   2102:     my $action = "drop";
                   2103:     $r->print(<<END);
                   2104: <input type="hidden" name="sortby" value="$sortby" />
                   2105: <input type="hidden" name="action" value="$action" />
                   2106: <input type="hidden" name="state"  value="done" />
                   2107: <script>
                   2108: function checkAll(field) {
                   2109:     for (i = 0; i < field.length; i++)
                   2110:         field[i].checked = true ;
                   2111: }
                   2112: 
                   2113: function uncheckAll(field) {
                   2114:     for (i = 0; i < field.length; i++)
                   2115:         field[i].checked = false ;
                   2116: }
                   2117: </script>
                   2118: <p>
                   2119: <input type="hidden" name="phase" value="four">
                   2120: END
                   2121: 
                   2122: my %lt=&Apache::lonlocal::texthash('usrn'   => "username",
                   2123:                                    'dom'    => "domain",
                   2124:                                    'sn'     => "student name",
                   2125:                                    'sec'    => "section",
                   2126:                                    'start'  => "start date",
                   2127:                                    'end'    => "end date",
                   2128:                                    'groups' => "active groups",
                   2129:                                    );
                   2130:     if ($nosort) {
                   2131:         $r->print(&Apache::loncommon::start_data_table());
                   2132:         $r->print(<<END);
                   2133: <tr>
                   2134:     <th>&nbsp;</th>
                   2135:     <th>$lt{'usrn'}</th>
                   2136:     <th>$lt{'dom'}</th>
                   2137:     <th>ID</th>
                   2138:     <th>$lt{'sn'}</th>
                   2139:     <th>$lt{'sec'}</th>
                   2140:     <th>$lt{'start'}</th>
                   2141:     <th>$lt{'end'}</th>
                   2142:     <th>$lt{'groups'}</th>
                   2143: </tr>
                   2144: END
                   2145: 
                   2146:     } else  {
                   2147:         $r->print(&Apache::loncommon::start_data_table());
                   2148:         $r->print(<<END);
                   2149: <tr><th>&nbsp;</th>
                   2150:     <th>
                   2151:        <a href="/adm/dropadd?action=$action&sortby=username">$lt{'usrn'}</a>
                   2152:     </th><th>
                   2153:        <a href="/adm/dropadd?action=$action&sortby=domain">$lt{'dom'}</a>
                   2154:     </th><th>
                   2155:        <a href="/adm/dropadd?action=$action&sortby=id">ID</a>
                   2156:     </th><th>
                   2157:        <a href="/adm/dropadd?action=$action&sortby=fullname">$lt{'sn'}</a>
                   2158:     </th><th>
                   2159:        <a href="/adm/dropadd?action=$action&sortby=section">$lt{'sec'}</a>
                   2160:     </th><th>
                   2161:        <a href="/adm/dropadd?action=$action&sortby=start">$lt{'start'}</a>
                   2162:     </th><th>
                   2163:        <a href="/adm/dropadd?action=$action&sortby=end">$lt{'end'}</a>
                   2164:     </th><th>
                   2165:        <a href="/adm/dropadd?action=$action&sortby=groups">$lt{'groups'}</a>
                   2166:     </th>
                   2167: </tr>
                   2168: END
                   2169:     }
                   2170:     #
                   2171:     # Sort the students
                   2172:     my %index;
                   2173:     my $i;
                   2174:     foreach (@$keylist) {
                   2175:         $index{$_} = $i++;
                   2176:     }
                   2177:     $index{'groups'} = scalar(@$keylist);
                   2178:     my $index  = $index{$sortby};
                   2179:     my $second = $index{'username'};
                   2180:     my $third  = $index{'domain'};
                   2181:     my @Sorted_Students = sort {
                   2182:         lc($classlist->{$a}->[$index])  cmp lc($classlist->{$b}->[$index])
                   2183:             ||
                   2184:         lc($classlist->{$a}->[$second]) cmp lc($classlist->{$b}->[$second])
                   2185:             ||
                   2186:         lc($classlist->{$a}->[$third]) cmp lc($classlist->{$b}->[$third])
                   2187:         } (keys(%$classlist));
                   2188:     foreach my $student (@Sorted_Students) {
                   2189:         my $error;
                   2190:         my $sdata = $classlist->{$student};
                   2191:         my $username = $sdata->[$index{'username'}];
                   2192:         my $domain   = $sdata->[$index{'domain'}];
                   2193:         my $section  = $sdata->[$index{'section'}];
                   2194:         my $name     = $sdata->[$index{'fullname'}];
                   2195:         my $id       = $sdata->[$index{'id'}];
                   2196:         my $start    = $sdata->[$index{'start'}];
                   2197:         my $end      = $sdata->[$index{'end'}];
                   2198:         my $groups = $classgroups->{$student};
                   2199:         my $active_groups;
                   2200:         if (ref($groups->{active}) eq 'HASH') {
                   2201:             $active_groups = join(', ',keys(%{$groups->{'active'}}));
                   2202:         }
                   2203:         if (! defined($start) || $start == 0) {
                   2204:             $start = &mt('none');
                   2205:         } else {
                   2206:             $start = &Apache::lonlocal::locallocaltime($start);
                   2207:         }
                   2208:         if (! defined($end) || $end == 0) {
                   2209:             $end = &mt('none');
                   2210:         } else {
                   2211:             $end = &Apache::lonlocal::locallocaltime($end);
                   2212:         }
                   2213:         my $status   = $sdata->[$index{'status'}];
                   2214:         next if ($status ne 'Active');
                   2215:         #
                   2216:         $r->print(&Apache::loncommon::start_data_table_row());
                   2217:         $r->print(<<"END");
                   2218:     <td><input type="checkbox" name="droplist" value="$student"></td>
                   2219:     <td>$username</td>
                   2220:     <td>$domain</td>
                   2221:     <td>$id</td>
                   2222:     <td>$name</td>
                   2223:     <td>$section</td>
                   2224:     <td>$start</td>
                   2225:     <td>$end</td>
                   2226:     <td>$active_groups</td>
                   2227: END
                   2228:         $r->print(&Apache::loncommon::end_data_table_row());
                   2229:     }
                   2230:     $r->print(&Apache::loncommon::end_data_table().'<br />');
                   2231:     %lt=&Apache::lonlocal::texthash(
                   2232:                        'dp'   => "Expire Users' Roles",
                   2233:                        'ca'   => "check all",
                   2234:                        'ua'   => "uncheck all",
                   2235:                                        );
                   2236:     $r->print(<<"END");
                   2237: </p><p>
                   2238: <input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.droplist)"> &nbsp;
                   2239: <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.droplist)">
                   2240: <p><input type=submit value="$lt{'dp'}"></p>
                   2241: END
                   2242:     return;
                   2243: }
                   2244: 
                   2245: #
                   2246: # Print out the initial form to get the file containing a list of users
                   2247: #
                   2248: sub print_first_users_upload_form {
                   2249:     my ($r,$context) = @_;
                   2250:     my $str;
                   2251:     $str  = '<input type="hidden" name="phase" value="two">';
                   2252:     $str .= '<input type="hidden" name="action" value="upload" />';
                   2253:     $str .= '<input type="hidden"   name="state"  value="got_file" />';
1.2     ! raeburn  2254:     $str .= "<h3>".&mt('Upload a file containing information about users')."</h3>\n";
1.1       raeburn  2255:     $str .= &Apache::loncommon::upfile_select_html();
                   2256:     $str .= "<p>\n";
                   2257:     $str .= '<input type="submit" name="fileupload" value="'.
1.2     ! raeburn  2258:         &mt('Upload file of users').'">'."\n";
1.1       raeburn  2259:     $str .= '<label><input type="checkbox" name="noFirstLine" /> '.
                   2260:         &mt('Ignore First Line')."</label></p>\n";
                   2261:     $str .= &Apache::loncommon::help_open_topic("Course_Create_Class_List",
                   2262:                          &mt("How do I create a users list from a spreadsheet")).
                   2263:                              "<br />\n";
                   2264:     $str .= &Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   2265:                            &mt("How do I create a CSV file from a spreadsheet")).
                   2266:                                "<br />\n";
                   2267:     $str .= &Apache::loncommon::end_page();
                   2268:     $r->print($str);
                   2269:     return;
                   2270: }
                   2271: 
                   2272: # ================================================= Drop/Add from uploaded file
                   2273: sub upfile_drop_add {
                   2274:     my ($r,$context) = @_;
                   2275:     &Apache::loncommon::load_tmp_file($r);
                   2276:     my @userdata=&Apache::loncommon::upfile_record_sep();
                   2277:     if($env{'form.noFirstLine'}){shift(@userdata);}
                   2278:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   2279:     my %fields=();
                   2280:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   2281:         if ($env{'form.upfile_associate'} eq 'reverse') {
                   2282:             if ($env{'form.f'.$i} ne 'none') {
                   2283:                 $fields{$keyfields[$i]}=$env{'form.f'.$i};
                   2284:             }
                   2285:         } else {
                   2286:             $fields{$env{'form.f'.$i}}=$keyfields[$i];
                   2287:         }
                   2288:     }
                   2289:     #
                   2290:     # Store the field choices away
                   2291:     foreach my $field (qw/username names
                   2292:                        fname mname lname gen id sec ipwd email role/) {
                   2293:         $env{'form.'.$field.'_choice'}=$fields{$field};
                   2294:     }
                   2295:     &Apache::loncommon::store_course_settings('enrollment_upload',
                   2296:                                               { 'username_choice' => 'scalar',
                   2297:                                                 'names_choice' => 'scalar',
                   2298:                                                 'fname_choice' => 'scalar',
                   2299:                                                 'mname_choice' => 'scalar',
                   2300:                                                 'lname_choice' => 'scalar',
                   2301:                                                 'gen_choice' => 'scalar',
                   2302:                                                 'id_choice' => 'scalar',
                   2303:                                                 'sec_choice' => 'scalar',
                   2304:                                                 'ipwd_choice' => 'scalar',
                   2305:                                                 'email_choice' => 'scalar',
                   2306:                                                 'role_choice'  => 'scalar' });
                   2307:     #
                   2308:     my ($startdate,$enddate) = &get_dates_from_form();
                   2309:     if ($env{'form.makedatesdefault'}) {
                   2310:         $r->print(&make_dates_default($startdate,$enddate));
                   2311:     }
                   2312:     # Determine domain and desired host (home server)
                   2313:     my $domain=$env{'request.role.domain'};
                   2314:     my $desiredhost = $env{'form.lcserver'};
                   2315:     if (lc($desiredhost) eq 'default') {
                   2316:         $desiredhost = undef;
                   2317:     } else {
                   2318:         my %home_servers = &Apache::lonnet::get_servers($domain,'library');
                   2319:         if (! exists($home_servers{$desiredhost})) {
                   2320:             $r->print('<span class="LC_error">'.&mt('Error').
                   2321:                       &mt('Invalid home server specified').'</span>');
                   2322:             $r->print(&Apache::loncommon::end_page());
                   2323:             return;
                   2324:         }
                   2325:     }
                   2326:     # Determine authentication mechanism
                   2327:     my $changeauth;
                   2328:     if ($context eq 'domain') {
                   2329:         $changeauth = $env{'form.changeauth'};
                   2330:     }
                   2331:     my $amode  = '';
                   2332:     my $genpwd = '';
                   2333:     if ($env{'form.login'} eq 'krb') {
                   2334:         $amode='krb';
                   2335:         $amode.=$env{'form.krbver'};
                   2336:         $genpwd=$env{'form.krbarg'};
                   2337:     } elsif ($env{'form.login'} eq 'int') {
                   2338:         $amode='internal';
                   2339:         if ((defined($env{'form.intarg'})) && ($env{'form.intarg'})) {
                   2340:             $genpwd=$env{'form.intarg'};
                   2341:         }
                   2342:     } elsif ($env{'form.login'} eq 'loc') {
                   2343:         $amode='localauth';
                   2344:         if ((defined($env{'form.locarg'})) && ($env{'form.locarg'})) {
                   2345:             $genpwd=$env{'form.locarg'};
                   2346:         }
                   2347:     }
                   2348:     if ($amode =~ /^krb/) {
                   2349:         if (! defined($genpwd) || $genpwd eq '') {
                   2350:             $r->print('<span class="Error">'.
                   2351:                       &mt('Unable to enroll users').' '.
                   2352:                       &mt('No Kerberos domain was specified.').'</span></p>');
                   2353:             $amode = ''; # This causes the loop below to be skipped
                   2354:         }
                   2355:     }
                   2356:     my ($cid,$defaultsec,$defaultrole,$setting);
                   2357:     if ($context eq 'domain') {
                   2358:         $setting = $env{'form.roleaction'};
                   2359:         if ($setting eq 'domain') {
                   2360:             $defaultrole = $env{'form.defaultrole'};
                   2361:         } elsif ($setting eq 'course') {
                   2362:             $defaultrole = $env{'form.courserole'};
                   2363:         }  
                   2364:     } elsif ($context eq 'construction_space') {
                   2365:         $defaultrole = $env{'form.defaultrole'};
                   2366:     }
                   2367:     if ($context eq 'domain' && $setting eq 'course') { 
                   2368:         if ($env{'form.newsec'} ne '') {
                   2369:             $defaultsec = $env{'form.newsec'};
                   2370:         } elsif ($env{'form.defaultsec'} ne '') {
                   2371:             $defaultsec = $env{'form.defaultsec'}
                   2372:         }
                   2373:     }
                   2374:     if ($env{'request.course.id'} ne '') {
                   2375:         $cid = $env{'request.course.id'};
                   2376:     } elsif ($env{'form.defaultdomain'} ne '' && $env{'form.defaultcourse'} ne '') {
                   2377:         $cid = $env{'form.defaultdomain'}.'_'.
                   2378:                $env{'form.defaultcourse'};
                   2379:     }
                   2380:     if ( $domain eq &LONCAPA::clean_domain($domain)
                   2381:         && ($amode ne '')) {
                   2382:         #######################################
                   2383:         ##         Add/Modify Users          ##
                   2384:         #######################################
                   2385:         if ($context eq 'course') {
                   2386:             $r->print('<h3>'.&mt('Enrolling Users')."</h3>\n<p>\n");
                   2387:         } elsif ($context eq 'construction_space') {
                   2388:             $r->print('<h3>'.&mt('Updating Co-authors')."</h3>\n<p>\n");
                   2389:         } else {
                   2390:             $r->print('<h3>'.&mt('Adding/Modifying Users')."</h3>\n<p>\n");
                   2391:         }
                   2392:         my %counts = (
                   2393:                        user => 0,
                   2394:                        auth => 0,
                   2395:                        role => 0,
                   2396:                      );
                   2397:         my $flushc=0;
                   2398:         my %student=();
                   2399:         my %curr_groups;
                   2400:         my %userchg;
                   2401:         if ($context eq 'course') {
                   2402:             # Get information about course groups
                   2403:             %curr_groups = &Apache::longroup::coursegroups();
                   2404:         }
                   2405:         # Get new users list
                   2406:         foreach (@userdata) {
                   2407:             my %entries=&Apache::loncommon::record_sep($_);
                   2408:             # Determine user name
                   2409:             unless (($entries{$fields{'username'}} eq '') ||
                   2410:                     (!defined($entries{$fields{'username'}}))) {
                   2411:                 my ($fname, $mname, $lname,$gen) = ('','','','');
                   2412:                 if (defined($fields{'names'})) {
                   2413:                     ($lname,$fname,$mname)=($entries{$fields{'names'}}=~
                   2414:                                             /([^\,]+)\,\s*(\w+)\s*(.*)$/);
                   2415:                 } else {
                   2416:                     if (defined($fields{'fname'})) {
                   2417:                         $fname=$entries{$fields{'fname'}};
                   2418:                     }
                   2419:                     if (defined($fields{'mname'})) {
                   2420:                         $mname=$entries{$fields{'mname'}};
                   2421:                     }
                   2422:                     if (defined($fields{'lname'})) {
                   2423:                         $lname=$entries{$fields{'lname'}};
                   2424:                     }
                   2425:                     if (defined($fields{'gen'})) {
                   2426:                         $gen=$entries{$fields{'gen'}};
                   2427:                     }
                   2428:                 }
                   2429:                 if ($entries{$fields{'username'}}
                   2430:                     ne &LONCAPA::clean_username($entries{$fields{'username'}})) {
                   2431:                     $r->print('<br />'.
                   2432:       &mt('<b>[_1]</b>: Unacceptable username for user [_2] [_3] [_4] [_5]',
                   2433:           $entries{$fields{'username'}},$fname,$mname,$lname,$gen).
                   2434:                               '</b>');
                   2435:                 } else {
                   2436:                     my $username = $entries{$fields{'username'}}; 
                   2437:                     my $sec;
                   2438:                     if ($context eq 'course' || $setting eq 'course') {
                   2439:                         # determine section number
                   2440:                         if (defined($fields{'sec'})) {
                   2441:                             if (defined($entries{$fields{'sec'}})) {
                   2442:                                 $sec=$entries{$fields{'sec'}};
                   2443:                             }
                   2444:                         } else {
                   2445:                             $sec = $defaultsec;
                   2446:                         }
                   2447:                         # remove non alphanumeric values from section
                   2448:                         $sec =~ s/\W//g;
                   2449:                         if ($sec eq "none" || $sec eq 'all') {
                   2450:                             $r->print('<br />'.
                   2451:       &mt('<b>[_1]</b>: Unable to enroll: section name "[_2]" for user [_3] [_4] [_5] [_6] is a reserved word.',
                   2452:                                       $username,$sec,$fname,$mname,$lname,$gen));
                   2453:                             next;
                   2454:                         } elsif (($sec ne '') && (exists($curr_groups{$sec}))) {
                   2455:                             $r->print('<br />'.
                   2456:       &mt('<b>[_1]</b>: Unable to enroll: section name "[_2]" for user [_3] [_4] [_5] [_6] is a course group. Section names and group names must be distinct.',
                   2457:                                       $username,$sec,$fname,$mname,$lname,$gen));
                   2458:                             next;
                   2459:                         }
                   2460:                     }
                   2461:                     # determine id number
                   2462:                     my $id='';
                   2463:                     if (defined($fields{'id'})) {
                   2464:                         if (defined($entries{$fields{'id'}})) {
                   2465:                             $id=$entries{$fields{'id'}};
                   2466:                         }
                   2467:                         $id=~tr/A-Z/a-z/;
                   2468:                     }
                   2469:                     # determine email address
                   2470:                     my $email='';
                   2471:                     if (defined($fields{'email'})) {
                   2472:                         if (defined($entries{$fields{'email'}})) {
                   2473:                             $email=$entries{$fields{'email'}};
                   2474:                             unless ($email=~/^[^\@]+\@[^\@]+$/) { $email=''; }                        }
                   2475:                     }
                   2476:                     # determine user password
                   2477:                     my $password = $genpwd;
                   2478:                     if (defined($fields{'ipwd'})) {
                   2479:                         if ($entries{$fields{'ipwd'}}) {
                   2480:                             $password=$entries{$fields{'ipwd'}};
                   2481:                         }
                   2482:                     }
                   2483:                     # determine user role
                   2484:                     my $role = '';
                   2485:                     if (defined($fields{'role'})) {
                   2486:                         if ($entries{$fields{'role'}}) {
1.2     ! raeburn  2487:                             my @poss_roles = 
1.1       raeburn  2488:                                  &curr_role_permissions($context,$setting);
1.2     ! raeburn  2489:                             if (grep(/^\Q$entries{$fields{'role'}}\E/,@poss_roles)) {
1.1       raeburn  2490:                                 $role=$entries{$fields{'role'}};
                   2491:                             } else {
                   2492:                                 my $rolestr = join(', ',@poss_roles);
                   2493:                                 $r->print('<br />'.
                   2494:       &mt('<b>[_1]</b>: You do not have permission to add the requested role [_2] for the user.',$entries{$fields{'username'}},$entries{$fields{'role'}}).'<br />'.&mt('Allowable role(s) is/are: [_1].',$rolestr)."\n");
                   2495:                                 next;
                   2496:                             }
                   2497:                         }
                   2498:                     }
                   2499:                     if ($role eq '') {
                   2500:                         $role = $defaultrole;
                   2501:                     }
                   2502:                     # Clean up whitespace
                   2503:                     foreach (\$domain,\$username,\$id,\$fname,\$mname,
                   2504:                              \$lname,\$gen,\$sec,\$role) {
                   2505:                         $$_ =~ s/(\s+$|^\s+)//g;
                   2506:                     }
                   2507:                     if ($password || $env{'form.login'} eq 'loc') {
                   2508:                         my ($userresult,$authresult,$roleresult);
                   2509:                         if ($role eq 'st') {
                   2510:                             &modifystudent($domain,$username,$cid,$sec,
                   2511:                                            $desiredhost);
                   2512:                             $roleresult = 
                   2513:                                 &Apache::lonnet::modifystudent
                   2514:                                     ($domain,$username,$id,$amode,$password,
                   2515:                                      $fname,$mname,$lname,$gen,$sec,$enddate,
                   2516:                                      $startdate,$env{'form.forceid'},
                   2517:                                      $desiredhost,$email);
                   2518:                         } else {
                   2519:                             ($userresult,$authresult,$roleresult) = 
                   2520:                                 &modifyuserrole($context,$setting,
                   2521:                                     $changeauth,$cid,$domain,$username, 
                   2522:                                     $id,$amode,$password,$fname,
                   2523:                                     $mname,$lname,$gen,$sec,
                   2524:                                     $env{'form.forceid'},$desiredhost,
                   2525:                                     $email,$role,$enddate,$startdate);
                   2526:                         }
                   2527:                         $flushc = 
                   2528:                             &user_change_result($r,$userresult,$authresult,
                   2529:                                                 $roleresult,\%counts,$flushc,
                   2530:                                                 $username,%userchg);
                   2531:                     } else {
                   2532:                         if ($context eq 'course') {
                   2533:                             $r->print('<br />'. 
                   2534:       &mt('<b>[_1]</b>: Unable to enroll.  No password specified.',$username)
                   2535:                                      );
                   2536:                         } elsif ($context eq 'construction_space') {
                   2537:                             $r->print('<br />'.
                   2538:       &mt('<b>[_1]</b>: Unable to add co-author.  No password specified.',$username)
                   2539:                                      );
                   2540:                         } else {
                   2541:                             $r->print('<br />'.
                   2542:       &mt('<b>[_1]</b>: Unable to add user.  No password specified.',$username)
                   2543:                                      );
                   2544:                         }
                   2545:                     }
                   2546:                 }
                   2547:             }
                   2548:         } # end of foreach (@userdata)
                   2549:         # Flush the course logs so reverse user roles immediately updated
                   2550:         if ($context eq 'course' || ($context eq 'domain' && $setting eq 'course')) {
                   2551:             &Apache::lonnet::flushcourselogs();
                   2552:         }
                   2553:         $r->print("</p>\n<p>\n".&mt('Processed [_1] user(s).',$counts{'user'}).
                   2554:                   "</p>\n");
                   2555:         if ($counts{'role'} > 0) {
                   2556:             $r->print("<p>\n".
                   2557:                       &mt('Roles added for [_1] users. If user is active, the new role will be available when the user next logs in to LON-CAPA.',$counts{'role'})."</p>\n");
                   2558:         }
                   2559:         if ($counts{'auth'} > 0) {
                   2560:             $r->print("<p>\n".
                   2561:                       &mt('Authentication changed for [_1] existing users.',
                   2562:                           $counts{'auth'})."</p>\n");
                   2563:         }
                   2564:         $r->print('<form name="uploadresult" action="/adm/createuser">');
                   2565:         $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','prevphase','currstate']));
                   2566:         $r->print('</form>');
                   2567:         #####################################
                   2568:         #           Drop students           #
                   2569:         #####################################
                   2570:         if ($env{'form.fullup'} eq 'yes') {
                   2571:             $r->print('<h3>'.&mt('Dropping Students')."</h3>\n");
                   2572:             #  Get current classlist
                   2573:             my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
                   2574:             if (! defined($classlist)) {
                   2575:                 $r->print(&mt('There are no students currently enrolled.').
                   2576:                           "\n");
                   2577:             } else {
                   2578:                 # Remove the students we just added from the list of students.
                   2579:                 foreach (@userdata) {
                   2580:                     my %entries=&Apache::loncommon::record_sep($_);
                   2581:                     unless (($entries{$fields{'username'}} eq '') ||
                   2582:                             (!defined($entries{$fields{'username'}}))) {
                   2583:                         delete($classlist->{$entries{$fields{'username'}}.
                   2584:                                                 ':'.$domain});
                   2585:                     }
                   2586:                 }
                   2587:                 # Print out list of dropped students.
                   2588:                 &show_drop_list($r,$classlist,$keylist,'nosort');
                   2589:             }
                   2590:         }
                   2591:     } # end of unless
                   2592: }
                   2593: 
                   2594: sub user_change_result {
                   2595:     my ($r,$userresult,$authresult,$roleresult,$counts,$flushc,$username,
                   2596:         $userchg) = @_;
                   2597:     my $okresult = 0;
                   2598:     if ($userresult ne 'ok') {
                   2599:         if ($userresult =~ /^error:(.+)$/) {
                   2600:             my $error = $1;
                   2601:             $r->print('<br />'.
                   2602:                   &mt('<b>[_1]</b>:  Unable to add/modify: [_2]',$username,$error));
                   2603:         }
                   2604:     } else {
                   2605:         $counts->{'user'} ++;
                   2606:         $okresult = 1;
                   2607:     }
                   2608:     if ($authresult ne 'ok') {
                   2609:         if ($authresult =~ /^error:(.+)$/) {
                   2610:             my $error = $1;
                   2611:             $r->print('<br />'.
                   2612:                   &mt('<b>[_1]</b>:  Unable to modify authentication: [_2]',$username,$error));
                   2613:         } 
                   2614:     } else {
                   2615:         $counts->{'auth'} ++;
                   2616:         $okresult = 1;
                   2617:     }
                   2618:     if ($roleresult ne 'ok') {
                   2619:         if ($roleresult =~ /^error:(.+)$/) {
                   2620:             my $error = $1;
                   2621:             $r->print('<br />'.
                   2622:                   &mt('<b>[_1]</b>:  Unable to add role: [_2]',$username,$error));
                   2623:         }
                   2624:     } else {
                   2625:         $counts->{'role'} ++;
                   2626:         $okresult = 1;
                   2627:     }
                   2628:     if ($okresult) {
                   2629:         $flushc++;
                   2630:         $userchg->{$username}=1;
                   2631:         $r->print('. ');
                   2632:         if ($flushc>15) {
                   2633:             $r->rflush;
                   2634:             $flushc=0;
                   2635:         }
                   2636:     }
                   2637:     return $flushc;
                   2638: }
                   2639: 
                   2640: # ========================================================= Menu Phase Two Drop
                   2641: sub print_expire_menu {
                   2642:     my ($r,$context) = @_;
                   2643:     $r->print("<h3>".&mt("Expire Users' Roles")."</h3>");
                   2644:     my $cid=$env{'request.course.id'};
                   2645:     my ($classlist,$keylist) = &Apache::loncoursedata::get_classlist();
                   2646:     if (! defined($classlist)) {
                   2647:         $r->print(&mt('There are no students currently enrolled.')."\n");
                   2648:         return;
                   2649:     }
                   2650:     # Print out the available choices
                   2651:     &show_drop_list($r,$classlist,$keylist);
                   2652:     return;
                   2653: }
                   2654: 
                   2655: 
                   2656: # ================================================================== Phase four
                   2657: 
                   2658: sub expire_user_list {
                   2659:     my ($r,$context) = @_;
                   2660:     my $count=0;
                   2661:     my @droplist = &Apache::loncommon::get_env_multiple('form.droplist');
                   2662:     foreach (@droplist) {
                   2663:         my ($uname,$udom)=split(/\:/,$_);
                   2664:         # drop student
                   2665:         my $result = &modifystudent($udom,$uname,$env{'request.course.id'});
                   2666:         if ($result eq 'ok' || $result eq 'ok:') {
                   2667:             $r->print(&mt('Dropped [_1]',$uname.'@'.$udom).'<br>');
                   2668:             $count++;
                   2669:         } else {
                   2670:             $r->print(
                   2671:           &mt('Error dropping [_1]:[_2]',$uname.'@'.$udom,$result).
                   2672:                       '<br />');
                   2673:         }
                   2674:     }
                   2675:     $r->print('<p><b>'.&mt('Dropped [_1] user(s).',$count).'</b></p>');
                   2676:     $r->print('<p>'.&mt('Re-enrollment will re-activate data.')) if ($count);
                   2677: }
                   2678: 
                   2679: sub section_check_js {
                   2680:     my $groupslist;
                   2681:     my %curr_groups = &Apache::longroup::coursegroups();
                   2682:     if (%curr_groups) {
                   2683:         $groupslist = join('","',sort(keys(%curr_groups)));
                   2684:     }
                   2685:     return <<"END";
                   2686: function validate(caller) {
                   2687:     var groups = new Array("$groupslist");
                   2688:     var secname = caller.value;
                   2689:     if ((secname == 'all') || (secname == 'none')) {
                   2690:         alert("'"+secname+"' may not be used as the name for a section, as it is a reserved word.\\nPlease choose a different section name.");
                   2691:         return 'error';
                   2692:     }
                   2693:     if (secname != '') {
                   2694:         for (var k=0; k<groups.length; k++) {
                   2695:             if (secname == groups[k]) {
                   2696:                 alert("'"+secname+"' may not be used as the name for a section, as it is the name of a course group.\\nSection names and group names must be distinct. Please choose a different section name.");
                   2697:                 return 'error';
                   2698:             }
                   2699:         }
                   2700:     }
                   2701:     return 'ok';
                   2702: }
                   2703: END
                   2704: }
                   2705: 
                   2706: sub set_login {
                   2707:     my ($dom,$authformkrb,$authformint,$authformloc) = @_;
                   2708:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2709:     my $response;
                   2710:     my ($authnum,%can_assign) =
                   2711:         &Apache::loncommon::get_assignable_auth($dom);
                   2712:     if ($authnum) {
                   2713:         $response = &Apache::loncommon::start_data_table();
                   2714:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
                   2715:             $response .= &Apache::loncommon::start_data_table_row().
                   2716:                          '<td>'.$authformkrb.'</td>'.
                   2717:                          &Apache::loncommon::end_data_table_row()."\n";
                   2718:         }
                   2719:         if ($can_assign{'int'}) {
                   2720:             $response .= &Apache::loncommon::start_data_table_row().
                   2721:                          '<td>'.$authformint.'</td>'.
                   2722:                          &Apache::loncommon::end_data_table_row()."\n"
                   2723:         }
                   2724:         if ($can_assign{'loc'}) {
                   2725:             $response .= &Apache::loncommon::start_data_table_row().
                   2726:                          '<td>'.$authformloc.'</td>'.
                   2727:                          &Apache::loncommon::end_data_table_row()."\n";
                   2728:         }
                   2729:         $response .= &Apache::loncommon::end_data_table();
                   2730:     }
                   2731:     return $response;
                   2732: }
                   2733: 
                   2734: 1;
                   2735: 

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