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

1.1       raeburn     1: # The LearningOnline Network with CAPA
                      2: # Utility functions for managing LON-CAPA user accounts
                      3: #
1.11    ! raeburn     4: # $Id: lonuserutils.pm,v 1.10 2007/12/05 19:11:37 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;
1.8       raeburn    38: use Apache::longroup;
                     39: use LONCAPA qw(:DEFAULT :match);
1.1       raeburn    40: 
                     41: ###############################################################
                     42: ###############################################################
                     43: # Drop student from all sections of a course, except optional $csec
                     44: sub modifystudent {
                     45:     my ($udom,$unam,$courseid,$csec,$desiredhost)=@_;
                     46:     # if $csec is undefined, drop the student from all the courses matching
                     47:     # this one.  If $csec is defined, drop them from all other sections of
                     48:     # this course and add them to section $csec
                     49:     my $cdom = $env{'course.'.$courseid.'.domain'};
                     50:     my $cnum = $env{'course.'.$courseid.'.num'};
                     51:     my %roles = &Apache::lonnet::dump('roles',$udom,$unam);
                     52:     my ($tmp) = keys(%roles);
                     53:     # Bail out if we were unable to get the students roles
                     54:     return "$1" if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                     55:     # Go through the roles looking for enrollment in this course
                     56:     my $result = '';
                     57:     foreach my $course (keys(%roles)) {
                     58:         if ($course=~m{^/\Q$cdom\E/\Q$cnum\E(?:\/)*(?:\s+)*(\w+)*\_st$}) {
                     59:             # We are in this course
                     60:             my $section=$1;
                     61:             $section='' if ($course eq "/$cdom/$cnum".'_st');
                     62:             if (defined($csec) && $section eq $csec) {
                     63:                 $result .= 'ok:';
                     64:             } elsif ( ((!$section) && (!$csec)) || ($section ne $csec) ) {
                     65:                 my (undef,$end,$start)=split(/\_/,$roles{$course});
                     66:                 my $now=time;
                     67:                 # if this is an active role
                     68:                 if (!($start && ($now<$start)) || !($end && ($now>$end))) {
                     69:                     my $reply=&Apache::lonnet::modifystudent
                     70:                         # dom  name  id mode pass     f     m     l     g
                     71:                         ($udom,$unam,'',  '',  '',undef,undef,undef,undef,
                     72:                          $section,time,undef,undef,$desiredhost);
                     73:                     $result .= $reply.':';
                     74:                 }
                     75:             }
                     76:         }
                     77:     }
                     78:     if ($result eq '') {
                     79:         $result = 'Unable to find section for this student';
                     80:     } else {
                     81:         $result =~ s/(ok:)+/ok/g;
                     82:     }
                     83:     return $result;
                     84: }
                     85: 
                     86: sub modifyuserrole {
                     87:     my ($context,$setting,$changeauth,$cid,$udom,$uname,$uid,$umode,$upass,
                     88:         $first,$middle,$last,$gene,$sec,$forceid,$desiredhome,$email,$role,
1.5       raeburn    89:         $end,$start,$checkid) = @_;
                     90:     my ($scope,$userresult,$authresult,$roleresult,$idresult);
1.1       raeburn    91:     if ($setting eq 'course' || $context eq 'course') {
                     92:         $scope = '/'.$cid;
                     93:         $scope =~ s/\_/\//g;
                     94:         if ($role ne 'cc' && $sec ne '') {
                     95:             $scope .='/'.$sec;
                     96:         }
1.5       raeburn    97:     } elsif ($context eq 'domain') {
1.1       raeburn    98:         $scope = '/'.$env{'request.role.domain'}.'/';
1.5       raeburn    99:     } elsif ($context eq 'construction_space') {
1.1       raeburn   100:         $scope =  '/'.$env{'user.domain'}.'/'.$env{'user.name'};
                    101:     }
                    102:     if ($context eq 'domain') {
                    103:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
                    104:         if ($uhome ne 'no_host') {
1.5       raeburn   105:             if (($changeauth eq 'Yes') && (&Apache::lonnet::allowed('mau',$udom))) {
1.1       raeburn   106:                 if ((($umode =~ /^krb4|krb5|internal$/) && $upass ne '') ||
                    107:                     ($umode eq 'localauth')) {
                    108:                     $authresult = &Apache::lonnet::modifyuserauth($udom,$uname,$umode,$upass);
                    109:                 }
                    110:             }
1.5       raeburn   111:             if (($forceid) && (&Apache::lonnet::allowed('mau',$udom)) &&
                    112:                 ($env{'form.recurseid'}) && ($checkid)) {
                    113:                 my %userupdate = (
                    114:                                   lastname   => $last,
                    115:                                   middlename => $middle,
                    116:                                   firstname  => $first,
                    117:                                   generation => $gene,
                    118:                                   id         => $uid,
                    119:                                  );
                    120:                 $idresult = &propagate_id_change($uname,$udom,\%userupdate);
                    121:             }
1.1       raeburn   122:         }
                    123:     }
                    124:     $userresult =
                    125:         &Apache::lonnet::modifyuser($udom,$uname,$uid,$umode,$upass,$first,
                    126:                                     $middle,$last,$gene,$forceid,$desiredhome,
                    127:                                     $email,$role,$start,$end);
                    128:     if ($userresult eq 'ok') {
1.5       raeburn   129:         if ($role ne '') {
1.1       raeburn   130:             $roleresult = &Apache::lonnet::assignrole($udom,$uname,$scope,
                    131:                                                       $role,$end,$start);
                    132:         }
                    133:     }
1.5       raeburn   134:     return ($userresult,$authresult,$roleresult,$idresult);
1.1       raeburn   135: }
                    136: 
1.5       raeburn   137: sub propagate_id_change {
                    138:     my ($uname,$udom,$user) = @_;
                    139:     my (@types,@roles,@cdoms);
                    140:     @types = ('active','future');
                    141:     @roles = ('st');
                    142:     my $idresult;
                    143:     my %roleshash = &Apache::lonnet::get_my_roles($uname,
                    144:                         $udom,'userroles',\@types,\@roles,\@cdoms);
                    145:     foreach my $item (keys(%roleshash)) {
                    146:         my ($cnum,$cdom,$role) = split(/:/,$item);
                    147:         my ($start,$end) = split(/:/,$roleshash{$item});
                    148:         if (&Apache::lonnet::is_course($cdom,$cnum)) {
                    149:             my %userupdate;
                    150:             my $result = &update_classlist($cdom,$cnum,$udom,$uname,\%userupdate);
                    151:             if ($result eq 'ok') {
                    152:                 $idresult .= "Classlist change: $uname:$udom - class -> $cnum:$cdom\n";
                    153:             } else {
                    154:                 $idresult .= "Error - $result -during classlist update for $uname:$udom in $cnum:$cdom\n";
                    155:             }
                    156:         }
                    157:     }
                    158:     return $idresult;
                    159: }
                    160: 
                    161: sub update_classlist {
                    162:     my ($cdom,$cnum,$udom,$uname,$user) = @_;
1.6       albertel  163:     my ($uid,$classlistentry);
1.5       raeburn   164:     my $fullname =
                    165:         &Apache::lonnet::format_name($user->{'firstname'},$user->{'middlename'},
                    166:                                      $user->{'lastname'},$user->{'generation'},
                    167:                                      'lastname');
                    168:     my %classhash = &Apache::lonnet::get('classlist',[$uname.':'.$udom],
                    169:                                          $cdom,$cnum);
                    170:     my @classinfo = split(/:/,$classhash{$uname.':'.$udom});
                    171:     my $ididx=&Apache::loncoursedata::CL_ID() - 2;
                    172:     my $nameidx=&Apache::loncoursedata::CL_FULLNAME() - 2;
                    173:     for (my $i=0; $i<@classinfo; $i++) {
                    174:         if ($i == $ididx) {
                    175:             if (defined($user->{'id'})) {
                    176:                 $classlistentry .= $user->{'id'}.':';
                    177:             } else {
                    178:                 $classlistentry .= $classinfo[$i].':';
                    179:             }
                    180:         } elsif ($i == $nameidx) {
                    181:             $classlistentry .= $fullname.':';
                    182:         } else {
                    183:             $classlistentry .= $classinfo[$i].':';
                    184:         }
                    185:     }
                    186:     $classlistentry =~ s/:$//;
                    187:     my $reply=&Apache::lonnet::cput('classlist',
                    188:                                     {"$uname:$udom" => $classlistentry},
                    189:                                     $cdom,$cnum);
                    190:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                    191:         return 'ok';
                    192:     } else {
                    193:         return 'error: '.$reply;
                    194:     }
                    195: }
                    196: 
                    197: 
1.1       raeburn   198: ###############################################################
                    199: ###############################################################
1.2       raeburn   200: # build a role type and role selection form
                    201: sub domain_roles_select {
                    202:     # Set up the role type and role selection boxes when in 
                    203:     # domain context   
                    204:     #
                    205:     # Role types
                    206:     my @roletypes = ('domain','construction_space','course');
                    207:     my %lt = &role_type_names();
1.1       raeburn   208:     #
                    209:     # build up the menu information to be passed to
                    210:     # &Apache::loncommon::linked_select_forms
                    211:     my %select_menus;
1.2       raeburn   212:     if ($env{'form.roletype'} eq '') {
                    213:         $env{'form.roletype'} = 'domain';
                    214:     }
                    215:     foreach my $roletype (@roletypes) {
1.1       raeburn   216:         # set up the text for this domain
1.2       raeburn   217:         $select_menus{$roletype}->{'text'}= $lt{$roletype};
1.1       raeburn   218:         # we want a choice of 'default' as the default in the second menu
1.2       raeburn   219:         if ($env{'form.roletype'} ne '') {
                    220:             $select_menus{$roletype}->{'default'} = $env{'form.showrole'};
                    221:         } else { 
                    222:             $select_menus{$roletype}->{'default'} = 'Any';
                    223:         }
1.1       raeburn   224:         # Now build up the other items in the second menu
1.2       raeburn   225:         my @roles;
                    226:         if ($roletype eq 'domain') {
                    227:             @roles = &domain_roles();
                    228:         } elsif ($roletype eq 'construction_space') {
                    229:             @roles = &construction_space_roles();
                    230:         } else {
                    231:             @roles = &course_roles('domain');
1.5       raeburn   232:             unshift(@roles,'cr');
1.1       raeburn   233:         }
1.2       raeburn   234:         my $order = ['Any',@roles];
                    235:         $select_menus{$roletype}->{'order'} = $order; 
                    236:         foreach my $role (@roles) {
1.5       raeburn   237:             if ($role eq 'cr') {
                    238:                 $select_menus{$roletype}->{'select2'}->{$role} =
                    239:                               &mt('Custom role');
                    240:             } else {
                    241:                 $select_menus{$roletype}->{'select2'}->{$role} = 
                    242:                               &Apache::lonnet::plaintext($role);
                    243:             }
1.2       raeburn   244:         }
                    245:         $select_menus{$roletype}->{'select2'}->{'Any'} = &mt('Any');
1.1       raeburn   246:     }
1.2       raeburn   247:     my $result = &Apache::loncommon::linked_select_forms
                    248:         ('studentform',('&nbsp;'x3).&mt('Role: '),$env{'form.roletype'},
                    249:          'roletype','showrole',\%select_menus,['domain','construction_space','course']);
1.1       raeburn   250:     return $result;
                    251: }
                    252: 
                    253: ###############################################################
                    254: ###############################################################
                    255: sub hidden_input {
                    256:     my ($name,$value) = @_;
                    257:     return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
                    258: }
                    259: 
                    260: sub print_upload_manager_header {
                    261:     my ($r,$datatoken,$distotal,$krbdefdom,$context)=@_;
                    262:     my $javascript;
                    263:     #
                    264:     if (! exists($env{'form.upfile_associate'})) {
                    265:         $env{'form.upfile_associate'} = 'forward';
                    266:     }
                    267:     if ($env{'form.associate'} eq 'Reverse Association') {
                    268:         if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                    269:             $env{'form.upfile_associate'} = 'reverse';
                    270:         } else {
                    271:             $env{'form.upfile_associate'} = 'forward';
                    272:         }
                    273:     }
                    274:     if ($env{'form.upfile_associate'} eq 'reverse') {
                    275:         $javascript=&upload_manager_javascript_reverse_associate();
                    276:     } else {
                    277:         $javascript=&upload_manager_javascript_forward_associate();
                    278:     }
                    279:     #
                    280:     # Deal with restored settings
                    281:     my $password_choice = '';
                    282:     if (exists($env{'form.ipwd_choice'}) &&
                    283:         $env{'form.ipwd_choice'} ne '') {
                    284:         # If a column was specified for password, assume it is for an
                    285:         # internal password.  This is a bug waiting to be filed (could be
                    286:         # local or krb auth instead of internal) but I do not have the
                    287:         # time to mess around with this now.
                    288:         $password_choice = 'int';
                    289:     }
                    290:     #
                    291:     my $javascript_validations =
                    292:         &javascript_validations('auth',$krbdefdom,$password_choice,undef,
                    293:                                 $env{'request.role.domain'});
                    294:     my $checked=(($env{'form.noFirstLine'})?' checked="checked" ':'');
                    295:     $r->print(&mt('Total number of records found in file: <b>[_1]</b>.',$distotal).
                    296:               "<br />\n");
                    297:     $r->print('<div class="LC_left_float"><h3>'.
                    298:               &mt('Identify fields in uploaded list')."</h3>\n");
                    299:     $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");
                    300:     $r->print(&hidden_input('action','upload').
                    301:               &hidden_input('state','got_file').
                    302:               &hidden_input('associate','').
                    303:               &hidden_input('datatoken',$datatoken).
                    304:               &hidden_input('fileupload',$env{'form.fileupload'}).
                    305:               &hidden_input('upfiletype',$env{'form.upfiletype'}).
                    306:               &hidden_input('upfile_associate',$env{'form.upfile_associate'}));
                    307:     $r->print('<br /><input type="button" value="Reverse Association" '.
                    308:               'name="'.&mt('Reverse Association').'" '.
                    309:               'onClick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />');
                    310:     $r->print('<label><input type="checkbox" name="noFirstLine"'.$checked.'/>'.
                    311:               &mt('Ignore First Line').'</label>');
                    312:     $r->print("<br /><br />\n".
                    313:               '<script type="text/javascript" language="Javascript">'."\n".
                    314:               $javascript."\n".$javascript_validations.'</script>');
                    315: }
                    316: 
                    317: ###############################################################
                    318: ###############################################################
                    319: sub javascript_validations {
                    320:     my ($mode,$krbdefdom,$curr_authtype,$curr_authfield,$domain)=@_;
                    321:     my $authheader;
                    322:     if ($mode eq 'auth') {
                    323:         my %param = ( formname => 'studentform',
                    324:                       kerb_def_dom => $krbdefdom,
                    325:                       curr_authtype => $curr_authtype);
                    326:         $authheader = &Apache::loncommon::authform_header(%param);
                    327:     } elsif ($mode eq 'createcourse') {
                    328:         my %param = ( formname => 'ccrs',
                    329:                       kerb_def_dom => $krbdefdom,
                    330:                       curr_authtype => $curr_authtype );
                    331:         $authheader = &Apache::loncommon::authform_header(%param);
                    332:     } elsif ($mode eq 'modifycourse') {
                    333:         my %param = ( formname => 'cmod',
                    334:                   kerb_def_dom => $krbdefdom,
                    335:                   mode => 'modifycourse',
                    336:                   curr_authtype => $curr_authtype,
                    337:                   curr_autharg => $curr_authfield );
                    338:         $authheader = &Apache::loncommon::authform_header(%param);
                    339:     }
                    340: 
                    341:     my %alert = &Apache::lonlocal::texthash
                    342:         (username => 'You need to specify the username field.',
                    343:          authen   => 'You must choose an authentication type.',
                    344:          krb      => 'You need to specify the Kerberos domain.',
                    345:          ipass    => 'You need to specify the initial password.',
                    346:          name     => 'The optional name field was not specified.',
                    347:          snum     => 'The optional ID number field was not specified.',
                    348:          section  => 'The optional section field was not specified.',
                    349:          email    => 'The optional email address field was not specified.',
                    350:          role     => 'The optional role field was not specified.',
                    351:          continue => 'Continue adding users?',
                    352:          );
                    353: 
                    354: #    my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
                    355:     my $function_name =(<<END);
                    356: function verify_message (vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail) {
                    357: END
                    358:     my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($domain);
                    359:     my $auth_checks;
                    360:     if ($mode eq 'createcourse') {
                    361:         $auth_checks .= (<<END);
                    362:     if (vf.autoadds[0].checked == true) {
                    363:         if (current.radiovalue == null || current.radiovalue == 'nochange') {
                    364:             alert('$alert{'authen'}');
                    365:             return;
                    366:         }
                    367:     }
                    368: END
                    369:     } else {
                    370:         $auth_checks .= (<<END);
                    371:     var foundatype=0;
                    372:     if (founduname==0) {
                    373:         alert('$alert{'username'}');
                    374:         return;
                    375:     }
                    376: 
                    377: END
                    378:         if ($authnum > 1) {
                    379:             $auth_checks .= (<<END);
                    380:     if (current.radiovalue == null || current.radiovalue == '' || current.radiovalue == 'nochange') {
                    381:         // They did not check any of the login radiobuttons.
                    382:         alert('$alert{'authen'}');
                    383:         return;
                    384:     }
                    385: END
                    386:         }
                    387:     }
                    388:     if ($mode eq 'createcourse') {
                    389:         $auth_checks .= "
                    390:     if ( (vf.autoadds[0].checked == true) &&
                    391:          (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') ) {
                    392: ";
                    393:     } elsif ($mode eq 'modifycourse') {
                    394:         $auth_checks .= "
                    395:     if (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') {
                    396: ";
                    397:     }
                    398:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
                    399:         $auth_checks .= (<<END);
                    400:         var alertmsg = '';
                    401:         switch (current.radiovalue) {
                    402:             case 'krb':
                    403:                 alertmsg = '$alert{'krb'}';
                    404:                 break;
                    405:             default:
                    406:                 alertmsg = '';
                    407:         }
                    408:         if (alertmsg != '') {
                    409:             alert(alertmsg);
                    410:             return;
                    411:         }
                    412:     }
                    413: END
                    414:     } else {
                    415:         $auth_checks .= (<<END);
                    416:     foundatype=1;
                    417:     if (current.argfield == null || current.argfield == '') {
                    418:         var alertmsg = '';
                    419:         switch (current.value) {
                    420:             case 'krb':
                    421:                 alertmsg = '$alert{'krb'}';
                    422:                 break;
                    423:             case 'loc':
                    424:             case 'fsys':
                    425:                 alertmsg = '$alert{'ipass'}';
                    426:                 break;
                    427:             case 'fsys':
                    428:                 alertmsg = '';
                    429:                 break;
                    430:             default:
                    431:                 alertmsg = '';
                    432:         }
                    433:         if (alertmsg != '') {
                    434:             alert(alertmsg);
                    435:             return;
                    436:         }
                    437:     }
                    438: END
                    439:     }
                    440:     my $section_checks;
                    441:     my $optional_checks = '';
                    442:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
                    443:         $optional_checks = (<<END);
                    444:     vf.submit();
                    445: }
                    446: END
                    447:     } else {
                    448:         $section_checks = &section_check_js();
                    449:         $optional_checks = (<<END);
                    450:     var message='';
                    451:     if (foundname==0) {
                    452:         message='$alert{'name'}';
                    453:     }
                    454:     if (foundid==0) {
                    455:         if (message!='') {
                    456:             message+='\\n';
                    457:         }
                    458:         message+='$alert{'snum'}';
                    459:     }
                    460:     if (foundsec==0) {
                    461:         if (message!='') {
                    462:             message+='\\n';
                    463:         }
                    464:     }
                    465:     if (foundemail==0) {
                    466:         if (message!='') {
                    467:             message+='\\n';
                    468:         }
                    469:         message+='$alert{'email'}';
                    470:     }
                    471:     if (message!='') {
                    472:         message+= '\\n$alert{'continue'}';
                    473:         if (confirm(message)) {
                    474:             vf.state.value='enrolling';
                    475:             vf.submit();
                    476:         }
                    477:     } else {
                    478:         vf.state.value='enrolling';
                    479:         vf.submit();
                    480:     }
                    481: }
                    482: END
                    483:     }
                    484:     my $result = $function_name;
                    485:     if ( ($mode eq 'auth') || ($mode eq 'createcourse') || ($mode eq 'modifycourse')  ) {
                    486:         $result .= $auth_checks;
                    487:     }
                    488:     $result .= $optional_checks."\n".$section_checks;
                    489:     if ( ($mode eq 'auth') || ($mode eq 'createcourse') || ($mode eq 'modifycourse')  ) {
                    490:         $result .= $authheader;
                    491:     }
                    492:     return $result;
                    493: }
                    494: ###############################################################
                    495: ###############################################################
                    496: sub upload_manager_javascript_forward_associate {
                    497:     return(<<ENDPICK);
                    498: function verify(vf,sec_caller) {
                    499:     var founduname=0;
                    500:     var foundpwd=0;
                    501:     var foundname=0;
                    502:     var foundid=0;
                    503:     var foundsec=0;
                    504:     var foundemail=0;
                    505:     var foundrole=0;
                    506:     var tw;
                    507:     for (i=0;i<=vf.nfields.value;i++) {
                    508:         tw=eval('vf.f'+i+'.selectedIndex');
                    509:         if (tw==1) { founduname=1; }
                    510:         if ((tw>=2) && (tw<=6)) { foundname=1; }
                    511:         if (tw==7) { foundid=1; }
                    512:         if (tw==8) { foundsec=1; }
                    513:         if (tw==9) { foundpwd=1; }
                    514:         if (tw==10) { foundemail=1; }
                    515:         if (tw==11) { foundrole=1; }
                    516:     }
                    517:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole);
                    518: }
                    519: 
                    520: //
                    521: // vf = this.form
                    522: // tf = column number
                    523: //
                    524: // values of nw
                    525: //
                    526: // 0 = none
                    527: // 1 = username
                    528: // 2 = names (lastname, firstnames)
                    529: // 3 = fname (firstname)
                    530: // 4 = mname (middlename)
                    531: // 5 = lname (lastname)
                    532: // 6 = gen   (generation)
                    533: // 7 = id
                    534: // 8 = section
                    535: // 9 = ipwd  (password)
                    536: // 10 = email address
                    537: // 11 = role
                    538: 
                    539: function flip(vf,tf) {
                    540:    var nw=eval('vf.f'+tf+'.selectedIndex');
                    541:    var i;
                    542:    // make sure no other columns are labeled the same as this one
                    543:    for (i=0;i<=vf.nfields.value;i++) {
                    544:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                    545:           eval('vf.f'+i+'.selectedIndex=0;')
                    546:       }
                    547:    }
                    548:    // If we set this to 'lastname, firstnames', clear out all the ones
                    549:    // set to 'fname','mname','lname','gen' (3,4,5,6) currently.
                    550:    if (nw==2) {
                    551:       for (i=0;i<=vf.nfields.value;i++) {
                    552:          if ((eval('vf.f'+i+'.selectedIndex')>=3) &&
                    553:              (eval('vf.f'+i+'.selectedIndex')<=6)) {
                    554:              eval('vf.f'+i+'.selectedIndex=0;')
                    555:          }
                    556:       }
                    557:    }
                    558:    // If we set this to one of 'fname','mname','lname','gen' (3,4,5,6),
                    559:    // clear out any that are set to 'lastname, firstnames' (2)
                    560:    if ((nw>=3) && (nw<=6)) {
                    561:       for (i=0;i<=vf.nfields.value;i++) {
                    562:          if (eval('vf.f'+i+'.selectedIndex')==2) {
                    563:              eval('vf.f'+i+'.selectedIndex=0;')
                    564:          }
                    565:       }
                    566:    }
                    567:    // If we set the password, make the password form below correspond to
                    568:    // the new value.
                    569:    if (nw==9) {
                    570:        changed_radio('int',document.studentform);
                    571:        set_auth_radio_buttons('int',document.studentform);
                    572:        vf.intarg.value='';
                    573:        vf.krbarg.value='';
                    574:        vf.locarg.value='';
                    575:    }
                    576: }
                    577: 
                    578: function clearpwd(vf) {
                    579:     var i;
                    580:     for (i=0;i<=vf.nfields.value;i++) {
                    581:         if (eval('vf.f'+i+'.selectedIndex')==9) {
                    582:             eval('vf.f'+i+'.selectedIndex=0;')
                    583:         }
                    584:     }
                    585: }
                    586: 
                    587: ENDPICK
                    588: }
                    589: 
                    590: ###############################################################
                    591: ###############################################################
                    592: sub upload_manager_javascript_reverse_associate {
                    593:     return(<<ENDPICK);
                    594: function verify(vf,sec_caller) {
                    595:     var founduname=0;
                    596:     var foundpwd=0;
                    597:     var foundname=0;
                    598:     var foundid=0;
                    599:     var foundsec=0;
                    600:     var foundrole=0;
                    601:     var tw;
                    602:     for (i=0;i<=vf.nfields.value;i++) {
                    603:         tw=eval('vf.f'+i+'.selectedIndex');
                    604:         if (i==0 && tw!=0) { founduname=1; }
                    605:         if (((i>=1) && (i<=5)) && tw!=0 ) { foundname=1; }
                    606:         if (i==6 && tw!=0) { foundid=1; }
                    607:         if (i==7 && tw!=0) { foundsec=1; }
                    608:         if (i==8 && tw!=0) { foundpwd=1; }
                    609:         if (i==9 && tw!=0) { foundrole=1; }
                    610:     }
                    611:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundrole);
                    612: }
                    613: 
                    614: function flip(vf,tf) {
                    615:    var nw=eval('vf.f'+tf+'.selectedIndex');
                    616:    var i;
                    617:    // picked the all one name field, reset the other name ones to blank
                    618:    if (tf==1 && nw!=0) {
                    619:       for (i=2;i<=5;i++) {
                    620:          eval('vf.f'+i+'.selectedIndex=0;')
                    621:       }
                    622:    }
                    623:    //picked one of the piecewise name fields, reset the all in
                    624:    //one field to blank
                    625:    if ((tf>=2) && (tf<=5) && (nw!=0)) {
                    626:       eval('vf.f1.selectedIndex=0;')
                    627:    }
                    628:    // intial password specified, pick internal authentication
                    629:    if (tf==8 && nw!=0) {
                    630:        changed_radio('int',document.studentform);
                    631:        set_auth_radio_buttons('int',document.studentform);
                    632:        vf.krbarg.value='';
                    633:        vf.intarg.value='';
                    634:        vf.locarg.value='';
                    635:    }
                    636: }
                    637: 
                    638: function clearpwd(vf) {
                    639:     var i;
                    640:     if (eval('vf.f8.selectedIndex')!=0) {
                    641:         eval('vf.f8.selectedIndex=0;')
                    642:     }
                    643: }
                    644: ENDPICK
                    645: }
                    646: 
                    647: ###############################################################
                    648: ###############################################################
                    649: sub print_upload_manager_footer {
                    650:     my ($r,$i,$keyfields,$defdom,$today,$halfyear,$context)=@_;
                    651:     my $formname;
                    652:     if ($context eq 'course') {
                    653:         $formname = 'document.studentform';
                    654:     } elsif ($context eq 'construction_space') {
                    655:         $formname = 'document.studentform';
                    656:     } elsif ($context eq 'domain') {
                    657:         $formname = 'document.studentform';
                    658:     }
                    659:     my ($krbdef,$krbdefdom) =
                    660:         &Apache::loncommon::get_kerberos_defaults($defdom);
                    661:     my %param = ( formname => $formname,
                    662:                   kerb_def_dom => $krbdefdom,
                    663:                   kerb_def_auth => $krbdef
                    664:                   );
                    665:     if (exists($env{'form.ipwd_choice'}) &&
                    666:         defined($env{'form.ipwd_choice'}) &&
                    667:         $env{'form.ipwd_choice'} ne '') {
                    668:         $param{'curr_authtype'} = 'int';
                    669:     }
                    670:     my $krbform = &Apache::loncommon::authform_kerberos(%param);
                    671:     my $intform = &Apache::loncommon::authform_internal(%param);
                    672:     my $locform = &Apache::loncommon::authform_local(%param);
                    673:     my $date_table = &date_setting_table(undef,undef,$context);
                    674: 
                    675:     my $Str = "\n".'<div class="LC_left_float">';
                    676:     $Str .= &hidden_input('nfields',$i);
                    677:     $Str .= &hidden_input('keyfields',$keyfields);
                    678:     $Str .= "<h3>".&mt('Login Type')."</h3>\n";
                    679:     if ($context eq 'domain') {
                    680:         $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>'; 
                    681:     } else {
                    682:         $Str .= "<p>\n".
                    683:             &mt('Note: this will not take effect if the user already exists').
                    684:             &Apache::loncommon::help_open_topic('Auth_Options').
                    685:             "</p>\n";
                    686:     }
                    687:     $Str .= &set_login($defdom,$krbform,$intform,$locform);
                    688:     my ($home_server_pick,$numlib) =
                    689:         &Apache::loncommon::home_server_form_item($defdom,'lcserver',
                    690:                                                   'default','hide');
                    691:     if ($numlib > 1) {
                    692:         $Str .= '<h3>'.&mt('LON-CAPA Home Server for New Users')."</h3>\n".
                    693:                 &mt('LON-CAPA domain: [_1] with home server: [_2]',$defdom,
                    694:                 $home_server_pick).'<br />';
                    695:     } else {
                    696:         $Str .= $home_server_pick;
                    697:     }
                    698:     $Str .= '<h3>'.&mt('Starting and Ending Dates').
                    699:             "</h3>\n";
                    700:     $Str .= "<p>\n".$date_table."</p>\n";
                    701:     if ($context eq 'domain') {
                    702:         $Str .= '<h3>'.&mt('Settings for assigning roles:').'</h3>'."\n".
                    703:                 &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>';
                    704:     }
                    705:     if ($context eq 'construction_space') {
                    706:         $Str .= '<h3>'.&mt('Default role')."</h3>\n".
                    707:                 &mt('Choose the role to assign to users without one specified in the uploaded file');
                    708:     } elsif ($context eq 'course') {
                    709:         $Str .= '<h3>'.&mt('Default role and section')."</h3>\n".
                    710:                 &mt('Choose the role and/or section to assign to users without one specified in the uploaded file');
                    711:     } else {
                    712:         $Str .= '<br /><br /><b>'.&mt('Default role and/or section')."</b><br />\n".
                    713:                 &mt('Role and/or section for users without one in the uploaded file.');
                    714:     }
                    715:     $Str .= '<br /><br />';
1.2       raeburn   716:     my ($options,$cb_script,$coursepick) = &default_role_selector($context,'defaultrole',1);
1.1       raeburn   717:     if ($context eq 'domain') {
                    718:         $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;
1.5       raeburn   719:     } elsif ($context eq 'construction_space') {
                    720:         $Str .= $options;
1.1       raeburn   721:     } else {
1.5       raeburn   722:         $Str .= '<table><tr><td><span class="LC_nobreak"<b>'.&mt('role').':&nbsp;</b>'.
                    723:                 $options.'</span></td><td>&nbsp;</td><td><span class="LC_nobreak">'.
                    724:                 '<b>'.&mt('section').':&nbsp;</b><input type="text" name="section" value="" size="12" /></span></td></tr></table>';
1.1       raeburn   725:     }
                    726:     if ($context eq 'course') {
                    727:         $Str .= "<h3>".&mt('Full Update')."</h3>\n".
                    728:                 '<label><input type="checkbox" name="fullup" value="yes">'.
                    729:                 ' '.&mt('Full update (also print list of users not enrolled anymore)').
                    730:                 "</label></p>\n";
                    731:     }
1.5       raeburn   732:     if ($context eq 'course' || $context eq 'domain') {
                    733:         $Str .= &forceid_change($context);
                    734:     }
1.1       raeburn   735:     $Str .= '</div><div class="LC_clear_float_footer"><br /><input type="button"'.
                    736:               'onClick="javascript:verify(this.form,this.form.csec)" '.
                    737:         'value="Update Users" />'."<br />\n";
                    738:     if ($context eq 'course') {
                    739:         $Str .= &mt('Note: for large courses, this operation may be time '.
                    740:                     'consuming');
                    741:     }
                    742:     $Str .= '</div>';
                    743:     $r->print($Str);
                    744:     return;
                    745: }
                    746: 
1.5       raeburn   747: sub forceid_change {
                    748:     my ($context) = @_;
                    749:     my $output = 
                    750:         "<h3>".&mt('ID/Student Number')."</h3>\n".
                    751:         "<p>\n".'<label><input type="checkbox" name="forceid" value="yes">'.
                    752:         &mt('Disable ID/Student Number Safeguard and Force Change '.
                    753:         'of Conflicting IDs').'</label><br />'."\n".
                    754:         &mt('(only do if you know what you are doing.)')."</br><br />\n";
                    755:     if ($context eq 'domain') {
                    756:         $output .= '<label><input type="checkbox" name="recurseid"'.
                    757:                    ' value="yes">'. 
                    758:   &mt('Update ID/Student Number in courses in which user is an Active or Future student, (if forcing change).').
                    759:                    '</label></p>'."\n";
                    760:     }
                    761:     return $output;
                    762: }
                    763: 
1.1       raeburn   764: ###############################################################
                    765: ###############################################################
                    766: sub print_upload_manager_form {
                    767:     my ($r,$context) = @_;
                    768:     my $firstLine;
                    769:     my $datatoken;
                    770:     if (!$env{'form.datatoken'}) {
                    771:         $datatoken=&Apache::loncommon::upfile_store($r);
                    772:     } else {
                    773:         $datatoken=$env{'form.datatoken'};
                    774:         &Apache::loncommon::load_tmp_file($r);
                    775:     }
                    776:     my @records=&Apache::loncommon::upfile_record_sep();
                    777:     if($env{'form.noFirstLine'}){
                    778:         $firstLine=shift(@records);
                    779:     }
                    780:     my $total=$#records;
                    781:     my $distotal=$total+1;
                    782:     my $today=time;
                    783:     my $halfyear=$today+15552000;
                    784:     #
                    785:     # Restore memorized settings
                    786:     my $col_setting_names =  { 'username_choice' => 'scalar', # column settings
                    787:                                'names_choice' => 'scalar',
                    788:                                'fname_choice' => 'scalar',
                    789:                                'mname_choice' => 'scalar',
                    790:                                'lname_choice' => 'scalar',
                    791:                                'gen_choice' => 'scalar',
                    792:                                'id_choice' => 'scalar',
                    793:                                'sec_choice' => 'scalar',
                    794:                                'ipwd_choice' => 'scalar',
                    795:                                'email_choice' => 'scalar',
                    796:                                'role_choice' => 'scalar',
                    797:                              };
                    798:     my $defdom = $env{'request.role.domain'};
                    799:     if ($context eq 'course') {
                    800:         &Apache::loncommon::restore_course_settings('enrollment_upload',
                    801:                                                     $col_setting_names);
                    802:     } else {
                    803:         &Apache::loncommon::restore_settings($context,'user_upload',
                    804:                                              $col_setting_names);
                    805:     }
                    806:     #
                    807:     # Determine kerberos parameters as appropriate
                    808:     my ($krbdef,$krbdefdom) =
                    809:         &Apache::loncommon::get_kerberos_defaults($defdom);
                    810:     #
                    811:     &print_upload_manager_header($r,$datatoken,$distotal,$krbdefdom,$context);
                    812:     my $i;
                    813:     my $keyfields;
                    814:     if ($total>=0) {
                    815:         my @field=
                    816:             (['username',&mt('Username'),     $env{'form.username_choice'}],
                    817:              ['names',&mt('Last Name, First Names'),$env{'form.names_choice'}],
                    818:              ['fname',&mt('First Name'),      $env{'form.fname_choice'}],
                    819:              ['mname',&mt('Middle Names/Initials'),$env{'form.mname_choice'}],
                    820:              ['lname',&mt('Last Name'),       $env{'form.lname_choice'}],
                    821:              ['gen',  &mt('Generation'),      $env{'form.gen_choice'}],
                    822:              ['id',   &mt('ID/Student Number'),$env{'form.id_choice'}],
                    823:              ['sec',  &mt('Section'),          $env{'form.sec_choice'}],
                    824:              ['ipwd', &mt('Initial Password'),$env{'form.ipwd_choice'}],
                    825:              ['email',&mt('E-mail Address'),   $env{'form.email_choice'}],
                    826:              ['role',&mt('Role'),             $env{'form.role_choice'}]);
                    827:         if ($env{'form.upfile_associate'} eq 'reverse') {
                    828:             &Apache::loncommon::csv_print_samples($r,\@records);
                    829:             $i=&Apache::loncommon::csv_print_select_table($r,\@records,
                    830:                                                           \@field);
                    831:             foreach (@field) {
                    832:                 $keyfields.=$_->[0].',';
                    833:             }
                    834:             chop($keyfields);
                    835:         } else {
                    836:             unshift(@field,['none','']);
                    837:             $i=&Apache::loncommon::csv_samples_select_table($r,\@records,
                    838:                                                             \@field);
                    839:             my %sone=&Apache::loncommon::record_sep($records[0]);
                    840:             $keyfields=join(',',sort(keys(%sone)));
                    841:         }
                    842:     }
                    843:     $r->print('</div>');
                    844:     &print_upload_manager_footer($r,$i,$keyfields,$defdom,$today,$halfyear,
                    845:                                  $context);
                    846: }
                    847: 
                    848: sub setup_date_selectors {
1.11    ! raeburn   849:     my ($starttime,$endtime,$mode,$nolink) = @_;
1.1       raeburn   850:     if (! defined($starttime)) {
                    851:         $starttime = time;
                    852:         unless ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
                    853:             if (exists($env{'course.'.$env{'request.course.id'}.
                    854:                             '.default_enrollment_start_date'})) {
                    855:                 $starttime = $env{'course.'.$env{'request.course.id'}.
                    856:                                   '.default_enrollment_start_date'};
                    857:             }
                    858:         }
                    859:     }
                    860:     if (! defined($endtime)) {
                    861:         $endtime = time+(6*30*24*60*60); # 6 months from now, approx
                    862:         unless ($mode eq 'createcourse') {
                    863:             if (exists($env{'course.'.$env{'request.course.id'}.
                    864:                             '.default_enrollment_end_date'})) {
                    865:                 $endtime = $env{'course.'.$env{'request.course.id'}.
                    866:                                 '.default_enrollment_end_date'};
                    867:             }
                    868:         }
                    869:     }
1.11    ! raeburn   870: 
        !           871:     my $startdateform = 
        !           872:         &Apache::lonhtmlcommon::date_setter('studentform','startdate',$starttime,
        !           873:             undef,undef,undef,undef,undef,undef,undef,$nolink);
        !           874: 
        !           875:     my $enddateform = 
        !           876:         &Apache::lonhtmlcommon::date_setter('studentform','enddate',$endtime,
        !           877:             undef,undef,undef,undef,undef,undef,undef,$nolink);
        !           878: 
1.1       raeburn   879:     if ($mode eq 'create_enrolldates') {
                    880:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    881:                                                             'startenroll',
                    882:                                                             $starttime);
                    883:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    884:                                                           'endenroll',
                    885:                                                           $endtime);
                    886:     }
                    887:     if ($mode eq 'create_defaultdates') {
                    888:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    889:                                                             'startaccess',
                    890:                                                             $starttime);
                    891:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    892:                                                           'endaccess',
                    893:                                                           $endtime);
                    894:     }
                    895:     return ($startdateform,$enddateform);
                    896: }
                    897: 
                    898: 
                    899: sub get_dates_from_form {
                    900:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate');
                    901:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate');
                    902:     if ($env{'form.no_end_date'}) {
                    903:         $enddate = 0;
                    904:     }
                    905:     return ($startdate,$enddate);
                    906: }
                    907: 
                    908: sub date_setting_table {
1.11    ! raeburn   909:     my ($starttime,$endtime,$mode,$bulkaction) = @_;
        !           910:     my $nolink;
        !           911:     if ($bulkaction) {
        !           912:         $nolink = 1;
        !           913:     }
        !           914:     my ($startform,$endform) = 
        !           915:         &setup_date_selectors($starttime,$endtime,$mode,$nolink);
1.1       raeburn   916:     my $dateDefault;
                    917:     if ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
                    918:         $dateDefault = '&nbsp;';
                    919:     } elsif ($mode ne 'construction_space' && $mode ne 'domain') {
1.11    ! raeburn   920:         if (($bulkaction eq 'reenable') || 
        !           921:             ($bulkaction eq 'activate') || 
        !           922:             ($bulkaction eq 'chgdates')) { 
        !           923:             $dateDefault = '<span class="LC_nobreak">'.
        !           924:                 '<label><input type="checkbox" name="makedatesdefault" /> '.
        !           925:                 &mt('make these dates the default for future enrollment').
        !           926:                 '</label></span>';
        !           927:         }
1.1       raeburn   928:     }
1.11    ! raeburn   929:     my $perpetual = '<span class="LC_nobreak"><label><input type="checkbox" name="no_end_date"';
1.1       raeburn   930:     if (defined($endtime) && $endtime == 0) {
                    931:         $perpetual .= ' checked';
                    932:     }
1.11    ! raeburn   933:     $perpetual.= ' /> '.&mt('no ending date').'</label></span>';
1.1       raeburn   934:     if ($mode eq 'create_enrolldates') {
                    935:         $perpetual = '&nbsp;';
                    936:     }
1.11    ! raeburn   937:     my $result = &Apache::lonhtmlcommon::start_pick_box()."\n";
        !           938:     $result .= &Apache::lonhtmlcommon::row_title(&mt('Starting Date'),
        !           939:                                                      'LC_oddrow_value')."\n".
        !           940:                $startform."\n".
        !           941:                &Apache::lonhtmlcommon::row_closure(1).
        !           942:                &Apache::lonhtmlcommon::row_title(&mt('Ending Date'), 
        !           943:                                                      'LC_oddrow_value')."\n".
        !           944:                $endform.'&nbsp;'.$perpetual.
        !           945:                &Apache::lonhtmlcommon::row_closure(1).
        !           946:                &Apache::lonhtmlcommon::end_pick_box().'<br />';
1.1       raeburn   947:     if ($dateDefault) {
                    948:         $result .=  $dateDefault.'<br />'."\n";
                    949:     }
                    950:     return $result;
                    951: }
                    952: 
                    953: sub make_dates_default {
                    954:     my ($startdate,$enddate,$context) = @_;
                    955:     my $result = '';
                    956:     if ($context eq 'course') {
                    957:         my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    958:         my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
                    959:         my $put_result = &Apache::lonnet::put('environment',
                    960:                 {'default_enrollment_start_date'=>$startdate,
                    961:                  'default_enrollment_end_date'  =>$enddate},$dom,$crs);
                    962:         if ($put_result eq 'ok') {
1.11    ! raeburn   963:             $result .= &mt('Set default start and end dates for course').
        !           964:                        '<br />'."\n";
1.1       raeburn   965:             #
                    966:             # Refresh the course environment
                    967:             &Apache::lonnet::coursedescription($env{'request.course.id'},
                    968:                                                {'freshen_cache' => 1});
                    969:         } else {
                    970:             $result .= &mt('Unable to set default dates for course').":".$put_result.
                    971:                        '<br />';
                    972:         }
                    973:     }
                    974:     return $result;
                    975: }
                    976: 
                    977: sub default_role_selector {
1.2       raeburn   978:     my ($context,$checkpriv) = @_;
1.1       raeburn   979:     my %customroles;
                    980:     my ($options,$coursepick,$cb_jscript);
                    981:     if ($context ne 'construction_space') {
                    982:         %customroles = &my_custom_roles();
                    983:     }
                    984: 
                    985:     my %lt=&Apache::lonlocal::texthash(
                    986:                     'rol'  => "Role",
                    987:                     'grs'  => "Section",
                    988:                     'exs'  => "Existing sections",
                    989:                     'new'  => "New section",
                    990:                   );
                    991:     $options = '<select name="defaultrole">'."\n".
                    992:                ' <option value="">'.&mt('Please select').'</option>'."\n"; 
                    993:     if ($context eq 'course') {
1.2       raeburn   994:         $options .= &default_course_roles($context,$checkpriv,%customroles);
1.1       raeburn   995:     } elsif ($context eq 'construction_space') {
1.2       raeburn   996:         my @roles = &construction_space_roles($checkpriv);
1.1       raeburn   997:         foreach my $role (@roles) {
                    998:            my $plrole=&Apache::lonnet::plaintext($role);
                    999:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>'."\n";
                   1000:         }
                   1001:     } elsif ($context eq 'domain') {
1.2       raeburn  1002:         my @roles = &domain_roles($checkpriv);
1.1       raeburn  1003:         foreach my $role (@roles) {
                   1004:            my $plrole=&Apache::lonnet::plaintext($role);
                   1005:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>';
                   1006:         }
                   1007:         my $courseform = &Apache::loncommon::selectcourse_link
                   1008:             ('studentform','defaultcourse','defaultdomain','defaultdesc',"$env{'request.role.domain'}",undef,'Course');
                   1009:         $cb_jscript = 
                   1010:             &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'},'defaultsec','studentform');
                   1011:         $coursepick = &Apache::loncommon::start_data_table().
                   1012:                       &Apache::loncommon::start_data_table_header_row().
                   1013:                       '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th>'.
                   1014:                       '<th>'.$lt{'grs'}.'</th>'.
                   1015:                       &Apache::loncommon::end_data_table_header_row().
                   1016:                       &Apache::loncommon::start_data_table_row()."\n".
                   1017:                       '<td><input type="text" name="defaultdesc" value="" onFocus="this.blur();opencrsbrowser('."'studentform','defcourse','defdomain','coursedesc',''".')" /></td>'."\n".
                   1018:                       '<td><select name="courserole">'."\n".
1.2       raeburn  1019:                       &default_course_roles($context,$checkpriv,%customroles)."\n".
1.1       raeburn  1020:                       '</select></td><td>'.
                   1021:                       '<table class="LC_createuser">'.
                   1022:                       '<tr class="LC_section_row"><td valign"top">'.
                   1023:                       $lt{'exs'}.'<br /><select name="defaultsec">'.
                   1024:                       ' <option value=""><--'.&mt('Pick course first').
                   1025:                       '</select></td>'.
                   1026:                       '<td>&nbsp;&nbsp;</td>'.
                   1027:                       '<td valign="top">'.$lt{'new'}.'<br />'.
                   1028:                       '<input type="text" name="newsec" value="" size="5" />'.
                   1029:                       '<input type="hidden" name="groups" value="" /></td>'.
                   1030:                       '</tr></table></td>'.
                   1031:                       &Apache::loncommon::end_data_table_row().
                   1032:                       &Apache::loncommon::end_data_table()."\n".
                   1033:                       '<input type="hidden" name="defaultcourse" value="" />'.
                   1034:                       '<input type="hidden" name="defaultdomain" value="" />';
                   1035:     }
                   1036:     $options .= '</select>';
                   1037:     return ($options,$cb_jscript,$coursepick);
                   1038: }
                   1039: 
                   1040: sub default_course_roles {
1.2       raeburn  1041:     my ($context,$checkpriv,%customroles) = @_;
1.1       raeburn  1042:     my $output;
1.2       raeburn  1043:     my @roles = &course_roles($context,$checkpriv);
1.1       raeburn  1044:     foreach my $role (@roles) {
                   1045:         my $plrole=&Apache::lonnet::plaintext($role);
                   1046:         $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
                   1047:     }
                   1048:     if (keys(%customroles) > 0) {
1.2       raeburn  1049:         my %customroles = &my_custom_roles();
1.1       raeburn  1050:         foreach my $cust (sort(keys(%customroles))) {
                   1051:             my $custrole='cr_cr_'.$env{'user.domain'}.
                   1052:                 '_'.$env{'user.name'}.'_'.$cust;
                   1053:             $output .= '  <option value="'.$custrole.'">'.$cust.'</option>';
                   1054:         }
                   1055:     }
                   1056:     return $output;
                   1057: }
                   1058: 
                   1059: sub construction_space_roles {
1.2       raeburn  1060:     my ($checkpriv) = @_;
1.1       raeburn  1061:     my @allroles = ('ca','aa');
                   1062:     my @roles;
1.2       raeburn  1063:     if ($checkpriv) {
                   1064:         foreach my $role (@allroles) {
                   1065:             if (&Apache::lonnet::allowed('c'.$role,$env{'user.domain'}.'/'.$env{'user.name'})) { 
                   1066:                 push(@roles,$role); 
                   1067:             }
1.1       raeburn  1068:         }
1.2       raeburn  1069:         return @roles;
                   1070:     } else {
                   1071:         return @allroles;
1.1       raeburn  1072:     }
                   1073: }
                   1074: 
                   1075: sub domain_roles {
1.2       raeburn  1076:     my ($checkpriv) = @_;
1.1       raeburn  1077:     my @allroles = ('dc','li','dg','au','sc');
                   1078:     my @roles;
1.2       raeburn  1079:     if ($checkpriv) {
                   1080:         foreach my $role (@allroles) {
                   1081:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
                   1082:                 push(@roles,$role);
                   1083:             }
1.1       raeburn  1084:         }
1.2       raeburn  1085:         return @roles;
                   1086:     } else {
                   1087:         return @allroles;
1.1       raeburn  1088:     }
                   1089: }
                   1090: 
                   1091: sub course_roles {
1.2       raeburn  1092:     my ($context,$checkpriv) = @_;
1.1       raeburn  1093:     my @allroles = ('st','ta','ep','in','cc');
                   1094:     my @roles;
                   1095:     if ($context eq 'domain') {
                   1096:         @roles = @allroles;
                   1097:     } elsif ($context eq 'course') {
                   1098:         if ($env{'request.course.id'}) {
1.2       raeburn  1099:             if ($checkpriv) { 
                   1100:                 foreach my $role (@allroles) {
                   1101:                     if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
                   1102:                         push(@roles,$role);
                   1103:                     } else {
                   1104:                         if ($role ne 'cc' && $env{'request.course.section'} ne '') {
                   1105:                             if (!&Apache::lonnet::allowed('c'.$role,
                   1106:                                              $env{'request.course.id'}.'/'.
                   1107:                                              $env{'request.course.section'})) {
                   1108:                                 push(@roles,$role);
                   1109:                             }
1.1       raeburn  1110:                         }
                   1111:                     }
                   1112:                 }
1.2       raeburn  1113:             } else {
                   1114:                 @roles = @allroles;
1.1       raeburn  1115:             }
                   1116:         }
                   1117:     }
                   1118:     return @roles;
                   1119: }
                   1120: 
                   1121: sub curr_role_permissions {
1.2       raeburn  1122:     my ($context,$setting,$checkpriv) = @_; 
1.1       raeburn  1123:     my @roles;
                   1124:     if ($context eq 'construction_space') {
1.2       raeburn  1125:         @roles = &construction_space_roles($checkpriv);
1.1       raeburn  1126:     } elsif ($context eq 'domain') {
                   1127:         if ($setting eq 'course') {
1.2       raeburn  1128:             @roles = &course_roles($context,$checkpriv); 
1.1       raeburn  1129:         } else {
1.2       raeburn  1130:             @roles = &domain_roles($checkpriv);
1.1       raeburn  1131:         }
                   1132:     } elsif ($context eq 'course') {
1.2       raeburn  1133:         @roles = &course_roles($context,$checkpriv);
1.1       raeburn  1134:     }
                   1135:     return @roles;
                   1136: }
                   1137: 
                   1138: # ======================================================= Existing Custom Roles
                   1139: 
                   1140: sub my_custom_roles {
                   1141:     my %returnhash=();
                   1142:     my %rolehash=&Apache::lonnet::dump('roles');
                   1143:     foreach my $key (keys %rolehash) {
                   1144:         if ($key=~/^rolesdef\_(\w+)$/) {
                   1145:             $returnhash{$1}=$1;
                   1146:         }
                   1147:     }
                   1148:     return %returnhash;
                   1149: }
                   1150: 
1.2       raeburn  1151: sub print_userlist {
                   1152:     my ($r,$mode,$permission,$context,$formname,$totcodes,$codetitles,
                   1153:         $idlist,$idlist_titles) = @_;
                   1154:     my $format = $env{'form.output'};
1.1       raeburn  1155:     if (! exists($env{'form.sortby'})) {
                   1156:         $env{'form.sortby'} = 'username';
                   1157:     }
1.2       raeburn  1158:     if ($env{'form.Status'} !~ /^(Any|Expired|Active|Future)$/) {
                   1159:         $env{'form.Status'} = 'Active';
1.1       raeburn  1160:     }
                   1161:     my $status_select = &Apache::lonhtmlcommon::StatusOptions
1.2       raeburn  1162:         ($env{'form.Status'});
1.1       raeburn  1163: 
1.2       raeburn  1164:     if ($env{'form.showrole'} eq '') {
                   1165:         $env{'form.showrole'} = 'Any';
                   1166:     }
1.1       raeburn  1167:     if (! defined($env{'form.output'}) ||
                   1168:         $env{'form.output'} !~ /^(csv|excel|html)$/ ) {
                   1169:         $env{'form.output'} = 'html';
                   1170:     }
                   1171: 
1.2       raeburn  1172:     my @statuses;
                   1173:     if ($env{'form.Status'} eq 'Any') {
                   1174:         @statuses = ('previous','active','future');
                   1175:     } elsif ($env{'form.Status'} eq 'Expired') {
                   1176:         @statuses = ('previous');
                   1177:     } elsif ($env{'form.Status'} eq 'Active') {
                   1178:         @statuses = ('active');
                   1179:     } elsif ($env{'form.Status'} eq 'Future') {
                   1180:         @statuses = ('future');
                   1181:     }
1.1       raeburn  1182: 
1.2       raeburn  1183: #    if ($context eq 'course') { 
                   1184: #        $r->print(&display_adv_courseroles());
                   1185: #    }
1.1       raeburn  1186:     #
                   1187:     # Interface output
1.2       raeburn  1188:     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n".
                   1189:               '<input type="hidden" name="action" value="'.
1.1       raeburn  1190:               $env{'form.action'}.'" />');
                   1191:     $r->print("<p>\n");
                   1192:     if ($env{'form.action'} ne 'modifystudent') {
                   1193:         my %lt=&Apache::lonlocal::texthash('csv' => "CSV",
                   1194:                                            'excel' => "Excel",
                   1195:                                            'html'  => 'HTML');
                   1196:         my $output_selector = '<select size="1" name="output" >';
                   1197:         foreach my $outputformat ('html','csv','excel') {
                   1198:             my $option = '<option value="'.$outputformat.'" ';
                   1199:             if ($outputformat eq $env{'form.output'}) {
                   1200:                 $option .= 'selected ';
                   1201:             }
                   1202:             $option .='>'.$lt{$outputformat}.'</option>';
                   1203:             $output_selector .= "\n".$option;
                   1204:         }
                   1205:         $output_selector .= '</select>';
                   1206:         $r->print('<label>'.&mt('Output Format: [_1]',$output_selector).'</label>'.('&nbsp;'x3));
                   1207:     }
1.2       raeburn  1208:     $r->print('<label>'.&mt('User Status: [_1]',$status_select).'</label>'.('&nbsp;'x3)."\n");
                   1209:     my $roleselected = '';
                   1210:     if ($env{'form.showrole'} eq 'Any') {
                   1211:        $roleselected = ' selected="selected" '; 
                   1212:     }
                   1213:     my $role_select;
                   1214:     if ($context eq 'domain') {
                   1215:         $role_select = &domain_roles_select();
                   1216:         $r->print('<label>'.&mt('Role Type: [_1]',$role_select).'</label>');
                   1217:     } else {
                   1218:         $role_select = '<select name="showrole">'."\n".
                   1219:                        '<option value="Any" '.$roleselected.'>'.
                   1220:                        &mt('Any role').'</option>';
                   1221:         my @poss_roles = &curr_role_permissions($context);
                   1222:         foreach my $role (@poss_roles) {
                   1223:             $roleselected = '';
                   1224:             if ($role eq $env{'form.showrole'}) {
                   1225:                 $roleselected = ' selected="selected" ';
                   1226:             }
                   1227:             my $plrole=&Apache::lonnet::plaintext($role);
                   1228:             $role_select .= '<option value="'.$role.'"'.$roleselected.'>'.$plrole.'</option>';
                   1229:         }
                   1230:         $roleselected = '';
                   1231:         if ($env{'form.showrole'} eq 'cr') {
                   1232:             $roleselected = ' selected="selected" ';
                   1233:         }
                   1234:         $role_select .= '<option value="cr"'.$roleselected.'>'.&mt('Custom role').'</option>'.
                   1235:                         '</select>';
                   1236:         $r->print('<label>'.&mt('Role: [_1]',$role_select).'</label>');
                   1237:     }
                   1238:     if (!(($context eq 'domain') && ($env{'form.roletype'} eq 'course'))) {
                   1239:         $r->print(&list_submit_button(&mt('Update Display'))."\n</p>\n");
                   1240:     }
                   1241:     my ($indexhash,$keylist) = &make_keylist_array();
                   1242:     my (%userlist,%userinfo);
1.3       raeburn  1243:     if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
                   1244:         my $courseform =
                   1245:             &Apache::lonhtmlcommon::course_selection($formname,$totcodes,
                   1246:                                          $codetitles,$idlist,$idlist_titles);
                   1247:         $r->print('<p>'.&Apache::lonhtmlcommon::start_pick_box()."\n".
                   1248:                   &Apache::lonhtmlcommon::start_pick_box()."\n".
                   1249:                   &Apache::lonhtmlcommon::row_title(&mt('Select Course(s)'),
                   1250:                                                     'LC_oddrow_value')."\n".
                   1251:                   $courseform."\n".
                   1252:                   &Apache::lonhtmlcommon::row_closure(1).
                   1253:                   &Apache::lonhtmlcommon::end_pick_box().'</p>'.
                   1254:                   '<p>'.&list_submit_button(&mt('Update Display')).
                   1255:                   "\n</p>\n");
1.11    ! raeburn  1256:         if ($env{'form.coursepick'}) {
        !          1257:             $r->print('<hr />'.&mt('Searching').' ...<br />&nbsp;<br />');
        !          1258:         }
        !          1259:     } else {
        !          1260:         $r->print('<hr />'.&mt('Searching').' ...<br />&nbsp;<br />');
1.3       raeburn  1261:     }
                   1262:     $r->rflush();
1.1       raeburn  1263:     if ($context eq 'course') {
1.3       raeburn  1264:         my $classlist = &Apache::loncoursedata::get_classlist();
                   1265:         my $secidx = &Apache::loncoursedata::CL_SECTION();
                   1266:         foreach my $student (keys(%{$classlist})) {
                   1267:             if (exists($permission->{'view_section'})) {
                   1268:                 if ($classlist->{$student}[$secidx] ne $permission->{'view_section'}) {
                   1269:                     next;
                   1270:                 } else {
                   1271:                     $userlist{$student} = $classlist->{$student};
1.1       raeburn  1272:                 }
1.3       raeburn  1273:             } else {
                   1274:                 $userlist{$student} = $classlist->{$student};
1.1       raeburn  1275:             }
                   1276:         }
1.2       raeburn  1277:         my $cid =$env{'request.course.id'};
                   1278:         my $cdom=$env{'course.'.$cid.'.domain'};
                   1279:         my $cnum=$env{'course.'.$cid.'.num'};
                   1280:         my $showroles;
                   1281:         if ($env{'form.showrole'} ne 'Any') {
                   1282:             $showroles = [$env{'form.showrole'}];
1.1       raeburn  1283:         } else {
1.2       raeburn  1284:             $showroles = undef;
                   1285:         }
                   1286:         my %advrolehash = &Apache::lonnet::get_my_roles($cnum,$cdom,undef,
                   1287:                                                         \@statuses,$showroles);
                   1288:         &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
1.11    ! raeburn  1289:                          \%advrolehash,$permission);
1.2       raeburn  1290:     } else {
                   1291:         my (%cstr_roles,%dom_roles);
                   1292:         if ($context eq 'construction_space') {
                   1293:             # List co-authors and assistant co-authors
                   1294:             my @possroles = ('ca','aa');
                   1295:             %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
                   1296:                                               \@statuses,\@possroles);
                   1297:             &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
1.11    ! raeburn  1298:                              \%cstr_roles,$permission);
1.2       raeburn  1299:         } elsif ($context eq 'domain') {
                   1300:             if ($env{'form.roletype'} eq 'domain') {
                   1301:                 %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'});
                   1302:                 foreach my $key (keys(%dom_roles)) {
                   1303:                     if (ref($dom_roles{$key}) eq 'HASH') {
                   1304:                         &gather_userinfo($context,$format,\%userlist,$indexhash,
1.11    ! raeburn  1305:                                          \%userinfo,$dom_roles{$key},$permission);
1.2       raeburn  1306:                     }
                   1307:                 }
                   1308:             } elsif ($env{'form.roletype'} eq 'construction_space') {
                   1309:                 my %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'},['au']);
                   1310:                 my %coauthors;
                   1311:                 foreach my $key (keys(%dom_roles)) {
                   1312:                     if (ref($dom_roles{$key}) eq 'HASH') {
                   1313:                         if ($env{'form.showrole'} eq 'au') {
                   1314:                             &gather_userinfo($context,$format,\%userlist,$indexhash,
1.11    ! raeburn  1315:                                              \%userinfo,$dom_roles{$key},$permission);
1.2       raeburn  1316:                         } else {
                   1317:                             my @possroles;
                   1318:                             if ($env{'form.showrole'} eq 'Any') {
                   1319:                                 @possroles = ('ca','aa');
                   1320:                             } else {
                   1321:                                 @possroles = ($env{'form.showrole'}); 
                   1322:                             }
                   1323:                             foreach my $author (sort(keys(%{$dom_roles{$key}}))) {
                   1324:                                 my ($role,$authorname,$authordom) = split(/:/,$author);
                   1325:                                 my $extent = '/'.$authordom.'/'.$authorname;
                   1326:                                 %{$coauthors{$extent}} =
                   1327:                                     &Apache::lonnet::get_my_roles($authorname,
                   1328:                                        $authordom,undef,\@statuses,\@possroles);
                   1329:                             }
                   1330:                             &gather_userinfo($context,$format,\%userlist,
1.11    ! raeburn  1331:                                      $indexhash,\%userinfo,\%coauthors,$permission);
1.2       raeburn  1332:                         }
                   1333:                     }
                   1334:                 }
                   1335:             } elsif ($env{'form.roletype'} eq 'course') {
                   1336:                 if ($env{'form.coursepick'}) {
                   1337:                     my %courses = &process_coursepick();
                   1338:                     my %allusers; 
                   1339:                     foreach my $cid (keys(%courses)) {
                   1340:                         my %coursehash =
                   1341:                             &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
                   1342:                         my $cdom = $coursehash{'domain'};
                   1343:                         my $cnum = $coursehash{'num'};
1.11    ! raeburn  1344:                         next if ($cnum eq '' || $cdom eq '');
1.2       raeburn  1345:                         my $cdesc = $coursehash{'description'};
                   1346:                         my (@roles,@sections,%access,%users,%userdata,
1.6       albertel 1347:                             %statushash);
1.2       raeburn  1348:                         if ($env{'form.showrole'} eq 'Any') {
                   1349:                             @roles = &course_roles($context);
1.5       raeburn  1350:                             unshift(@roles,'cr');
1.2       raeburn  1351:                         } else {
                   1352:                             @roles = ($env{'form.showrole'});
                   1353:                         }
                   1354:                         foreach my $role (@roles) {
                   1355:                             %{$users{$role}} = ();
                   1356:                         }
                   1357:                         foreach my $type (@statuses) {
                   1358:                             $access{$type} = $type;
                   1359:                         }
                   1360:                         &Apache::loncommon::get_course_users($cdom,$cnum,\%access,\@roles,\@sections,\%users,\%userdata,\%statushash);
                   1361:                         foreach my $user (keys(%userdata)) {
                   1362:                             next if (ref($userinfo{$user}) eq 'HASH');
                   1363:                             foreach my $item ('fullname','id') {
                   1364:                                 $userinfo{$user}{$item} = $userdata{$user}[$indexhash->{$item}];
                   1365:                             }
                   1366:                         }
                   1367:                         foreach my $role (keys(%users)) {
                   1368:                             foreach my $user (keys(%{$users{$role}})) {
                   1369:                                 my $uniqid = $user.':'.$role;
                   1370:                                 $allusers{$uniqid}{$cid} = { desc => $cdesc,
                   1371:                                                              secs  => $statushash{$user}{$role},
                   1372:                                                            };
                   1373:                             }
                   1374:                         }
                   1375:                     }
                   1376:                     &gather_userinfo($context,$format,\%userlist,$indexhash,
1.11    ! raeburn  1377:                                      \%userinfo,\%allusers,$permission);
1.2       raeburn  1378:                 } else {
1.10      raeburn  1379:                     $r->print('<input type="hidden" name="phase" value="'.
                   1380:                               $env{'form.phase'}.'" /></form>');
1.2       raeburn  1381:                     return;
                   1382:                 }
1.1       raeburn  1383:             }
                   1384:         }
1.3       raeburn  1385:     }
                   1386:     if (keys(%userlist) == 0) {
                   1387:         if ($context eq 'construction_space') {
                   1388:             $r->print(&mt('There are no co-authors to display.')."\n");
                   1389:         } elsif ($context eq 'domain') {
                   1390:             if ($env{'form.roletype'} eq 'domain') {
                   1391:                 $r->print(&mt('There are no users with domain roles to display.')."\n");
                   1392:             } elsif ($env{'form.roletype'} eq 'construction_space') {
                   1393:                 $r->print(&mt('There are no authors or co-authors to display.')."\n");
                   1394:             } elsif ($env{'form.roletype'} eq 'course') {
                   1395:                 $r->print(&mt('There are no course users to display')."\n"); 
1.2       raeburn  1396:             }
1.3       raeburn  1397:         } elsif ($context eq 'course') {
                   1398:             $r->print(&mt('There are no course users to display.')."\n");
                   1399:         }
                   1400:     } else {
                   1401:         # Print out the available choices
1.4       raeburn  1402:         my $usercount;
1.3       raeburn  1403:         if ($env{'form.action'} eq 'modifystudent') {
1.10      raeburn  1404:             ($usercount) = &show_users_list($r,$context,'view',$permission,
1.4       raeburn  1405:                                  $env{'form.Status'},\%userlist,$keylist);
1.1       raeburn  1406:         } else {
1.4       raeburn  1407:             ($usercount) = &show_users_list($r,$context,$env{'form.output'},
1.10      raeburn  1408:                                $permission,$env{'form.Status'},\%userlist,$keylist);
1.4       raeburn  1409:         }
                   1410:         if (!$usercount) {
                   1411:             $r->print('<br />'.&mt('There are no users matching the search criteria.')); 
1.2       raeburn  1412:         }
                   1413:     }
1.10      raeburn  1414:     $r->print('<input type="hidden" name="phase" value="'.
                   1415:               $env{'form.phase'}.'" /></form>');
1.2       raeburn  1416: }
                   1417: 
                   1418: sub list_submit_button {
                   1419:     my ($text) = @_;
1.11    ! raeburn  1420:     return '<input type="button" name="updatedisplay" value="'.$text.'" onclick="javascript:display_update()" />';
1.2       raeburn  1421: }
                   1422: 
                   1423: sub gather_userinfo {
1.11    ! raeburn  1424:     my ($context,$format,$userlist,$indexhash,$userinfo,$rolehash,$permission) = @_;
1.2       raeburn  1425:     foreach my $item (keys(%{$rolehash})) {
                   1426:         @{$userlist->{$item}} = ();
                   1427:         my %userdata;
                   1428:         if ($context eq 'construction_space' || $context eq 'course') { 
                   1429:             ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
                   1430:                 split(/:/,$item);
                   1431:             ($userdata{'start'},$userdata{'end'})=split(/:/,$rolehash->{$item});
                   1432:             &build_user_record(\%userdata,$userinfo,$indexhash,$item,$userlist);
                   1433:         } elsif ($context eq 'domain') {
                   1434:             if ($env{'form.roletype'} eq 'domain') {
                   1435:                 ($userdata{'role'},$userdata{'username'},$userdata{'domain'}) =
                   1436:                     split(/:/,$item);
                   1437:                 ($userdata{'end'},$userdata{'start'})=split(/:/,$rolehash->{$item});
                   1438:                 &build_user_record(\%userdata,$userinfo,$indexhash,$item,$userlist);
                   1439:             } elsif ($env{'form.roletype'} eq 'construction_space') {
                   1440:                 if (ref($rolehash->{$item}) eq 'HASH') {
                   1441:                     $userdata{'extent'} = $item;
                   1442:                     foreach my $key (keys(%{$rolehash->{$item}})) {
                   1443:                         ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =  split(/:/,$key);
                   1444:                         ($userdata{'start'},$userdata{'end'}) = 
                   1445:                             split(/:/,$rolehash->{$item}{$key});
                   1446:                         my $uniqid = $key.':'.$item;
                   1447:                         &build_user_record(\%userdata,$userinfo,$indexhash,$uniqid,$userlist);
                   1448:                     }
                   1449:                 }
                   1450:             } elsif ($env{'form.roletype'} eq 'course') {
                   1451:                 ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
                   1452:                     split(/:/,$item);
                   1453:                 if (ref($rolehash->{$item}) eq 'HASH') {
1.11    ! raeburn  1454:                     my $numcids = keys(%{$rolehash->{$item}});
1.2       raeburn  1455:                     foreach my $cid (sort(keys(%{$rolehash->{$item}}))) {
                   1456:                         if (ref($rolehash->{$item}{$cid}) eq 'HASH') {
                   1457:                             my $spanstart = '';
                   1458:                             my $spanend = '; ';
                   1459:                             my $space = ', ';
                   1460:                             if ($format eq 'html' || $format eq 'view') {
                   1461:                                 $spanstart = '<span class="LC_nobreak">';
1.11    ! raeburn  1462:                                 if ($permission->{'cusr'}) {
        !          1463:                                     if ($numcids > 1) {
        !          1464:                                         $spanstart .= '<input type="radio" name="'.$item.'" value="'.$cid.'" &nbsp; />';
        !          1465:                                     } else {
        !          1466:                                         $spanstart .= '<input type="hidden" name="'.$item.'" value="'.$cid.'" &nbsp; />';
        !          1467:                                     }
        !          1468:                                 }
1.2       raeburn  1469:                                 $spanend = '</span><br />';
                   1470:                                 $space = ',&nbsp;';
                   1471:                             }
                   1472:                             $userdata{'extent'} .= $spanstart.
                   1473:                                     $rolehash->{$item}{$cid}{'desc'}.$space;
                   1474:                             if (ref($rolehash->{$item}{$cid}{'secs'}) eq 'HASH') { 
                   1475:                                 foreach my $sec (sort(keys(%{$rolehash->{$item}{$cid}{'secs'}}))) {
                   1476:                                     $userdata{'extent'} .= $sec.$space.$rolehash->{$item}{$cid}{'secs'}{$sec}.$spanend;
                   1477:                                 }
                   1478:                             }
                   1479:                         }
                   1480:                     }
                   1481:                 }
                   1482:                 &build_user_record(\%userdata,$userinfo,$indexhash,$item,$userlist);
                   1483:             }
                   1484:         }
                   1485:     }
                   1486:     return;
                   1487: }
                   1488: 
                   1489: sub build_user_record {
                   1490:     my ($userdata,$userinfo,$indexhash,$record_key,$userlist) = @_;
1.11    ! raeburn  1491:     next if ($userdata->{'start'} eq '-1' && $userdata->{'end'} eq '-1');
1.2       raeburn  1492:     &process_date_info($userdata);
                   1493:     my $username = $userdata->{'username'};
                   1494:     my $domain = $userdata->{'domain'};
                   1495:     if (ref($userinfo->{$username.':'.$domain}) eq 'HASH') {
                   1496:         $userdata->{'fullname'} =
                   1497:         $userinfo->{$username.':'.$domain}{'fullname'};
                   1498:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
                   1499:     } else {
                   1500:         &aggregate_user_info($domain,$username,$userinfo);
                   1501:         $userdata->{'fullname'} = $userinfo->{$username.':'.$domain}{'fullname'};
                   1502:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
                   1503:     }
                   1504:     foreach my $key (keys(%{$indexhash})) {
                   1505:         if (defined($userdata->{$key})) {
                   1506:             $userlist->{$record_key}[$indexhash->{$key}] = $userdata->{$key};
                   1507:         }
                   1508:     }
                   1509:     return;
                   1510: }
                   1511: 
                   1512: sub courses_selector {
                   1513:     my ($cdom,$formname) = @_;
                   1514:     my %coursecodes = ();
                   1515:     my %codes = ();
                   1516:     my @codetitles = ();
                   1517:     my %cat_titles = ();
                   1518:     my %cat_order = ();
                   1519:     my %idlist = ();
                   1520:     my %idnums = ();
                   1521:     my %idlist_titles = ();
                   1522:     my $caller = 'global';
                   1523:     my $format_reply;
                   1524:     my $jscript = '';
                   1525: 
1.7       albertel 1526:     my $totcodes = 0;
                   1527:     $totcodes =
1.2       raeburn  1528:         &Apache::courseclassifier::retrieve_instcodes(\%coursecodes,
                   1529:                                                       $cdom,$totcodes);
                   1530:     if ($totcodes > 0) {
                   1531:         $format_reply =
                   1532:              &Apache::lonnet::auto_instcode_format($caller,$cdom,\%coursecodes,
                   1533:                                 \%codes,\@codetitles,\%cat_titles,\%cat_order);
                   1534:         if ($format_reply eq 'ok') {
                   1535:             my $numtypes = @codetitles;
                   1536:             &Apache::courseclassifier::build_code_selections(\%codes,\@codetitles,\%cat_titles,\%cat_order,\%idlist,\%idnums,\%idlist_titles);
                   1537:             my ($scripttext,$longtitles) = &Apache::courseclassifier::javascript_definitions(\@codetitles,\%idlist,\%idlist_titles,\%idnums,\%cat_titles);
                   1538:             my $longtitles_str = join('","',@{$longtitles});
                   1539:             my $allidlist = $idlist{$codetitles[0]};
                   1540:             $jscript .= &Apache::courseclassifier::courseset_js_start($formname,$longtitles_str,$allidlist);
                   1541:             $jscript .= $scripttext;
                   1542:             $jscript .= &Apache::courseclassifier::javascript_code_selections($formname,@codetitles);
                   1543:         }
                   1544:     }
                   1545:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($cdom);
                   1546: 
                   1547:     my %elements = (
                   1548:                      Year => 'selectbox',
                   1549:                      coursepick => 'radio',
                   1550:                      coursetotal => 'text',
                   1551:                      courselist => 'text',
                   1552:                    );
                   1553:     $jscript .= &Apache::lonhtmlcommon::set_form_elements(\%elements);
                   1554:     if ($env{'form.coursepick'} eq 'category') {
                   1555:         $jscript .= qq|
                   1556: function setCourseCat(formname) {
                   1557:     if (formname.Year.options[formname.Year.selectedIndex].value == -1) {
                   1558:         return;
                   1559:     }
                   1560:     courseSet('Year');
                   1561:     for (var j=0; j<formname.Semester.length; j++) {
                   1562:         if (formname.Semester.options[j].value == "$env{'form.Semester'}") {
                   1563:             formname.Semester.options[j].selected = true;
                   1564:         }
                   1565:     }
                   1566:     if (formname.Semester.options[formname.Semester.selectedIndex].value == -1) {
                   1567:         return;
                   1568:     }
                   1569:     courseSet('Semester');
                   1570:     for (var j=0; j<formname.Department.length; j++) {
                   1571:         if (formname.Department.options[j].value == "$env{'form.Department'}") {            formname.Department.options[j].selected = true;
                   1572:         }
                   1573:     }
                   1574:     if (formname.Department.options[formname.Department.selectedIndex].value == -1) {
                   1575:         return;
                   1576:     }
                   1577:     courseSet('Department');
                   1578:     for (var j=0; j<formname.Number.length; j++) {
                   1579:         if (formname.Number.options[j].value == "$env{'form.Number'}") {
                   1580:             formname.Number.options[j].selected = true;
                   1581:         }
                   1582:     }
                   1583: }
                   1584: |;
                   1585:     }
                   1586:     return ($cb_jscript,$jscript,$totcodes,\@codetitles,\%idlist,
                   1587:             \%idlist_titles);
                   1588: }
                   1589: 
                   1590: sub course_selector_loadcode {
                   1591:     my ($formname) = @_;
                   1592:     my $loadcode;
                   1593:     if ($env{'form.coursepick'} ne '') {
                   1594:         $loadcode = 'javascript:setFormElements(document.'.$formname.')';
                   1595:         if ($env{'form.coursepick'} eq 'category') {
                   1596:             $loadcode .= ';javascript:setCourseCat(document.'.$formname.')';
                   1597:         }
                   1598:     }
                   1599:     return $loadcode;
                   1600: }
                   1601: 
                   1602: sub process_coursepick {
                   1603:     my $coursefilter = $env{'form.coursepick'};
                   1604:     my $cdom = $env{'request.role.domain'};
                   1605:     my %courses;
                   1606:     if ($coursefilter eq 'all') {
                   1607:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.','.','.','.',
                   1608:                                                  undef,undef,'Course');
                   1609:     } elsif ($coursefilter eq 'category') {
                   1610:         my $instcode = &instcode_from_coursefilter();
                   1611:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.',$instcode,'.','.',
                   1612:                                                  undef,undef,'Course');
                   1613:     } elsif ($coursefilter eq 'specific') {
                   1614:         if ($env{'form.coursetotal'} > 1) {
                   1615:             my @course_ids = split(/&&/,$env{'form.courselist'});
                   1616:             foreach my $cid (@course_ids) {
                   1617:                 $courses{$cid} = '';
1.1       raeburn  1618:             }
1.2       raeburn  1619:         } else {
                   1620:             $courses{$env{'form.courselist'}} = '';
1.1       raeburn  1621:         }
1.2       raeburn  1622:     }
                   1623:     return %courses;
                   1624: }
                   1625: 
                   1626: sub instcode_from_coursefilter {
                   1627:     my $instcode = '';
                   1628:     my @cats = ('Semester','Year','Department','Number');
                   1629:     foreach my $category (@cats) {
                   1630:         if (defined($env{'form.'.$category})) {
                   1631:             unless ($env{'form.'.$category} eq '-1') {
                   1632:                 $instcode .= $env{'form.'.$category};
                   1633:            }
                   1634:         }
                   1635:     }
                   1636:     if ($instcode eq '') {
                   1637:         $instcode = '.';
                   1638:     }
                   1639:     return $instcode;
                   1640: }
                   1641: 
                   1642: sub display_adv_courseroles {
                   1643:     my $output;
                   1644:     #
                   1645:     # List course personnel
                   1646:     my %coursepersonnel = 
                   1647:        &Apache::lonnet::get_course_adv_roles($env{'request.course.id'});
                   1648:     #
                   1649:     $output = '<br />'.&Apache::loncommon::start_data_table();
                   1650:     foreach my $role (sort(keys(%coursepersonnel))) {
                   1651:         next if ($role =~ /^\s*$/);
                   1652:         $output .= &Apache::loncommon::start_data_table_row().
                   1653:                   '<td>'.$role.'</td><td>';
                   1654:         foreach my $user (split(',',$coursepersonnel{$role})) {
                   1655:             my ($puname,$pudom)=split(':',$user);
                   1656:             $output .= ' '.&Apache::loncommon::aboutmewrapper(
                   1657:                        &Apache::loncommon::plainname($puname,$pudom),
                   1658:                        $puname,$pudom);
                   1659:         }
                   1660:         $output .= '</td>'.&Apache::loncommon::end_data_table_row();
                   1661:     }
                   1662:     $output .= &Apache::loncommon::end_data_table();
                   1663: }
                   1664: 
                   1665: sub make_keylist_array {
                   1666:     my ($index,$keylist);
                   1667:     $index->{'domain'} = &Apache::loncoursedata::CL_SDOM();
                   1668:     $index->{'username'} = &Apache::loncoursedata::CL_SNAME();
                   1669:     $index->{'end'} = &Apache::loncoursedata::CL_END();
                   1670:     $index->{'start'} = &Apache::loncoursedata::CL_START();
                   1671:     $index->{'id'} = &Apache::loncoursedata::CL_ID();
                   1672:     $index->{'section'} = &Apache::loncoursedata::CL_SECTION();
                   1673:     $index->{'fullname'} = &Apache::loncoursedata::CL_FULLNAME();
                   1674:     $index->{'status'} = &Apache::loncoursedata::CL_STATUS();
                   1675:     $index->{'type'} = &Apache::loncoursedata::CL_TYPE();
                   1676:     $index->{'lockedtype'} = &Apache::loncoursedata::CL_LOCKEDTYPE();
                   1677:     $index->{'groups'} = &Apache::loncoursedata::CL_GROUP();
                   1678:     $index->{'email'} = &Apache::loncoursedata::CL_PERMANENTEMAIL();
                   1679:     $index->{'role'} = &Apache::loncoursedata::CL_ROLE();
                   1680:     $index->{'extent'} = &Apache::loncoursedata::CL_EXTENT();
                   1681:     foreach my $key (keys(%{$index})) {
                   1682:         $keylist->[$index->{$key}] = $key;
                   1683:     }
                   1684:     return ($index,$keylist);
                   1685: }
                   1686: 
                   1687: sub aggregate_user_info {
                   1688:     my ($udom,$uname,$userinfo) = @_;
                   1689:     my %info=&Apache::lonnet::get('environment',
                   1690:                                   ['firstname','middlename',
                   1691:                                    'lastname','generation','id'],
                   1692:                                    $udom,$uname);
                   1693:     my ($tmp) = keys(%info);
                   1694:     my ($fullname,$id);
                   1695:     if ($tmp =~/^(con_lost|error|no_such_host)/i) {
                   1696:         $fullname = 'not available';
                   1697:         $id = 'not available';
                   1698:         &Apache::lonnet::logthis('unable to retrieve environment '.
                   1699:                                  'for '.$uname.':'.$udom);
1.1       raeburn  1700:     } else {
1.2       raeburn  1701:         $fullname = &Apache::lonnet::format_name(@info{qw/firstname middlename lastname generation/},'lastname');
                   1702:         $id = $info{'id'};
                   1703:     }
                   1704:     $userinfo->{$uname.':'.$udom} = { 
                   1705:                                       fullname => $fullname,
                   1706:                                       id       => $id,
                   1707:                                     };
                   1708:     return;
                   1709: }
1.1       raeburn  1710: 
1.2       raeburn  1711: sub process_date_info {
                   1712:     my ($userdata) = @_;
                   1713:     my $now = time;
                   1714:     $userdata->{'status'} = 'Active';
                   1715:     if ($userdata->{'start'} > 0) {
                   1716:         if ($now < $userdata->{'start'}) {
                   1717:             $userdata->{'status'} = 'Future';
                   1718:         }
1.1       raeburn  1719:     }
1.2       raeburn  1720:     if ($userdata->{'end'} > 0) {
                   1721:         if ($now > $userdata->{'end'}) {
                   1722:             $userdata->{'status'} = 'Expired';
                   1723:         }
                   1724:     }
                   1725:     return;
1.1       raeburn  1726: }
                   1727: 
                   1728: sub show_users_list {
1.10      raeburn  1729:     my ($r,$context,$mode,$permission,$statusmode,$userlist,$keylist)=@_;
1.1       raeburn  1730:     #
                   1731:     # Variables for excel output
                   1732:     my ($excel_workbook, $excel_sheet, $excel_filename,$row,$format);
                   1733:     #
                   1734:     # Variables for csv output
                   1735:     my ($CSVfile,$CSVfilename);
                   1736:     #
                   1737:     my $sortby = $env{'form.sortby'};
1.3       raeburn  1738:     my @sortable = ('username','domain','id','fullname','start','end','email','role');
1.2       raeburn  1739:     if ($context eq 'course') {
1.3       raeburn  1740:         push(@sortable,('section','groups','type'));
1.2       raeburn  1741:     } else {
1.3       raeburn  1742:         push(@sortable,'extent');
                   1743:     }
                   1744:     if (!grep(/^\Q$sortby\E$/,@sortable)) {
                   1745:         $sortby = 'username';
1.1       raeburn  1746:     }
1.11    ! raeburn  1747:     my $setting = $env{'form.roleaction'};
1.2       raeburn  1748:     my ($cid,$cdom,$cnum,$classgroups,$displayphotos,$displayclickers);
1.1       raeburn  1749:     if ($context eq 'course') {
                   1750:         $cid=$env{'request.course.id'};
                   1751:         $cdom = $env{'course.'.$cid.'.domain'};
                   1752:         $cnum = $env{'course.'.$cid.'.num'};
1.2       raeburn  1753:         ($classgroups) = &Apache::loncoursedata::get_group_memberships(
                   1754:                                      $userlist,$keylist,$cdom,$cnum);
1.1       raeburn  1755:         if (! exists($env{'form.displayphotos'})) {
                   1756:             $env{'form.displayphotos'} = 'off';
                   1757:         }
                   1758:         $displayphotos = $env{'form.displayphotos'};
                   1759:         if (! exists($env{'form.displayclickers'})) {
                   1760:             $env{'form.displayclickers'} = 'off';
                   1761:         }
                   1762:         $displayclickers = $env{'form.displayclickers'};
                   1763:         if ($env{'course.'.$cid.'.internal.showphoto'}) {
                   1764:             $r->print('
                   1765: <script type="text/javascript">
                   1766: function photowindow(photolink) {
                   1767:     var title = "Photo_Viewer";
                   1768:     var options = "scrollbars=1,resizable=1,menubar=0";
                   1769:     options += ",width=240,height=240";
                   1770:     stdeditbrowser = open(photolink,title,options,"1");
                   1771:     stdeditbrowser.focus();
                   1772: }
                   1773: </script>
                   1774:            ');
                   1775:         }
                   1776:         $r->print(<<END);
                   1777: <input type="hidden" name="displayphotos" value="$displayphotos" />
                   1778: <input type="hidden" name="displayclickers" value="$displayclickers" />
                   1779: END
                   1780:     }
                   1781:     unless ($mode eq 'autoenroll') {
1.11    ! raeburn  1782:         my $check_uncheck_js = &Apache::loncommon::check_uncheck_jscript();
        !          1783:         my $alert = &mt("You must select at least one user by checking a user's 'Select' checkbox");
        !          1784:         my $singconfirm = &mt(' for a single user');
        !          1785:         my $multconfirm = &mt(' for multiple users');
        !          1786:         my $date_sec_selector = &date_section_javascript($context,$setting,$statusmode); 
1.1       raeburn  1787:         $r->print(<<END);
1.10      raeburn  1788: 
                   1789: <script type="text/javascript" language="Javascript">
1.11    ! raeburn  1790: $check_uncheck_js
        !          1791: 
        !          1792: function verify_action (field) {
        !          1793:     var numchecked = 0;
        !          1794:     var singconf = '$singconfirm';
        !          1795:     var multconf = '$multconfirm';
        !          1796:     if (field.length > 0) {
        !          1797:         for (i = 0; i < field.length; i++) {
        !          1798:             if (field[i].checked == true) {
        !          1799:                numchecked ++;
        !          1800:             }
        !          1801:         }
        !          1802:     } else {
        !          1803:         if (field.checked == true) {
        !          1804:             numchecked ++;
        !          1805:         }
        !          1806:     }
        !          1807:     if (numchecked == 0) {
        !          1808:         alert("$alert");
        !          1809:     } 
        !          1810:     else {
        !          1811:         var message = document.studentform.bulkaction[document.studentform.bulkaction.selectedIndex].text;
        !          1812:         if (numchecked == 1) { 
        !          1813:             message += singconf;
        !          1814:         } 
        !          1815:         else {
        !          1816:             message += multconf; 
        !          1817:         }
        !          1818:         if (confirm(message)) {
        !          1819:             document.studentform.phase.value = 'bulkchange';
        !          1820:             document.studentform.submit();
        !          1821:         }
        !          1822:     }
        !          1823: }
1.10      raeburn  1824: 
                   1825: function username_display_launch(username,domain) {
                   1826:     var target;
                   1827:     for (var i=0; i<document.studentform.usernamelink.length; i++) {
                   1828:         if (document.studentform.usernamelink[i].checked) {
                   1829:             target = document.studentform.usernamelink[i].value;
                   1830:         }
                   1831:     }
                   1832:     if (target == 'modify') {
                   1833:         document.studentform.srchterm.value=username;
                   1834:         document.studentform.srchdomain.value=domain;
                   1835:         document.studentform.phase.value='get_user_info';
                   1836:         document.studentform.action.value = 'singleuser';
                   1837:         document.studentform.submit();
                   1838:     }
                   1839:     else {
                   1840:         document.location.href = '/adm/'+domain+'/'+username+'/aboutme';
                   1841:     }
                   1842: }
                   1843: </script>
1.11    ! raeburn  1844: $date_sec_selector
1.1       raeburn  1845: <input type="hidden" name="state" value="$env{'form.state'}" />
                   1846: END
                   1847:     }
                   1848:     $r->print(<<END);
                   1849: <input type="hidden" name="sortby" value="$sortby" />
                   1850: END
                   1851: 
                   1852:     my %lt=&Apache::lonlocal::texthash(
                   1853:                        'username'   => "username",
                   1854:                        'domain'     => "domain",
                   1855:                        'id'         => 'ID',
                   1856:                        'fullname'   => "name",
                   1857:                        'section'    => "section",
                   1858:                        'groups'     => "active groups",
                   1859:                        'start'      => "start date",
                   1860:                        'end'        => "end date",
                   1861:                        'status'     => "status",
1.2       raeburn  1862:                        'role'       => "role",
1.1       raeburn  1863:                        'type'       => "enroll type/action",
                   1864:                        'email'      => "email address",
                   1865:                        'clicker'    => "clicker id",
                   1866:                        'photo'      => "photo",
1.2       raeburn  1867:                        'extent'     => "extent",
1.11    ! raeburn  1868:                        'pr'         => "Proceed",
        !          1869:                        'ca'         => "check all",
        !          1870:                        'ua'         => "uncheck all",
        !          1871:                        'ac'         => "Action to take for selected users",
1.10      raeburn  1872:                        'link'       => "Behavior of username links",
                   1873:                        'aboutme'    => "Display a user's personal page",
                   1874:                        'modify'     => "Modify a user's information",
1.1       raeburn  1875:                       );
1.2       raeburn  1876:     if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
                   1877:         $lt{'extent'} = &mt('Course(s): description, section(s), status');
                   1878:     } elsif ($context eq 'construction_space') {
                   1879:         $lt{'extent'} = &mt('Author'); 
                   1880:     }
1.1       raeburn  1881:     my @cols = ('username','domain','id','fullname');
                   1882:     if ($context eq 'course') {
                   1883:         push(@cols,'section');
                   1884:     }
1.2       raeburn  1885:     if (!($context eq 'domain' && $env{'form.roletype'} eq 'course')) { 
                   1886:         push(@cols,('start','end'));
                   1887:     }
1.3       raeburn  1888:     if ($env{'form.showrole'} eq 'Any' || $env{'form.showrole'} eq 'cr') {
1.2       raeburn  1889:         push(@cols,'role');
                   1890:     }
                   1891:     if ($context eq 'domain' && ($env{'form.roletype'} eq 'construction_space' ||
                   1892:                                 $env{'form.roletype'} eq 'course')) {
                   1893:         push (@cols,'extent');
                   1894:     }
                   1895:     if (($statusmode eq 'Any') && 
                   1896:         (!($context eq 'domain' && $env{'form.roletype'} eq 'course'))) {
1.1       raeburn  1897:         push(@cols,'status');
                   1898:     }
                   1899:     if ($context eq 'course') {
                   1900:         push(@cols,'groups');
                   1901:     }
                   1902:     push(@cols,'email');
                   1903: 
1.4       raeburn  1904:     my $rolefilter = $env{'form.showrole'};
1.5       raeburn  1905:     if ($env{'form.showrole'} eq 'cr') {
                   1906:         $rolefilter = &mt('custom');  
                   1907:     } elsif ($env{'form.showrole'} ne 'Any') {
1.2       raeburn  1908:         $rolefilter = &Apache::lonnet::plaintext($env{'form.showrole'});
                   1909:     }
                   1910:     my $results_description = &results_header_row($rolefilter,$statusmode,
                   1911:                                                   $context);
1.3       raeburn  1912:     $r->print('<b>'.$results_description.'</b><br />');
1.11    ! raeburn  1913:     my ($output,$actionselect);
1.1       raeburn  1914:     if ($mode eq 'html' || $mode eq 'view') {
1.11    ! raeburn  1915:         if ($permission->{'cusr'}) {
        !          1916:             $actionselect = &select_actions($context,$setting,$statusmode);
        !          1917:         }
1.1       raeburn  1918:         $r->print(<<END);
1.10      raeburn  1919: <input type="hidden" name="srchby"  value="uname" />
                   1920: <input type="hidden" name="srchin"   value="dom" />
                   1921: <input type="hidden" name="srchtype" value="exact" />
                   1922: <input type="hidden" name="srchterm" value="" />
1.11    ! raeburn  1923: <input type="hidden" name="srchdomain" value="" /> 
1.1       raeburn  1924: END
1.10      raeburn  1925:          if ($mode ne 'autoenroll') {
                   1926:              $output = '<p>';
                   1927:              my @linkdests = ('aboutme');
                   1928:              if ($permission->{'cusr'}) {
                   1929:                  push (@linkdests,'modify');
                   1930:                  $output .= '<span class="LC_nobreak">'.$lt{'link'}.':&nbsp;';
                   1931:                  my $usernamelink = $env{'form.usernamelink'};
                   1932:                  if ($usernamelink eq '') {
                   1933:                      $usernamelink = 'aboutme';
                   1934:                  }
                   1935:                  foreach my $item (@linkdests) {
                   1936:                      my $checkedstr = '';
                   1937:                      if ($item eq $usernamelink) {
                   1938:                          $checkedstr = ' checked="checked" ';
                   1939:                      }
                   1940:                      $output .= '<label><input type="radio" name="usernamelink" value="'.$item.'"'.$checkedstr.'>&nbsp;'.$lt{$item}.'</label>&nbsp;&nbsp;';
                   1941:                  }
                   1942:                  $output .= '</span><br />';
                   1943:              } else {
                   1944:                  $output .= &mt("Click on a username to view the user's personal page.").'<br />';
                   1945:              }
1.11    ! raeburn  1946:              if ($actionselect) {
        !          1947:                  $output .= <<"END"; 
        !          1948: $lt{'ac'}:&nbsp;$actionselect <input type="button" value="$lt{'pr'}" onclick="javascript:verify_action(document.studentform.actionlist)" /></p>
        !          1949: <p><input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.actionlist)" /> &nbsp;
        !          1950: <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.actionlist)" />
        !          1951: END
        !          1952:              }
1.4       raeburn  1953:         }
                   1954:         $output .= "\n<p>\n".
1.1       raeburn  1955:                   &Apache::loncommon::start_data_table().
1.4       raeburn  1956:                   &Apache::loncommon::start_data_table_header_row();
1.1       raeburn  1957:         if ($mode eq 'autoenroll') {
1.4       raeburn  1958:             $output .= "
1.1       raeburn  1959:  <th><a href=\"javascript:document.studentform.sortby.value='type';document.studentform.submit();\">$lt{'type'}</a></th>
1.4       raeburn  1960:             ";
1.1       raeburn  1961:         } else {
1.11    ! raeburn  1962:             $output .= "\n".'<th>'.&mt('Count').'</th>'."\n";
        !          1963:             if ($actionselect) {
        !          1964:                 $output .= '<th>'.&mt('Select').'</th>'."\n";
        !          1965:             }
1.1       raeburn  1966:         }
                   1967:         foreach my $item (@cols) {
1.4       raeburn  1968:             $output .= "<th><a href=\"javascript:document.studentform.sortby.value='$item';document.studentform.submit();\">$lt{$item}</a></th>\n";
1.1       raeburn  1969:         }
1.2       raeburn  1970:         my %role_types = &role_type_names();
1.1       raeburn  1971:         if ($context eq 'course') {
1.4       raeburn  1972:             if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
                   1973:                 # Clicker display on or off?
                   1974:                 my %clicker_options = &Apache::lonlocal::texthash(
                   1975:                                                             'on' => 'Show',
                   1976:                                                             'off' => 'Hide',
                   1977:                                                            );
                   1978:                 my $clickerchg = 'on';
                   1979:                 if ($displayclickers eq 'on') {
                   1980:                     $clickerchg = 'off';
                   1981:                 }
                   1982:                 $output .= '    <th>'."\n".'     '.
                   1983:                     '<a href="javascript:document.studentform.displayclickers.value='.
1.1       raeburn  1984:                       "'".$clickerchg."'".';document.studentform.submit();">'.
                   1985:                       $clicker_options{$clickerchg}.'</a>&nbsp;'.$lt{'clicker'}."\n".
1.4       raeburn  1986:                       '    </th>'."\n";
1.1       raeburn  1987: 
1.4       raeburn  1988:                 # Photo display on or off?
                   1989:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
                   1990:                     my %photo_options = &Apache::lonlocal::texthash(
                   1991:                                                             'on' => 'Show',
                   1992:                                                             'off' => 'Hide',
                   1993:                                                                 );
                   1994:                     my $photochg = 'on';
                   1995:                     if ($displayphotos eq 'on') {
                   1996:                         $photochg = 'off';
                   1997:                     }
                   1998:                     $output .= '    <th>'."\n".'     '.
                   1999:                 '<a href="javascript:document.studentform.displayphotos.value='.
1.1       raeburn  2000:                       "'".$photochg."'".';document.studentform.submit();">'.
                   2001:                       $photo_options{$photochg}.'</a>&nbsp;'.$lt{'photo'}."\n".
1.4       raeburn  2002:                       '    </th>'."\n";
                   2003:                 }
1.1       raeburn  2004:             }
1.4       raeburn  2005:             $output .= &Apache::loncommon::end_data_table_header_row();
                   2006:         }
1.1       raeburn  2007: # Done with the HTML header line
                   2008:     } elsif ($mode eq 'csv') {
                   2009:         #
                   2010:         # Open a file
                   2011:         $CSVfilename = '/prtspool/'.
1.2       raeburn  2012:                        $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
                   2013:                        time.'_'.rand(1000000000).'.csv';
1.1       raeburn  2014:         unless ($CSVfile = Apache::File->new('>/home/httpd'.$CSVfilename)) {
                   2015:             $r->log_error("Couldn't open $CSVfilename for output $!");
                   2016:             $r->print("Problems occured in writing the csv file.  ".
                   2017:                       "This error has been logged.  ".
                   2018:                       "Please alert your LON-CAPA administrator.");
                   2019:             $CSVfile = undef;
                   2020:         }
                   2021:         #
                   2022:         # Write headers and data to file
1.2       raeburn  2023:         print $CSVfile '"'.$results_description.'"'."\n"; 
1.1       raeburn  2024:         print $CSVfile '"'.join('","',map {
                   2025:             &Apache::loncommon::csv_translate($lt{$_})
                   2026:             } (@cols)).'"'."\n";
                   2027:     } elsif ($mode eq 'excel') {
                   2028:         # Create the excel spreadsheet
                   2029:         ($excel_workbook,$excel_filename,$format) =
                   2030:             &Apache::loncommon::create_workbook($r);
                   2031:         return if (! defined($excel_workbook));
                   2032:         $excel_sheet = $excel_workbook->addworksheet('userlist');
1.2       raeburn  2033:         $excel_sheet->write($row++,0,$results_description,$format->{'h2'});
1.1       raeburn  2034:         #
                   2035:         my @colnames = map {$lt{$_}} (@cols);
                   2036:         $excel_sheet->write($row++,0,\@colnames,$format->{'bold'});
                   2037:     }
                   2038: 
                   2039: # Done with header lines in all formats
                   2040: 
                   2041:     my %index;
                   2042:     my $i;
1.2       raeburn  2043:     foreach my $idx (@$keylist) {
                   2044:         $index{$idx} = $i++;
                   2045:     }
1.4       raeburn  2046:     my $usercount = 0;
1.2       raeburn  2047:     # Get groups, role, permanent e-mail so we can sort on them if
                   2048:     # necessary.
                   2049:     foreach my $user (keys(%{$userlist})) {
1.11    ! raeburn  2050:         if ($context eq 'domain' &&  $user eq $env{'request.role.domain'}.'-domainconfig:'.$env{'request.role.domain'}) {
        !          2051:             delete($userlist->{$user});
        !          2052:             next;
        !          2053:         }
1.2       raeburn  2054:         my ($uname,$udom,$role,$groups,$email);
1.5       raeburn  2055:         if (($statusmode ne 'Any') && 
                   2056:                  ($userlist->{$user}->[$index{'status'}] ne $statusmode)) {
                   2057:             delete($userlist->{$user});
                   2058:             next;
                   2059:         }
1.2       raeburn  2060:         if ($context eq 'domain') {
                   2061:             if ($env{'form.roletype'} eq 'domain') {
                   2062:                 ($role,$uname,$udom) = split(/:/,$user);
1.11    ! raeburn  2063:                 if (($uname eq $env{'request.role.domain'}.'-domainconfig') &&
        !          2064:                     ($udom eq $env{'request.role.domain'})) {
        !          2065:                     delete($userlist->{$user});
        !          2066:                     next;
        !          2067:                 }
1.2       raeburn  2068:             } elsif ($env{'form.roletype'} eq 'construction_space') {
                   2069:                 ($uname,$udom,$role) = split(/:/,$user,-1);
                   2070:             } elsif ($env{'form.roletype'} eq 'course') {
                   2071:                 ($uname,$udom,$role) = split(/:/,$user);
                   2072:             }
                   2073:         } else {
                   2074:             ($uname,$udom,$role) = split(/:/,$user,-1);
                   2075:             if (($context eq 'course') && $role eq '') {
                   2076:                 $role = 'st';
                   2077:             }
                   2078:         }
                   2079:         $userlist->{$user}->[$index{'role'}] = $role;
                   2080:         if (($env{'form.showrole'} ne 'Any') && (!($env{'form.showrole'}  eq 'cr' && $role =~ /^cr\//)) && ($role ne $env{'form.showrole'})) {
                   2081:             delete($userlist->{$user});
                   2082:             next;
                   2083:         }
                   2084:         if (ref($classgroups) eq 'HASH') {
                   2085:             $groups = $classgroups->{$user};
                   2086:         }
                   2087:         if (ref($groups->{active}) eq 'HASH') {
                   2088:             $userlist->{$user}->[$index{'groups'}] = join(', ',keys(%{$groups->{'active'}}));
                   2089:         }
                   2090:         my %emails   = &Apache::loncommon::getemails($uname,$udom);
                   2091:         if ($emails{'permanentemail'} =~ /\S/) {
                   2092:             $userlist->{$user}->[$index{'email'}] = $emails{'permanentemail'};
                   2093:         }
1.4       raeburn  2094:         $usercount ++;
                   2095:     }
                   2096:     my $autocount = 0;
                   2097:     my $manualcount = 0;
                   2098:     my $lockcount = 0;
                   2099:     my $unlockcount = 0;
                   2100:     if ($usercount) {
                   2101:         $r->print($output);
                   2102:     } else {
                   2103:         if ($mode eq 'autoenroll') {
                   2104:             return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
                   2105:         } else {
                   2106:             return;
                   2107:         }
1.1       raeburn  2108:     }
1.2       raeburn  2109:     #
                   2110:     # Sort the users
1.1       raeburn  2111:     my $index  = $index{$sortby};
                   2112:     my $second = $index{'username'};
                   2113:     my $third  = $index{'domain'};
1.2       raeburn  2114:     my @sorted_users = sort {
                   2115:         lc($userlist->{$a}->[$index])  cmp lc($userlist->{$b}->[$index])
1.1       raeburn  2116:             ||
1.2       raeburn  2117:         lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second])            ||
                   2118:         lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
                   2119:         } (keys(%$userlist));
1.4       raeburn  2120:     my $rowcount = 0;
1.2       raeburn  2121:     foreach my $user (@sorted_users) {
1.4       raeburn  2122:         my %in;
1.2       raeburn  2123:         my $sdata = $userlist->{$user};
1.4       raeburn  2124:         $rowcount ++; 
1.2       raeburn  2125:         foreach my $item (@{$keylist}) {
                   2126:             $in{$item} = $sdata->[$index{$item}];
                   2127:         }
1.11    ! raeburn  2128:         my $role = $in{'role'};
1.2       raeburn  2129:         $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}]); 
                   2130:         if (! defined($in{'start'}) || $in{'start'} == 0) {
                   2131:             $in{'start'} = &mt('none');
                   2132:         } else {
                   2133:             $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
1.1       raeburn  2134:         }
1.2       raeburn  2135:         if (! defined($in{'end'}) || $in{'end'} == 0) {
                   2136:             $in{'end'} = &mt('none');
1.1       raeburn  2137:         } else {
1.2       raeburn  2138:             $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
1.1       raeburn  2139:         }
1.2       raeburn  2140:         if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll') {
                   2141:             $r->print(&Apache::loncommon::start_data_table_row());
1.4       raeburn  2142:             $r->print("<td>$rowcount</td>\n");
1.11    ! raeburn  2143:             my $checkval;
        !          2144:             if ($mode ne 'autoenroll' && $actionselect) {
        !          2145:                 $checkval = $user; 
        !          2146:                 if ($context eq 'course') {
        !          2147:                     if ($role eq 'st') {
        !          2148:                         $checkval .= ':st';
        !          2149:                     }
        !          2150:                     $checkval .= ':'.$in{'section'};
        !          2151:                     if ($role eq 'st') {
        !          2152:                         $checkval .= ':'.$in{'type'}.':'.$in{'lockedtype'};
        !          2153:                     }
        !          2154:                 }
        !          2155:                 $r->print('<td><input type="checkbox" name="actionlist" value="'.
        !          2156:                           $checkval.'"></td>');
        !          2157:             }
1.2       raeburn  2158:             foreach my $item (@cols) {
1.10      raeburn  2159:                 if ($item eq 'username') {
                   2160:                     $r->print('<td>'.&print_username_link($permission,\%in).'</td>');
1.11    ! raeburn  2161:                 } elsif (($item eq 'start' || $item eq 'end') && ($mode ne 'autoeroll') && ($actionselect)) {
        !          2162:                     $r->print('<td>'.$in{$item}.'<input type="hidden" name="'.$checkval.'_'.$item.'" value="'.$sdata->[$index{$item}].'" /></td>'."\n");
1.10      raeburn  2163:                 } else {
                   2164:                     $r->print('<td>'.$in{$item}.'</td>'."\n");
                   2165:                 }
1.2       raeburn  2166:             }
                   2167:             if ($context eq 'course') {
1.4       raeburn  2168:                 if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
                   2169:                     if ($displayclickers eq 'on') {
                   2170:                         my $clickers =
1.2       raeburn  2171:                    (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
1.4       raeburn  2172:                         if ($clickers!~/\w/) { $clickers='-'; }
                   2173:                         $r->print('<td>'.$clickers.'</td>');
1.2       raeburn  2174:                     } else {
                   2175:                         $r->print('    <td>&nbsp;</td>  ');
                   2176:                     }
1.4       raeburn  2177:                     if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
                   2178:                         if ($displayphotos eq 'on' && $sdata->[$index{'role'}] eq 'st') {
                   2179:                             my $imgurl =
                   2180:                         &Apache::lonnet::retrievestudentphoto($in{'domain'},$in{'username'},
                   2181:                                                           'gif','thumbnail');
                   2182:                             $r->print('    <td align="right"><a href="javascript:photowindow('."'".&Apache::lonnet::studentphoto($in{'domain'},$in{'username'},'jpg')."'".')"><img src="'.$imgurl.'" border="1"></a></td>');
                   2183:                         } else {
                   2184:                             $r->print('    <td>&nbsp;</td>  ');
                   2185:                         }
                   2186:                     }
1.2       raeburn  2187:                 }
                   2188:             }
                   2189:             $r->print(&Apache::loncommon::end_data_table_row());
                   2190:         } elsif ($mode eq 'csv') {
                   2191:             next if (! defined($CSVfile));
                   2192:             # no need to bother with $linkto
                   2193:             if (! defined($in{'start'}) || $in{'start'} == 0) {
                   2194:                 $in{'start'} = &mt('none');
                   2195:             } else {
                   2196:                 $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
                   2197:             }
                   2198:             if (! defined($in{'end'}) || $in{'end'} == 0) {
                   2199:                 $in{'end'} = &mt('none');
                   2200:             } else {
                   2201:                 $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
                   2202:             }
                   2203:             my @line = ();
                   2204:             foreach my $item (@cols) {
                   2205:                 push @line,&Apache::loncommon::csv_translate($in{$item});
                   2206:             }
                   2207:             print $CSVfile '"'.join('","',@line).'"'."\n";
                   2208:         } elsif ($mode eq 'excel') {
                   2209:             my $col = 0;
                   2210:             foreach my $item (@cols) {
                   2211:                 if ($item eq 'start' || $item eq 'end') {
                   2212:                     if (defined($item) && $item != 0) {
                   2213:                         $excel_sheet->write($row,$col++,
                   2214:                             &Apache::lonstathelpers::calc_serial($in{item}),
                   2215:                                     $format->{'date'});
                   2216:                     } else {
                   2217:                         $excel_sheet->write($row,$col++,'none');
                   2218:                     }
                   2219:                 } else {
                   2220:                     $excel_sheet->write($row,$col++,$in{$item});
                   2221:                 }
                   2222:             }
                   2223:             $row++;
1.1       raeburn  2224:         }
                   2225:     }
1.2       raeburn  2226:     if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll') {
                   2227:             $r->print(&Apache::loncommon::end_data_table().'<br />');
                   2228:     } elsif ($mode eq 'excel') {
                   2229:         $excel_workbook->close();
                   2230:         $r->print('<p><a href="'.$excel_filename.'">'.
                   2231:                   &mt('Your Excel spreadsheet').'</a> '.&mt('is ready for download').'.</p>'."\n");
                   2232:     } elsif ($mode eq 'csv') {
                   2233:         close($CSVfile);
                   2234:         $r->print('<a href="'.$CSVfilename.'">'.
                   2235:                   &mt('Your CSV file').'</a> is ready for download.'.
                   2236:                   "\n");
                   2237:         $r->rflush();
                   2238:     }
                   2239:     if ($mode eq 'autoenroll') {
                   2240:         return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
1.4       raeburn  2241:     } else {
                   2242:         return ($usercount);
1.2       raeburn  2243:     }
1.1       raeburn  2244: }
                   2245: 
1.10      raeburn  2246: sub print_username_link {
                   2247:     my ($permission,$in) = @_;
                   2248:     my $output;
                   2249:     if (!$permission->{'cusr'}) {
                   2250:         $output = &Apache::loncommon::aboutmewrapper($in->{'username'},
                   2251:                                                      $in->{'username'},
                   2252:                                                      $in->{'domain'});
                   2253:     } else {
                   2254:         $output = '<a href="javascript:username_display_launch('.
                   2255:                   "'$in->{'username'}','$in->{'domain'}'".')" />'.
                   2256:                   $in->{'username'}.'</a>';
                   2257:     }
                   2258:     return $output;
                   2259: }
                   2260: 
1.2       raeburn  2261: sub role_type_names {
                   2262:     my %lt = &Apache::lonlocal::texthash (
                   2263:                          'domain'             => 'Domain Roles',
                   2264:                          'construction_space' => 'Co-Author Roles',
                   2265:                          'course'             => 'Course Roles',
                   2266:              );
                   2267:     return %lt;
                   2268: }
                   2269: 
1.11    ! raeburn  2270: sub select_actions {
        !          2271:     my ($context,$setting,$statusmode) = @_;
        !          2272:     my %lt = &Apache::lonlocal::texthash(
        !          2273:                 revoke   => "Revoke user roles",
        !          2274:                 delete   => "Delete user roles",
        !          2275:                 reenable => "Re-enable expired user roles",
        !          2276:                 activate => "Make future user roles active now",
        !          2277:                 chgdates  => "Change starting/ending dates",
        !          2278:                 chgsec   => "Change section associated with user roles",
        !          2279:     );
        !          2280:     my ($output,$options,%choices);
        !          2281:     if ($statusmode eq 'Any') {
        !          2282:         $options .= '
        !          2283: <option value="chgdates">'.$lt{'chgdates'}.'</option>';
        !          2284:         $choices{'dates'} = 1;
        !          2285:     } else {
        !          2286:         if ($statusmode eq 'Active' || $statusmode eq 'Future') {
        !          2287:             $options .= '
        !          2288: <option value="revoke">'.$lt{'revoke'}.'</option>';
        !          2289:         }
        !          2290:         if ($statusmode eq 'Future') {
        !          2291:             $options .= '
        !          2292: <option value="activate">'.$lt{'activate'}.'</option>';
        !          2293:             $choices{'dates'} = 1;
        !          2294:         } elsif ($statusmode eq 'Expired') {
        !          2295:             $options .= '
        !          2296: <option value="reenable">'.$lt{'reenable'}.'</option>';
        !          2297:             $choices{'dates'} = 1;
        !          2298:         }
        !          2299:     }
        !          2300:     if ($context eq 'domain') {
        !          2301:         $options .= '
        !          2302: <option value="delete">'.$lt{'delete'}.'</option>';
        !          2303:     }
        !          2304:     if (($context eq 'course') || ($context eq 'domain' && $setting eq 'course')) {
        !          2305:         if ($statusmode ne 'Expired') {
        !          2306:             $options .= '
        !          2307: <option value="chgsec">'.$lt{'chgsec'}.'</option>';
        !          2308:             $choices{'sections'} = 1;
        !          2309:         }
        !          2310:     }
        !          2311:     if ($options) {
        !          2312:         $output = '<select name="bulkaction" onchange="javascript:opendatebrowser(this.form,'."'studentform'".')" />'."\n".
        !          2313:                   '<option value="" selected="selected">'.
        !          2314:                   &mt('Please select').'</option>'."\n".$options."\n".'</select>';
        !          2315:         if ($choices{'dates'}) {
        !          2316:             $output .= 
        !          2317:                 '<input type="hidden" name="startdate_month" value="" />'."\n".
        !          2318:                 '<input type="hidden" name="startdate_day" value="" />'."\n".
        !          2319:                 '<input type="hidden" name="startdate_year" value="" />'."\n".
        !          2320:                 '<input type="hidden" name="startdate_hour" value="" />'."\n".
        !          2321:                 '<input type="hidden" name="startdate_minute" value="" />'."\n".
        !          2322:                 '<input type="hidden" name="startdate_second" value="" />'."\n".
        !          2323:                 '<input type="hidden" name="enddate_month" value="" />'."\n".
        !          2324:                 '<input type="hidden" name="enddate_day" value="" />'."\n".
        !          2325:                 '<input type="hidden" name="enddate_year" value="" />'."\n".
        !          2326:                 '<input type="hidden" name="enddate_hour" value="" />'."\n".
        !          2327:                 '<input type="hidden" name="enddate_minute" value="" />'."\n".
        !          2328:                 '<input type="hidden" name="enddate_second" value="" />'."\n";
        !          2329:             if ($context eq 'course') {
        !          2330:                 $output .= '<input type="hidden" name="makedatesdefault" value="" />'."\n";
        !          2331:             }
        !          2332:         }
        !          2333:         if ($choices{'sections'}) {
        !          2334:             $output .= '<input type="hidden" name="retainsec" value= "" />'."\n".
        !          2335:                        '<input type="hidden" name="newsecs" value= "" />'."\n";
        !          2336:         }
        !          2337:     }
        !          2338:     return $output;
        !          2339: }
        !          2340: 
        !          2341: sub date_section_javascript {
        !          2342:     my ($context,$setting) = @_;
        !          2343:     my $title;
        !          2344:     if (($context eq 'course') || ($context eq 'domain' && $setting eq 'course'))  {
        !          2345:         $title = &mt('Date and Section selector');
        !          2346:     } else {
        !          2347:         $title = &mt('Date selector');
        !          2348:     }
        !          2349:     my $output = '
        !          2350: <script type="text/javascript">
        !          2351:     var stdeditbrowser;'."\n";
        !          2352:     $output .= <<"ENDONE";
        !          2353:     function opendatebrowser(callingform,formname) {
        !          2354:         var bulkaction = callingform.bulkaction.options[callingform.bulkaction.selectedIndex].value;
        !          2355:         if (bulkaction == 'revoke' || bulkaction == 'delete' || bulkaction == '') {
        !          2356:             return;
        !          2357:         }
        !          2358:         var url = '/adm/createuser?';
        !          2359:         var type = '';
        !          2360:         var showrole = callingform.showrole.options[callingform.showrole.selectedIndex].value;
        !          2361: ENDONE
        !          2362:     if ($context eq 'domain') {
        !          2363:         $output .= '
        !          2364:         type = callingform.roletype.options[callingform.roletype.selectedIndex].value;
        !          2365: ';
        !          2366:     }
        !          2367:     my $width= '700';
        !          2368:     my $height = '400';
        !          2369:     $output .= <<"ENDTWO";
        !          2370:         url += 'action=dateselect&callingform=' + formname + 
        !          2371:                '&roletype='+type+'&showrole='+showrole +'&bulkaction='+bulkaction;
        !          2372:         var title = '$title';
        !          2373:         var options = 'scrollbars=1,resizable=1,menubar=0';
        !          2374:         options += ',width=$width,height=$height';
        !          2375:         stdeditbrowser = open(url,title,options,'1');
        !          2376:         stdeditbrowser.focus();
        !          2377:     }
        !          2378: </script>
        !          2379: ENDTWO
        !          2380:     return $output;
        !          2381: }
        !          2382: 
        !          2383: sub date_section_selector {
        !          2384:     my ($context) = @_;
        !          2385:     my $callingform = $env{'form.callingform'};
        !          2386:     my $formname = 'dateselect';  
        !          2387:     my $groupslist = &get_groupslist();
        !          2388:     my $sec_js = &setsections_javascript($formname,$groupslist);
        !          2389:     my $output = <<"END";
        !          2390: <script type="text/javascript">
        !          2391: 
        !          2392: $sec_js
        !          2393: 
        !          2394: function saveselections(formname) {
        !          2395: 
        !          2396: END
        !          2397:     if ($env{'form.bulkaction'} eq 'chgsec') {
        !          2398:         $output .= <<"END";
        !          2399:         opener.document.$callingform.retainsec.value = formname.retainsec.value;
        !          2400:         setSections(formname);
        !          2401:         if (seccheck == 'ok') {
        !          2402:             opener.document.$callingform.newsecs.value = formname.sections.value;
        !          2403:             window.close();
        !          2404:         }
        !          2405:         return;
        !          2406: END
        !          2407:     } else {
        !          2408:         if ($context eq 'course') {
        !          2409:             if (($env{'form.bulkaction'} eq 'reenable') || 
        !          2410:                 ($env{'form.bulkaction'} eq 'activate') || 
        !          2411:                 ($env{'form.bulkaction'} eq 'chgdates')) {
        !          2412:                 $output .= <<"END";
        !          2413:  
        !          2414:         if (formname.makedatesdefault.checked == true) {
        !          2415:             opener.document.$callingform.makedatesdefault.value = 1;
        !          2416:         }
        !          2417:         else {
        !          2418:             opener.document.$callingform.makedatesdefault.value = 0;
        !          2419:         }
        !          2420: 
        !          2421: END
        !          2422:             }
        !          2423:         }
        !          2424:         $output .= <<"END";
        !          2425:     opener.document.$callingform.startdate_month.value =  formname.startdate_month.options[formname.startdate_month.selectedIndex].value;
        !          2426:     opener.document.$callingform.startdate_day.value =  formname.startdate_day.value;
        !          2427:     opener.document.$callingform.startdate_year.value = formname.startdate_year.value;
        !          2428:     opener.document.$callingform.startdate_hour.value =  formname.startdate_hour.options[formname.startdate_hour.selectedIndex].value;
        !          2429:     opener.document.$callingform.startdate_minute.value =  formname.startdate_minute.value;
        !          2430:     opener.document.$callingform.startdate_second.value = formname.startdate_second.value;
        !          2431:     opener.document.$callingform.enddate_month.value =  formname.enddate_month.options[formname.enddate_month.selectedIndex].value;
        !          2432:     opener.document.$callingform.enddate_day.value =  formname.enddate_day.value;
        !          2433:     opener.document.$callingform.enddate_year.value = formname.enddate_year.value;
        !          2434:     opener.document.$callingform.enddate_hour.value =  formname.enddate_hour.options[formname.enddate_hour.selectedIndex].value;
        !          2435:     opener.document.$callingform.enddate_minute.value =  formname.enddate_minute.value;
        !          2436:     opener.document.$callingform.enddate_second.value = formname.enddate_second.value;
        !          2437:     window.close();
        !          2438: END
        !          2439:     }
        !          2440:     $output .= '
        !          2441: }
        !          2442: </script>
        !          2443: ';
        !          2444:     my %lt = &Apache::lonlocal::texthash (
        !          2445:                  chac => 'Access dates to apply for selected users',
        !          2446:                  chse => 'Changes in section affiliation to apply to selected users',
        !          2447:                  fors => 'For student roles changing the section, will result in a section switch as students may only be in one section of a course at a time.',
        !          2448:                  forn => 'For a role in a course that is not a student role, a user may have roles in more than one section of a course at a time.',
        !          2449:                  reta => "Retain each user's current section affiliations?", 
        !          2450:                  dnap => '(Does not apply to student roles).', 
        !          2451:             );
        !          2452:     my ($date_items,$headertext);
        !          2453:     if ($env{'form.bulkaction'} eq 'chgsec') {
        !          2454:         $headertext = $lt{'chse'};
        !          2455:     } else {
        !          2456:         $headertext = $lt{'chac'};
        !          2457:         my $starttime;
        !          2458:         if (($env{'form.bulkaction'} eq 'activate') || 
        !          2459:             ($env{'form.bulkaction'} eq 'reenable')) {
        !          2460:             $starttime = time;
        !          2461:         }
        !          2462:         $date_items = &date_setting_table($starttime,undef,$context,
        !          2463:                                           $env{'form.bulkaction'});
        !          2464:     }
        !          2465:     $output .= '<h3>'.$headertext.'</h3>'.
        !          2466:                '<form name="'.$formname.'" method="post">'."\n".
        !          2467:                 $date_items;
        !          2468:     if ($context eq 'course' && $env{'form.bulkaction'} eq 'chgsec') {
        !          2469:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          2470:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        !          2471:         my %sections_count =
        !          2472:             &Apache::loncommon::get_sections($cdom,$cnum);
        !          2473:         my $info;
        !          2474:         if ($env{'form.showrole'} eq 'st') {
        !          2475:             $output .= '<p>'.$lt{'fors'}.'</p>'; 
        !          2476:         } elsif ($env{'form.shorole'} eq 'Any') {
        !          2477:             $output .= '<p>'.$lt{'fors'}.'</p>'.
        !          2478:                        '<p>'.$lt{'forn'}.'&nbsp;';
        !          2479:             $info = $lt{'reta'};
        !          2480:         } else {
        !          2481:             $output .= '<p>'.$lt{'forn'}.'&nbsp;';
        !          2482:             $info = $lt{'reta'};
        !          2483:         }
        !          2484:         if ($info) {
        !          2485:             $info .= '<span class="LC_nobreak">'.
        !          2486:                      '<label><input type="radio" name="retainsec" value="1" '.
        !          2487:                      'checked="checked" />'.&mt('Yes').'</label>&nbsp;&nbsp;'.
        !          2488:                      '<label><input type="radio" name="retainsec" value="0" />'.
        !          2489:                      &mt('No').'</label></span>';
        !          2490:             if ($env{'form.showrole'} eq 'Any') {
        !          2491:                 $info .= '<br />'.$lt{'dnap'};
        !          2492:             }
        !          2493:             $info .= '</p>';
        !          2494:         } else {
        !          2495:             $info = '<input type="hidden" name="retainsec" value="0" />'; 
        !          2496:         }
        !          2497:         my $sections_select .= &course_sections(\%sections_count,$env{'form.showrole'});
        !          2498:         my $secbox = '<p>'.&Apache::lonhtmlcommon::start_pick_box()."\n".
        !          2499:                      &Apache::lonhtmlcommon::row_title(&mt('New section to assign'),'LC_oddrow_value')."\n".
        !          2500:                      '<table class="LC_createuser"><tr class="LC_section_row">'."\n".
        !          2501:                      '<td align="center">'.&mt('Existing sections')."\n".
        !          2502:                      '<br />'.$sections_select.'</td><td align="center">'.
        !          2503:                      &mt('New section').'<br />'."\n".
        !          2504:                      '<input type="text" name="newsec" size="15" />'."\n".
        !          2505:                      '<input type="hidden" name="sections" value="" />'."\n".
        !          2506:                      '</td></tr></table>'."\n".
        !          2507:                      &Apache::lonhtmlcommon::row_closure(1)."\n".
        !          2508:                      &Apache::lonhtmlcommon::end_pick_box().'</p>';
        !          2509:         $output .= $info.$secbox;
        !          2510:     }
        !          2511:     $output .= '<p>'.
        !          2512: &mt('Use "Save" to update the main window with your selections.').'<br /><br />'.
        !          2513: '<input type="button" name="dateselection" value="'.&mt('Save').'" onclick="javascript:saveselections(this.form)" /></p>'."\n".
        !          2514: '</form>';
        !          2515:     return $output;
        !          2516: }
        !          2517: 
1.2       raeburn  2518: sub results_header_row {
                   2519:     my ($rolefilter,$statusmode,$context) = @_;
1.5       raeburn  2520:     my ($description,$showfilter);
                   2521:     if ($rolefilter ne 'Any') {
                   2522:         $showfilter = $rolefilter;
                   2523:     }
1.2       raeburn  2524:     if ($context eq 'course') {
1.3       raeburn  2525:         $description = &mt('Course - ').$env{'course.'.$env{'request.course.id'}.'.description'}.': ';
1.2       raeburn  2526:         if ($statusmode eq 'Expired') {
1.5       raeburn  2527:             $description .= &mt('Users in course with expired [_1] roles',$showfilter);
1.11    ! raeburn  2528:         } elsif ($statusmode eq 'Future') {
1.5       raeburn  2529:             $description .= &mt('Users in course with future [_1] roles',$showfilter);
1.2       raeburn  2530:         } elsif ($statusmode eq 'Active') {
1.5       raeburn  2531:             $description .= &mt('Users in course with active [_1] roles',$showfilter);
1.2       raeburn  2532:         } else {
                   2533:             if ($rolefilter eq 'Any') {
                   2534:                 $description .= &mt('All users in course');
                   2535:             } else {
                   2536:                 $description .= &mt('All users in course with [_1] roles',$rolefilter);
                   2537:             }
                   2538:         }
                   2539:     } elsif ($context eq 'construction_space') {
                   2540:         $description = &mt('Author space for [_1].').' ';
                   2541:         if ($statusmode eq 'Expired') {
1.5       raeburn  2542:             $description .= &mt('Co-authors with expired [_1] roles',$showfilter);
1.2       raeburn  2543:         } elsif ($statusmode eq 'Future') {
1.5       raeburn  2544:             $description .= &mt('Co-authors with future [_1] roles',$showfilter);
1.2       raeburn  2545:         } elsif ($statusmode eq 'Active') {
1.5       raeburn  2546:             $description .= &mt('Co-authors with active [_1] roles',$showfilter);
1.2       raeburn  2547:         } else {
                   2548:             if ($rolefilter eq 'Any') {
1.5       raeburn  2549:                 $description .= &mt('All co-authors');
1.2       raeburn  2550:             } else {
                   2551:                 $description .= &mt('All co-authors with [_1] roles',$rolefilter);
                   2552:             }
                   2553:         }
                   2554:     } elsif ($context eq 'domain') {
                   2555:         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
                   2556:         $description = &mt('Domain - ').$domdesc.': ';
                   2557:         if ($env{'form.roletype'} eq 'domain') {
                   2558:             if ($statusmode eq 'Expired') {
1.5       raeburn  2559:                 $description .= &mt('Users in domain with expired [_1] roles',$showfilter);
1.2       raeburn  2560:             } elsif ($statusmode eq 'Future') {
1.5       raeburn  2561:                 $description .= &mt('Users in domain with future [_1] roles',$showfilter);
1.2       raeburn  2562:             } elsif ($statusmode eq 'Active') {
1.5       raeburn  2563:                 $description .= &mt('Users in domain with active [_1] roles',$showfilter);
1.2       raeburn  2564:             } else {
                   2565:                 if ($rolefilter eq 'Any') {
1.5       raeburn  2566:                     $description .= &mt('All users in domain');
1.2       raeburn  2567:                 } else {
                   2568:                     $description .= &mt('All users in domain with [_1] roles',$rolefilter);
                   2569:                 }
                   2570:             }
                   2571:         } elsif ($env{'form.roletype'} eq 'construction_space') {
                   2572:             if ($statusmode eq 'Expired') {
1.5       raeburn  2573:                 $description .= &mt('Co-authors in domain with expired [_1] roles',$showfilter);
1.2       raeburn  2574:             } elsif ($statusmode eq 'Future') {
1.5       raeburn  2575:                 $description .= &mt('Co-authors in domain with future [_1] roles',$showfilter);
1.2       raeburn  2576:             } elsif ($statusmode eq 'Active') {
1.5       raeburn  2577:                $description .= &mt('Co-authors in domain with active [_1] roles',$showfilter);
1.2       raeburn  2578:             } else {
                   2579:                 if ($rolefilter eq 'Any') {
1.5       raeburn  2580:                     $description .= &mt('All users with co-author roles in domain',$showfilter);
1.2       raeburn  2581:                 } else {
                   2582:                     $description .= &mt('All co-authors in domain  with [_1] roles',$rolefilter);
                   2583:                 }
                   2584:             }
                   2585:         } elsif ($env{'form.roletype'} eq 'course') {
                   2586:             my $coursefilter = $env{'form.coursepick'};
                   2587:             if ($coursefilter eq 'category') {
                   2588:                 my $instcode = &instcode_from_coursefilter();
                   2589:                 if ($instcode eq '.') {
                   2590:                     $description .= &mt('All courses in domain').' - ';
                   2591:                 } else {
                   2592:                     $description .= &mt('Courses in domain with institutional code: [_1]',$instcode).' - ';
                   2593:                 }
                   2594:             } elsif ($coursefilter eq 'selected') {
                   2595:                 $description .= &mt('Selected courses in domain').' - ';
                   2596:             } elsif ($coursefilter eq 'all') {
                   2597:                 $description .= &mt('All courses in domain').' - ';
                   2598:             }
                   2599:             if ($statusmode eq 'Expired') {
1.5       raeburn  2600:                 $description .= &mt('users with expired [_1] roles',$showfilter);
1.2       raeburn  2601:             } elsif ($statusmode eq 'Future') {
1.5       raeburn  2602:                 $description .= &mt('users with future [_1] roles',$showfilter);
1.2       raeburn  2603:             } elsif ($statusmode eq 'Active') {
1.5       raeburn  2604:                 $description .= &mt('users with active [_1] roles',$showfilter);
1.2       raeburn  2605:             } else {
                   2606:                 if ($rolefilter eq 'Any') {
                   2607:                     $description .= &mt('all users');
                   2608:                 } else {
                   2609:                     $description .= &mt('users with [_1] roles',$rolefilter);
                   2610:                 }
                   2611:             }
                   2612:         }
                   2613:     }
                   2614:     return $description;
                   2615: }
                   2616:     
1.1       raeburn  2617: #################################################
                   2618: #################################################
                   2619: sub show_drop_list {
                   2620:     my ($r,$classlist,$keylist,$nosort)=@_;
                   2621:     my $cid=$env{'request.course.id'};
                   2622:     if (! exists($env{'form.sortby'})) {
                   2623:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   2624:                                                 ['sortby']);
                   2625:     }
                   2626:     my $sortby = $env{'form.sortby'};
                   2627:     if ($sortby !~ /^(username|domain|section|groups|fullname|id|start|end)$/) {
                   2628:         $sortby = 'username';
                   2629:     }
                   2630:     my $cdom = $env{'course.'.$cid.'.domain'};
                   2631:     my $cnum = $env{'course.'.$cid,'.num'};
                   2632:     my ($classgroups) = &Apache::loncoursedata::get_group_memberships(
                   2633:                                               $classlist,$keylist,$cdom,$cnum);
                   2634:     #
                   2635:     my $action = "drop";
                   2636:     $r->print(<<END);
                   2637: <input type="hidden" name="sortby" value="$sortby" />
                   2638: <input type="hidden" name="action" value="$action" />
                   2639: <input type="hidden" name="state"  value="done" />
                   2640: <script>
                   2641: function checkAll(field) {
                   2642:     for (i = 0; i < field.length; i++)
                   2643:         field[i].checked = true ;
                   2644: }
                   2645: 
                   2646: function uncheckAll(field) {
                   2647:     for (i = 0; i < field.length; i++)
                   2648:         field[i].checked = false ;
                   2649: }
                   2650: </script>
                   2651: <p>
                   2652: <input type="hidden" name="phase" value="four">
                   2653: END
                   2654: 
                   2655: my %lt=&Apache::lonlocal::texthash('usrn'   => "username",
                   2656:                                    'dom'    => "domain",
                   2657:                                    'sn'     => "student name",
                   2658:                                    'sec'    => "section",
                   2659:                                    'start'  => "start date",
                   2660:                                    'end'    => "end date",
                   2661:                                    'groups' => "active groups",
                   2662:                                    );
                   2663:     if ($nosort) {
                   2664:         $r->print(&Apache::loncommon::start_data_table());
                   2665:         $r->print(<<END);
                   2666: <tr>
                   2667:     <th>&nbsp;</th>
                   2668:     <th>$lt{'usrn'}</th>
                   2669:     <th>$lt{'dom'}</th>
                   2670:     <th>ID</th>
                   2671:     <th>$lt{'sn'}</th>
                   2672:     <th>$lt{'sec'}</th>
                   2673:     <th>$lt{'start'}</th>
                   2674:     <th>$lt{'end'}</th>
                   2675:     <th>$lt{'groups'}</th>
                   2676: </tr>
                   2677: END
                   2678: 
                   2679:     } else  {
                   2680:         $r->print(&Apache::loncommon::start_data_table());
                   2681:         $r->print(<<END);
                   2682: <tr><th>&nbsp;</th>
                   2683:     <th>
                   2684:        <a href="/adm/dropadd?action=$action&sortby=username">$lt{'usrn'}</a>
                   2685:     </th><th>
                   2686:        <a href="/adm/dropadd?action=$action&sortby=domain">$lt{'dom'}</a>
                   2687:     </th><th>
                   2688:        <a href="/adm/dropadd?action=$action&sortby=id">ID</a>
                   2689:     </th><th>
                   2690:        <a href="/adm/dropadd?action=$action&sortby=fullname">$lt{'sn'}</a>
                   2691:     </th><th>
                   2692:        <a href="/adm/dropadd?action=$action&sortby=section">$lt{'sec'}</a>
                   2693:     </th><th>
                   2694:        <a href="/adm/dropadd?action=$action&sortby=start">$lt{'start'}</a>
                   2695:     </th><th>
                   2696:        <a href="/adm/dropadd?action=$action&sortby=end">$lt{'end'}</a>
                   2697:     </th><th>
                   2698:        <a href="/adm/dropadd?action=$action&sortby=groups">$lt{'groups'}</a>
                   2699:     </th>
                   2700: </tr>
                   2701: END
                   2702:     }
                   2703:     #
                   2704:     # Sort the students
                   2705:     my %index;
                   2706:     my $i;
                   2707:     foreach (@$keylist) {
                   2708:         $index{$_} = $i++;
                   2709:     }
                   2710:     $index{'groups'} = scalar(@$keylist);
                   2711:     my $index  = $index{$sortby};
                   2712:     my $second = $index{'username'};
                   2713:     my $third  = $index{'domain'};
                   2714:     my @Sorted_Students = sort {
                   2715:         lc($classlist->{$a}->[$index])  cmp lc($classlist->{$b}->[$index])
                   2716:             ||
                   2717:         lc($classlist->{$a}->[$second]) cmp lc($classlist->{$b}->[$second])
                   2718:             ||
                   2719:         lc($classlist->{$a}->[$third]) cmp lc($classlist->{$b}->[$third])
                   2720:         } (keys(%$classlist));
                   2721:     foreach my $student (@Sorted_Students) {
                   2722:         my $error;
                   2723:         my $sdata = $classlist->{$student};
                   2724:         my $username = $sdata->[$index{'username'}];
                   2725:         my $domain   = $sdata->[$index{'domain'}];
                   2726:         my $section  = $sdata->[$index{'section'}];
                   2727:         my $name     = $sdata->[$index{'fullname'}];
                   2728:         my $id       = $sdata->[$index{'id'}];
                   2729:         my $start    = $sdata->[$index{'start'}];
                   2730:         my $end      = $sdata->[$index{'end'}];
                   2731:         my $groups = $classgroups->{$student};
                   2732:         my $active_groups;
                   2733:         if (ref($groups->{active}) eq 'HASH') {
                   2734:             $active_groups = join(', ',keys(%{$groups->{'active'}}));
                   2735:         }
                   2736:         if (! defined($start) || $start == 0) {
                   2737:             $start = &mt('none');
                   2738:         } else {
                   2739:             $start = &Apache::lonlocal::locallocaltime($start);
                   2740:         }
                   2741:         if (! defined($end) || $end == 0) {
                   2742:             $end = &mt('none');
                   2743:         } else {
                   2744:             $end = &Apache::lonlocal::locallocaltime($end);
                   2745:         }
                   2746:         my $status   = $sdata->[$index{'status'}];
                   2747:         next if ($status ne 'Active');
                   2748:         #
                   2749:         $r->print(&Apache::loncommon::start_data_table_row());
                   2750:         $r->print(<<"END");
                   2751:     <td><input type="checkbox" name="droplist" value="$student"></td>
                   2752:     <td>$username</td>
                   2753:     <td>$domain</td>
                   2754:     <td>$id</td>
                   2755:     <td>$name</td>
                   2756:     <td>$section</td>
                   2757:     <td>$start</td>
                   2758:     <td>$end</td>
                   2759:     <td>$active_groups</td>
                   2760: END
                   2761:         $r->print(&Apache::loncommon::end_data_table_row());
                   2762:     }
                   2763:     $r->print(&Apache::loncommon::end_data_table().'<br />');
                   2764:     %lt=&Apache::lonlocal::texthash(
                   2765:                        'dp'   => "Expire Users' Roles",
                   2766:                        'ca'   => "check all",
                   2767:                        'ua'   => "uncheck all",
                   2768:                                        );
                   2769:     $r->print(<<"END");
                   2770: </p><p>
                   2771: <input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.droplist)"> &nbsp;
                   2772: <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.droplist)">
                   2773: <p><input type=submit value="$lt{'dp'}"></p>
                   2774: END
                   2775:     return;
                   2776: }
                   2777: 
                   2778: #
                   2779: # Print out the initial form to get the file containing a list of users
                   2780: #
                   2781: sub print_first_users_upload_form {
                   2782:     my ($r,$context) = @_;
                   2783:     my $str;
                   2784:     $str  = '<input type="hidden" name="phase" value="two">';
                   2785:     $str .= '<input type="hidden" name="action" value="upload" />';
                   2786:     $str .= '<input type="hidden"   name="state"  value="got_file" />';
1.2       raeburn  2787:     $str .= "<h3>".&mt('Upload a file containing information about users')."</h3>\n";
1.1       raeburn  2788:     $str .= &Apache::loncommon::upfile_select_html();
                   2789:     $str .= "<p>\n";
                   2790:     $str .= '<input type="submit" name="fileupload" value="'.
1.2       raeburn  2791:         &mt('Upload file of users').'">'."\n";
1.1       raeburn  2792:     $str .= '<label><input type="checkbox" name="noFirstLine" /> '.
                   2793:         &mt('Ignore First Line')."</label></p>\n";
                   2794:     $str .= &Apache::loncommon::help_open_topic("Course_Create_Class_List",
                   2795:                          &mt("How do I create a users list from a spreadsheet")).
                   2796:                              "<br />\n";
                   2797:     $str .= &Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   2798:                            &mt("How do I create a CSV file from a spreadsheet")).
                   2799:                                "<br />\n";
                   2800:     $str .= &Apache::loncommon::end_page();
                   2801:     $r->print($str);
                   2802:     return;
                   2803: }
                   2804: 
                   2805: # ================================================= Drop/Add from uploaded file
                   2806: sub upfile_drop_add {
                   2807:     my ($r,$context) = @_;
                   2808:     &Apache::loncommon::load_tmp_file($r);
                   2809:     my @userdata=&Apache::loncommon::upfile_record_sep();
                   2810:     if($env{'form.noFirstLine'}){shift(@userdata);}
                   2811:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   2812:     my %fields=();
                   2813:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   2814:         if ($env{'form.upfile_associate'} eq 'reverse') {
                   2815:             if ($env{'form.f'.$i} ne 'none') {
                   2816:                 $fields{$keyfields[$i]}=$env{'form.f'.$i};
                   2817:             }
                   2818:         } else {
                   2819:             $fields{$env{'form.f'.$i}}=$keyfields[$i];
                   2820:         }
                   2821:     }
                   2822:     #
                   2823:     # Store the field choices away
                   2824:     foreach my $field (qw/username names
                   2825:                        fname mname lname gen id sec ipwd email role/) {
                   2826:         $env{'form.'.$field.'_choice'}=$fields{$field};
                   2827:     }
                   2828:     &Apache::loncommon::store_course_settings('enrollment_upload',
                   2829:                                               { 'username_choice' => 'scalar',
                   2830:                                                 'names_choice' => 'scalar',
                   2831:                                                 'fname_choice' => 'scalar',
                   2832:                                                 'mname_choice' => 'scalar',
                   2833:                                                 'lname_choice' => 'scalar',
                   2834:                                                 'gen_choice' => 'scalar',
                   2835:                                                 'id_choice' => 'scalar',
                   2836:                                                 'sec_choice' => 'scalar',
                   2837:                                                 'ipwd_choice' => 'scalar',
                   2838:                                                 'email_choice' => 'scalar',
                   2839:                                                 'role_choice'  => 'scalar' });
                   2840:     #
                   2841:     my ($startdate,$enddate) = &get_dates_from_form();
                   2842:     if ($env{'form.makedatesdefault'}) {
                   2843:         $r->print(&make_dates_default($startdate,$enddate));
                   2844:     }
                   2845:     # Determine domain and desired host (home server)
                   2846:     my $domain=$env{'request.role.domain'};
                   2847:     my $desiredhost = $env{'form.lcserver'};
                   2848:     if (lc($desiredhost) eq 'default') {
                   2849:         $desiredhost = undef;
                   2850:     } else {
                   2851:         my %home_servers = &Apache::lonnet::get_servers($domain,'library');
                   2852:         if (! exists($home_servers{$desiredhost})) {
                   2853:             $r->print('<span class="LC_error">'.&mt('Error').
                   2854:                       &mt('Invalid home server specified').'</span>');
                   2855:             $r->print(&Apache::loncommon::end_page());
                   2856:             return;
                   2857:         }
                   2858:     }
                   2859:     # Determine authentication mechanism
                   2860:     my $changeauth;
                   2861:     if ($context eq 'domain') {
                   2862:         $changeauth = $env{'form.changeauth'};
                   2863:     }
                   2864:     my $amode  = '';
                   2865:     my $genpwd = '';
                   2866:     if ($env{'form.login'} eq 'krb') {
                   2867:         $amode='krb';
                   2868:         $amode.=$env{'form.krbver'};
                   2869:         $genpwd=$env{'form.krbarg'};
                   2870:     } elsif ($env{'form.login'} eq 'int') {
                   2871:         $amode='internal';
                   2872:         if ((defined($env{'form.intarg'})) && ($env{'form.intarg'})) {
                   2873:             $genpwd=$env{'form.intarg'};
                   2874:         }
                   2875:     } elsif ($env{'form.login'} eq 'loc') {
                   2876:         $amode='localauth';
                   2877:         if ((defined($env{'form.locarg'})) && ($env{'form.locarg'})) {
                   2878:             $genpwd=$env{'form.locarg'};
                   2879:         }
                   2880:     }
                   2881:     if ($amode =~ /^krb/) {
                   2882:         if (! defined($genpwd) || $genpwd eq '') {
                   2883:             $r->print('<span class="Error">'.
                   2884:                       &mt('Unable to enroll users').' '.
                   2885:                       &mt('No Kerberos domain was specified.').'</span></p>');
                   2886:             $amode = ''; # This causes the loop below to be skipped
                   2887:         }
                   2888:     }
                   2889:     my ($cid,$defaultsec,$defaultrole,$setting);
                   2890:     if ($context eq 'domain') {
                   2891:         $setting = $env{'form.roleaction'};
                   2892:         if ($setting eq 'domain') {
                   2893:             $defaultrole = $env{'form.defaultrole'};
                   2894:         } elsif ($setting eq 'course') {
                   2895:             $defaultrole = $env{'form.courserole'};
                   2896:         }  
                   2897:     } elsif ($context eq 'construction_space') {
                   2898:         $defaultrole = $env{'form.defaultrole'};
                   2899:     }
                   2900:     if ($context eq 'domain' && $setting eq 'course') { 
                   2901:         if ($env{'form.newsec'} ne '') {
                   2902:             $defaultsec = $env{'form.newsec'};
                   2903:         } elsif ($env{'form.defaultsec'} ne '') {
                   2904:             $defaultsec = $env{'form.defaultsec'}
                   2905:         }
                   2906:     }
                   2907:     if ($env{'request.course.id'} ne '') {
                   2908:         $cid = $env{'request.course.id'};
                   2909:     } elsif ($env{'form.defaultdomain'} ne '' && $env{'form.defaultcourse'} ne '') {
                   2910:         $cid = $env{'form.defaultdomain'}.'_'.
                   2911:                $env{'form.defaultcourse'};
                   2912:     }
                   2913:     if ( $domain eq &LONCAPA::clean_domain($domain)
                   2914:         && ($amode ne '')) {
                   2915:         #######################################
                   2916:         ##         Add/Modify Users          ##
                   2917:         #######################################
                   2918:         if ($context eq 'course') {
                   2919:             $r->print('<h3>'.&mt('Enrolling Users')."</h3>\n<p>\n");
                   2920:         } elsif ($context eq 'construction_space') {
                   2921:             $r->print('<h3>'.&mt('Updating Co-authors')."</h3>\n<p>\n");
                   2922:         } else {
                   2923:             $r->print('<h3>'.&mt('Adding/Modifying Users')."</h3>\n<p>\n");
                   2924:         }
                   2925:         my %counts = (
                   2926:                        user => 0,
                   2927:                        auth => 0,
                   2928:                        role => 0,
                   2929:                      );
                   2930:         my $flushc=0;
                   2931:         my %student=();
                   2932:         my %curr_groups;
                   2933:         my %userchg;
                   2934:         if ($context eq 'course') {
                   2935:             # Get information about course groups
                   2936:             %curr_groups = &Apache::longroup::coursegroups();
                   2937:         }
1.5       raeburn  2938:         my (%curr_rules,%got_rules,%alerts);
1.1       raeburn  2939:         # Get new users list
                   2940:         foreach (@userdata) {
                   2941:             my %entries=&Apache::loncommon::record_sep($_);
                   2942:             # Determine user name
                   2943:             unless (($entries{$fields{'username'}} eq '') ||
                   2944:                     (!defined($entries{$fields{'username'}}))) {
                   2945:                 my ($fname, $mname, $lname,$gen) = ('','','','');
                   2946:                 if (defined($fields{'names'})) {
                   2947:                     ($lname,$fname,$mname)=($entries{$fields{'names'}}=~
                   2948:                                             /([^\,]+)\,\s*(\w+)\s*(.*)$/);
                   2949:                 } else {
                   2950:                     if (defined($fields{'fname'})) {
                   2951:                         $fname=$entries{$fields{'fname'}};
                   2952:                     }
                   2953:                     if (defined($fields{'mname'})) {
                   2954:                         $mname=$entries{$fields{'mname'}};
                   2955:                     }
                   2956:                     if (defined($fields{'lname'})) {
                   2957:                         $lname=$entries{$fields{'lname'}};
                   2958:                     }
                   2959:                     if (defined($fields{'gen'})) {
                   2960:                         $gen=$entries{$fields{'gen'}};
                   2961:                     }
                   2962:                 }
                   2963:                 if ($entries{$fields{'username'}}
                   2964:                     ne &LONCAPA::clean_username($entries{$fields{'username'}})) {
                   2965:                     $r->print('<br />'.
                   2966:       &mt('<b>[_1]</b>: Unacceptable username for user [_2] [_3] [_4] [_5]',
                   2967:           $entries{$fields{'username'}},$fname,$mname,$lname,$gen).
                   2968:                               '</b>');
                   2969:                 } else {
1.5       raeburn  2970:                     my $username = $entries{$fields{'username'}};
1.1       raeburn  2971:                     my $sec;
                   2972:                     if ($context eq 'course' || $setting eq 'course') {
                   2973:                         # determine section number
                   2974:                         if (defined($fields{'sec'})) {
                   2975:                             if (defined($entries{$fields{'sec'}})) {
                   2976:                                 $sec=$entries{$fields{'sec'}};
                   2977:                             }
                   2978:                         } else {
                   2979:                             $sec = $defaultsec;
                   2980:                         }
                   2981:                         # remove non alphanumeric values from section
                   2982:                         $sec =~ s/\W//g;
                   2983:                         if ($sec eq "none" || $sec eq 'all') {
                   2984:                             $r->print('<br />'.
                   2985:       &mt('<b>[_1]</b>: Unable to enroll: section name "[_2]" for user [_3] [_4] [_5] [_6] is a reserved word.',
                   2986:                                       $username,$sec,$fname,$mname,$lname,$gen));
                   2987:                             next;
                   2988:                         } elsif (($sec ne '') && (exists($curr_groups{$sec}))) {
                   2989:                             $r->print('<br />'.
                   2990:       &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.',
                   2991:                                       $username,$sec,$fname,$mname,$lname,$gen));
                   2992:                             next;
                   2993:                         }
                   2994:                     }
                   2995:                     # determine id number
                   2996:                     my $id='';
                   2997:                     if (defined($fields{'id'})) {
                   2998:                         if (defined($entries{$fields{'id'}})) {
                   2999:                             $id=$entries{$fields{'id'}};
                   3000:                         }
                   3001:                         $id=~tr/A-Z/a-z/;
                   3002:                     }
                   3003:                     # determine email address
                   3004:                     my $email='';
                   3005:                     if (defined($fields{'email'})) {
                   3006:                         if (defined($entries{$fields{'email'}})) {
                   3007:                             $email=$entries{$fields{'email'}};
                   3008:                             unless ($email=~/^[^\@]+\@[^\@]+$/) { $email=''; }                        }
                   3009:                     }
                   3010:                     # determine user password
                   3011:                     my $password = $genpwd;
                   3012:                     if (defined($fields{'ipwd'})) {
                   3013:                         if ($entries{$fields{'ipwd'}}) {
                   3014:                             $password=$entries{$fields{'ipwd'}};
                   3015:                         }
                   3016:                     }
                   3017:                     # determine user role
                   3018:                     my $role = '';
                   3019:                     if (defined($fields{'role'})) {
                   3020:                         if ($entries{$fields{'role'}}) {
1.2       raeburn  3021:                             my @poss_roles = 
1.1       raeburn  3022:                                  &curr_role_permissions($context,$setting);
1.2       raeburn  3023:                             if (grep(/^\Q$entries{$fields{'role'}}\E/,@poss_roles)) {
1.1       raeburn  3024:                                 $role=$entries{$fields{'role'}};
                   3025:                             } else {
                   3026:                                 my $rolestr = join(', ',@poss_roles);
                   3027:                                 $r->print('<br />'.
                   3028:       &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");
                   3029:                                 next;
                   3030:                             }
                   3031:                         }
                   3032:                     }
                   3033:                     if ($role eq '') {
                   3034:                         $role = $defaultrole;
                   3035:                     }
                   3036:                     # Clean up whitespace
                   3037:                     foreach (\$domain,\$username,\$id,\$fname,\$mname,
                   3038:                              \$lname,\$gen,\$sec,\$role) {
                   3039:                         $$_ =~ s/(\s+$|^\s+)//g;
                   3040:                     }
1.5       raeburn  3041:                     # check against rules
                   3042:                     my $checkid = 0;
                   3043:                     my $newuser = 0;
                   3044:                     my (%rulematch,%inst_results,%idinst_results);
                   3045:                     my $uhome=&Apache::lonnet::homeserver($username,$domain);
                   3046:                     if ($uhome eq 'no_host') {
                   3047:                         $checkid = 1;
                   3048:                         $newuser = 1;
                   3049:                         my $checkhash;
                   3050:                         my $checks = { 'username' => 1 };
                   3051:                         $checkhash->{$username.':'.$domain} = { 'newuser' => 1, };
                   3052:                         &Apache::loncommon::user_rule_check($checkhash,$checks,
                   3053:                             \%alerts,\%rulematch,\%inst_results,\%curr_rules,
                   3054:                             \%got_rules);
                   3055:                         if (ref($alerts{'username'}) eq 'HASH') {
                   3056:                             if (ref($alerts{'username'}{$domain}) eq 'HASH') {
                   3057:                                 next if ($alerts{'username'}{$domain}{$username});
                   3058:                             }
                   3059:                         }
                   3060:                     }
                   3061:                     if ($id ne '') {
                   3062:                         if (!$newuser) {
                   3063:                             my %idhash = &Apache::lonnet::idrget($domain,($username));
                   3064:                             if ($idhash{$username} ne $id) {
                   3065:                                 $checkid = 1;
                   3066:                             }
                   3067:                         }
                   3068:                         if ($checkid) {
                   3069:                             my $checkhash;
                   3070:                             my $checks = { 'id' => 1 };
                   3071:                             $checkhash->{$username.':'.$domain} = { 'newuser' => $newuser,
                   3072:                                                                     'id'  => $id };
                   3073:                             &Apache::loncommon::user_rule_check($checkhash,$checks,
                   3074:                                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,
                   3075:                                 \%got_rules);
                   3076:                             if (ref($alerts{'id'}) eq 'HASH') {
                   3077:                                 if (ref($alerts{'id'}{$domain}) eq 'HASH') {
                   3078:                                     next if ($alerts{'id'}{$domain}{$id});
                   3079:                                 }
                   3080:                             }
                   3081:                         }
                   3082:                     }
1.1       raeburn  3083:                     if ($password || $env{'form.login'} eq 'loc') {
                   3084:                         my ($userresult,$authresult,$roleresult);
                   3085:                         if ($role eq 'st') {
                   3086:                             &modifystudent($domain,$username,$cid,$sec,
                   3087:                                            $desiredhost);
                   3088:                             $roleresult = 
                   3089:                                 &Apache::lonnet::modifystudent
                   3090:                                     ($domain,$username,$id,$amode,$password,
                   3091:                                      $fname,$mname,$lname,$gen,$sec,$enddate,
                   3092:                                      $startdate,$env{'form.forceid'},
                   3093:                                      $desiredhost,$email);
                   3094:                         } else {
                   3095:                             ($userresult,$authresult,$roleresult) = 
                   3096:                                 &modifyuserrole($context,$setting,
                   3097:                                     $changeauth,$cid,$domain,$username, 
                   3098:                                     $id,$amode,$password,$fname,
                   3099:                                     $mname,$lname,$gen,$sec,
                   3100:                                     $env{'form.forceid'},$desiredhost,
1.5       raeburn  3101:                                     $email,$role,$enddate,$startdate,$checkid);
1.1       raeburn  3102:                         }
                   3103:                         $flushc = 
                   3104:                             &user_change_result($r,$userresult,$authresult,
                   3105:                                                 $roleresult,\%counts,$flushc,
                   3106:                                                 $username,%userchg);
                   3107:                     } else {
                   3108:                         if ($context eq 'course') {
                   3109:                             $r->print('<br />'. 
                   3110:       &mt('<b>[_1]</b>: Unable to enroll.  No password specified.',$username)
                   3111:                                      );
                   3112:                         } elsif ($context eq 'construction_space') {
                   3113:                             $r->print('<br />'.
                   3114:       &mt('<b>[_1]</b>: Unable to add co-author.  No password specified.',$username)
                   3115:                                      );
                   3116:                         } else {
                   3117:                             $r->print('<br />'.
                   3118:       &mt('<b>[_1]</b>: Unable to add user.  No password specified.',$username)
                   3119:                                      );
                   3120:                         }
                   3121:                     }
                   3122:                 }
                   3123:             }
                   3124:         } # end of foreach (@userdata)
                   3125:         # Flush the course logs so reverse user roles immediately updated
1.5       raeburn  3126:         &Apache::lonnet::flushcourselogs();
1.1       raeburn  3127:         $r->print("</p>\n<p>\n".&mt('Processed [_1] user(s).',$counts{'user'}).
                   3128:                   "</p>\n");
                   3129:         if ($counts{'role'} > 0) {
                   3130:             $r->print("<p>\n".
                   3131:                       &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");
                   3132:         }
                   3133:         if ($counts{'auth'} > 0) {
                   3134:             $r->print("<p>\n".
                   3135:                       &mt('Authentication changed for [_1] existing users.',
                   3136:                           $counts{'auth'})."</p>\n");
                   3137:         }
1.5       raeburn  3138:         if (keys(%alerts) > 0) {
                   3139:             if (ref($alerts{'username'}) eq 'HASH') {
                   3140:                 foreach my $dom (sort(keys(%{$alerts{'username'}}))) {
                   3141:                     my $count;
                   3142:                     if (ref($alerts{'username'}{$dom}) eq 'HASH') {
                   3143:                         $count = keys(%{$alerts{'username'}{$dom}});
                   3144:                     } 
                   3145:                     my $domdesc = &Apache::lonnet::domain($domain,'description');
                   3146:                     if (ref($curr_rules{$dom}) eq 'HASH') {
                   3147:                         $r->print(&Apache::loncommon::instrule_disallow_msg(
                   3148:                                  'username',$domdesc,$count,'upload'));
                   3149:                     }
                   3150:                     $r->print(&Apache::loncommon::user_rule_formats($dom,
                   3151:                               $domdesc,$curr_rules{$dom}{'username'},
                   3152:                              'username'));
                   3153:                 }
                   3154:             }
                   3155:             if (ref($alerts{'id'}) eq 'HASH') {
                   3156:                 foreach my $dom (sort(keys(%{$alerts{'id'}}))) {
                   3157:                     my $count;
                   3158:                     if (ref($alerts{'id'}{$dom}) eq 'HASH') {
                   3159:                         $count = keys(%{$alerts{'id'}{$dom}});
                   3160:                     }
                   3161:                     my $domdesc = &Apache::lonnet::domain($domain,'description');
                   3162:                     if (ref($curr_rules{$dom}) eq 'HASH') {
                   3163:                         $r->print(&Apache::loncommon::instrule_disallow_msg(
                   3164:                                  'id',$domdesc,$count,'upload'));
                   3165:                     }
                   3166:                     $r->print(&Apache::loncommon::user_rule_formats($dom,
                   3167:                               $domdesc,$curr_rules{$dom}{'id'},'id'));
                   3168:                 }
                   3169:             }
                   3170:         }
1.1       raeburn  3171:         $r->print('<form name="uploadresult" action="/adm/createuser">');
                   3172:         $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','prevphase','currstate']));
                   3173:         $r->print('</form>');
                   3174:         #####################################
                   3175:         #           Drop students           #
                   3176:         #####################################
                   3177:         if ($env{'form.fullup'} eq 'yes') {
                   3178:             $r->print('<h3>'.&mt('Dropping Students')."</h3>\n");
                   3179:             #  Get current classlist
                   3180:             my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
                   3181:             if (! defined($classlist)) {
                   3182:                 $r->print(&mt('There are no students currently enrolled.').
                   3183:                           "\n");
                   3184:             } else {
                   3185:                 # Remove the students we just added from the list of students.
                   3186:                 foreach (@userdata) {
                   3187:                     my %entries=&Apache::loncommon::record_sep($_);
                   3188:                     unless (($entries{$fields{'username'}} eq '') ||
                   3189:                             (!defined($entries{$fields{'username'}}))) {
                   3190:                         delete($classlist->{$entries{$fields{'username'}}.
                   3191:                                                 ':'.$domain});
                   3192:                     }
                   3193:                 }
                   3194:                 # Print out list of dropped students.
                   3195:                 &show_drop_list($r,$classlist,$keylist,'nosort');
                   3196:             }
                   3197:         }
                   3198:     } # end of unless
                   3199: }
                   3200: 
                   3201: sub user_change_result {
                   3202:     my ($r,$userresult,$authresult,$roleresult,$counts,$flushc,$username,
                   3203:         $userchg) = @_;
                   3204:     my $okresult = 0;
                   3205:     if ($userresult ne 'ok') {
                   3206:         if ($userresult =~ /^error:(.+)$/) {
                   3207:             my $error = $1;
                   3208:             $r->print('<br />'.
                   3209:                   &mt('<b>[_1]</b>:  Unable to add/modify: [_2]',$username,$error));
                   3210:         }
                   3211:     } else {
                   3212:         $counts->{'user'} ++;
                   3213:         $okresult = 1;
                   3214:     }
                   3215:     if ($authresult ne 'ok') {
                   3216:         if ($authresult =~ /^error:(.+)$/) {
                   3217:             my $error = $1;
                   3218:             $r->print('<br />'.
                   3219:                   &mt('<b>[_1]</b>:  Unable to modify authentication: [_2]',$username,$error));
                   3220:         } 
                   3221:     } else {
                   3222:         $counts->{'auth'} ++;
                   3223:         $okresult = 1;
                   3224:     }
                   3225:     if ($roleresult ne 'ok') {
                   3226:         if ($roleresult =~ /^error:(.+)$/) {
                   3227:             my $error = $1;
                   3228:             $r->print('<br />'.
                   3229:                   &mt('<b>[_1]</b>:  Unable to add role: [_2]',$username,$error));
                   3230:         }
                   3231:     } else {
                   3232:         $counts->{'role'} ++;
                   3233:         $okresult = 1;
                   3234:     }
                   3235:     if ($okresult) {
                   3236:         $flushc++;
                   3237:         $userchg->{$username}=1;
                   3238:         $r->print('. ');
                   3239:         if ($flushc>15) {
                   3240:             $r->rflush;
                   3241:             $flushc=0;
                   3242:         }
                   3243:     }
                   3244:     return $flushc;
                   3245: }
                   3246: 
                   3247: # ========================================================= Menu Phase Two Drop
                   3248: sub print_expire_menu {
                   3249:     my ($r,$context) = @_;
                   3250:     $r->print("<h3>".&mt("Expire Users' Roles")."</h3>");
                   3251:     my $cid=$env{'request.course.id'};
                   3252:     my ($classlist,$keylist) = &Apache::loncoursedata::get_classlist();
                   3253:     if (! defined($classlist)) {
                   3254:         $r->print(&mt('There are no students currently enrolled.')."\n");
                   3255:         return;
                   3256:     }
                   3257:     # Print out the available choices
                   3258:     &show_drop_list($r,$classlist,$keylist);
                   3259:     return;
                   3260: }
                   3261: 
                   3262: 
                   3263: # ================================================================== Phase four
                   3264: 
1.11    ! raeburn  3265: sub update_user_list {
        !          3266:     my ($r,$context,$setting,$choice) = @_;
        !          3267:     my $now = time;
1.1       raeburn  3268:     my $count=0;
1.11    ! raeburn  3269:     my @changelist;
        !          3270:     if ($choice ne '') {
        !          3271:         @changelist = &Apache::loncommon::get_env_multiple('form.actionlist');
        !          3272:     } else {
        !          3273:         @changelist = &Apache::loncommon::get_env_multiple('form.droplist');
        !          3274:     }
        !          3275:     my %result_text = ( ok    => { 'revoke'   => 'Revoked',
        !          3276:                                    'delete'   => 'Deleted',
        !          3277:                                    'reenable' => 'Re-enabled',
        !          3278:                                    'activate' => 'Activated', 
        !          3279:                                  },
        !          3280:                         error => {'revoke'    => 'revoking',
        !          3281:                                   'delete'    => 'deleting',
        !          3282:                                   'reenable'  => 're-enabling',
        !          3283:                                   'activate'  => 'activating',
        !          3284:                                  },
        !          3285:                       );
        !          3286:     my ($startdate,$enddate);
        !          3287:     if ($choice eq 'chgdates' || $choice eq 'reenable' || $choice eq 'activate') {
        !          3288:         ($startdate,$enddate) = &get_dates_from_form();
        !          3289:     }
        !          3290:     foreach my $item (@changelist) {
        !          3291:         my ($role,$uname,$udom,$cid,$sec,$scope,$result,$type,$locktype,@sections,
        !          3292:             $scopestem);
        !          3293:         if ($context eq 'course') {
        !          3294:             ($uname,$udom,$role,$sec,$type,$locktype) = split(/\:/,$item,-1);
        !          3295:             $cid = $env{'request.course.id'};
        !          3296:             $scopestem = '/'.$cid;
        !          3297:             $scopestem =~s/\_/\//g;
        !          3298:             if ($sec eq '') {
        !          3299:                 $scope = $scopestem;
        !          3300:             } else {
        !          3301:                 $scope = $scopestem.'/'.$sec;
        !          3302:             }
        !          3303:         } elsif ($context eq 'construction_space') {
        !          3304:             ($uname,$udom,$role) = split(/\:/,$item,-1);
        !          3305:             $scope = '/'.$env{'user.domain'}.'/'.$env{'user.name'};
        !          3306:         } elsif ($context eq 'domain') {
        !          3307:             if ($setting eq 'domain') {
        !          3308:                 ($role,$uname,$udom) = split(/\:/,$item,-1);
        !          3309:                 $scope = '/'.$env{'request.role.domain'}.'/';
        !          3310:             } elsif ($setting eq 'construction_space') { 
        !          3311:                 ($uname,$udom,$role,$scope) = split(/\:/,$item);
        !          3312:             } elsif ($setting eq 'course') {
        !          3313:                 ($uname,$udom,$role,$cid,$sec,$type,$locktype) = 
        !          3314:                     split(/\:/,$item);
        !          3315:                 $scope = '/'.$cid;
        !          3316:                 $scope =~s/\_/\//g;
        !          3317:                 if ($sec ne '') {
        !          3318:                     $scope .= '/'.$sec;
        !          3319:                 }
        !          3320:             }
        !          3321:         }
        !          3322:         my $plrole = &Apache::lonnet::plaintext($role);
        !          3323:         my ($uid,$first,$middle,$last,$gene,$sec);
        !          3324:         my $start = $env{'form.'.$item.'_start'};
        !          3325:         my $end = $env{'form.'.$item.'_end'};
        !          3326:         # revoke or delete user role
        !          3327:         if ($choice eq 'revoke') {
        !          3328:             $end = $now; 
        !          3329:             if ($role eq 'st') {
        !          3330:                 $result = 
        !          3331:                     &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid);
        !          3332:             } else {
        !          3333:                 $result = 
        !          3334:                     &Apache::lonnet::revokerole($udom,$uname,$scope,$role);
        !          3335:             }
        !          3336:         } elsif ($choice eq 'delete') {
        !          3337:             $start = -1;
        !          3338:             $end = -1;
        !          3339:             if ($role eq 'st') {
        !          3340: # FIXME - how does role deletion affect classlist?
        !          3341:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid);
        !          3342:             } else {
        !          3343:                 $result =
        !          3344:                     &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$now,
        !          3345:                                                 0,1);
        !          3346:              }
        !          3347:         } else {
        !          3348:             #reenable, activate, change access dates or change section
        !          3349:             if ($choice ne 'chgsec') {
        !          3350:                 $start = $startdate; 
        !          3351:                 $end = $enddate;
        !          3352:             }
        !          3353:             if ($choice eq 'reenable') {
        !          3354:                 if ($role eq 'st') {
        !          3355:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid);
        !          3356:                 } else {
        !          3357:                     $result = 
        !          3358:                         &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
        !          3359:                                                     $now);
        !          3360:                 }
        !          3361:             } elsif ($choice eq 'activate') {
        !          3362:                 if ($role eq 'st') {
        !          3363:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid);
        !          3364:                 } else {
        !          3365:                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
        !          3366:                                             $now);
        !          3367:                 }
        !          3368:             } elsif ($choice eq 'chgdates') {
        !          3369:                 if ($role eq 'st') {
        !          3370:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid);
        !          3371:                 } else {
        !          3372:                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
        !          3373:                                                 $start);
        !          3374:                 }
        !          3375:             } elsif ($choice eq 'chgsec') {
        !          3376:                 my (@newsecs,$revresult,$nochg,@retained);
        !          3377:                 if ($role ne 'cc') {
        !          3378:                     @newsecs = split(/,/,$env{'form.newsecs'});
        !          3379:                 }
        !          3380:                 # remove existing section if not to be retained.   
        !          3381:                 if (!$env{'form.retainsec'}) {
        !          3382:                     if ($sec eq '') {
        !          3383:                         if (@newsecs == 0) {
        !          3384:                             $result = &mt('No change in section assignment (none)');
        !          3385:                             $nochg = 1;
        !          3386:                         }
        !          3387:                     } else {
        !          3388:                         if (!grep(/^\Q$sec\E$/,@newsecs)) {
        !          3389:                             $revresult =
        !          3390:                                &Apache::lonnet::revokerole($udom,$uname,$scope,$role);
        !          3391:                         } else {
        !          3392:                             push(@retained,$sec);
        !          3393:                         }
        !          3394:                     }
        !          3395:                 } else {
        !          3396:                     push(@retained,$sec);
        !          3397:                 }
        !          3398:                 # add new sections
        !          3399:                 if (@newsecs == 0) {
        !          3400:                     if (!$nochg) {
        !          3401:                         if ($sec ne '') {
        !          3402:                             if ($role eq 'st') {
        !          3403:                                 $result = 
        !          3404:                                     &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,undef,$end,$start,$type,$locktype,$cid);
        !          3405:                             } else {
        !          3406:                                 my $newscope = $scopestem;
        !          3407:                                 $result = &Apache::lonnet::assignrole($udom,$uname,$newscope,$role,$end,$start);
        !          3408:                             }
        !          3409:                         }
        !          3410:                     }
        !          3411:                 } else {
        !          3412:                     foreach my $newsec (@newsecs) { 
        !          3413:                         if (!grep(/^\Q$newsec\E$/,@retained)) {
        !          3414:                             if ($role eq 'st') {
        !          3415:                                 $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$newsec,$end,$start,$type,$locktype,$cid);
        !          3416:                             } else {
        !          3417:                                 my $newscope = $scopestem;
        !          3418:                                 if ($newsec ne '') {
        !          3419:                                    $newscope .= '/'.$newsec;
        !          3420:                                 }
        !          3421:                                 $result = &Apache::lonnet::assignrole($udom,$uname,
        !          3422:                                                         $newscope,$role,$end,$start);
        !          3423:                             }
        !          3424:                         }
        !          3425:                     }
        !          3426:                 }
        !          3427:             }
        !          3428:         }
1.1       raeburn  3429:         if ($result eq 'ok' || $result eq 'ok:') {
1.11    ! raeburn  3430:             $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for [_3]",
        !          3431:                           $plrole,$scope,$uname.':'.$udom).'<br />');
1.1       raeburn  3432:             $count++;
                   3433:         } else {
                   3434:             $r->print(
1.11    ! raeburn  3435:                 &mt("Error $result_text{'error'}{$choice} [_1] in [_2] for [_3]:[_4]",
        !          3436:                     $plrole,$scope,$uname.':'.$udom,$result).'<br />');
        !          3437:         }
        !          3438:     }
        !          3439:     $r->print('<p><b>'.&mt("$result_text{'ok'}{$choice} role(s) for [quant,_1,user,users,users].",$count).'</b></p>');
        !          3440:     if ($count > 0) {
        !          3441:         if ($choice eq 'revoke') {
        !          3442:             $r->print('<p>'.&mt('Re-enabling will re-activate data for the role.</p>'));
        !          3443:         }
        !          3444:         # Flush the course logs so reverse user roles immediately updated
        !          3445:         &Apache::lonnet::flushcourselogs();
        !          3446:     }
        !          3447:     if ($env{'form.makedatesdefault'}) {
        !          3448:         if ($choice eq 'chgdates' || $choice eq 'reenable' || $choice eq 'activate') {
        !          3449:             $r->print(&make_dates_default($startdate,$enddate));
1.1       raeburn  3450:         }
                   3451:     }
                   3452: }
                   3453: 
1.8       raeburn  3454: sub classlist_drop {
                   3455:     my ($scope,$uname,$udom,$now,$action) = @_;
                   3456:     my ($cdom,$cnum) = ($scope=~m{^/($match_domain)/($match_courseid)});
                   3457:     my $cid=$cdom.'_'.$cnum;
                   3458:     my $user = $uname.':'.$udom;
                   3459:     if ($action eq 'drop') {
                   3460:         if (!&active_student_roles($cnum,$cdom,$uname,$udom)) {
                   3461:             my $result =
                   3462:                 &Apache::lonnet::cput('classlist',
                   3463:                                       { $user => $now },
                   3464:                                       $env{'course.'.$cid.'.domain'},
                   3465:                                       $env{'course.'.$cid.'.num'});
                   3466:             return &mt('Drop from classlist: [_1]',
                   3467:                        '<b>'.$result.'</b>').'<br />';
                   3468:         }
                   3469:     }
                   3470: }
                   3471: 
                   3472: sub active_student_roles {
                   3473:     my ($cnum,$cdom,$uname,$udom) = @_;
                   3474:     my %roles =
                   3475:         &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   3476:                                       ['future','active'],['st']);
                   3477:     return exists($roles{"$cnum:$cdom:st"});
                   3478: }
                   3479: 
1.1       raeburn  3480: sub section_check_js {
1.8       raeburn  3481:     my $groupslist= &get_groupslist();
1.1       raeburn  3482:     return <<"END";
                   3483: function validate(caller) {
1.9       raeburn  3484:     var groups = new Array($groupslist);
1.1       raeburn  3485:     var secname = caller.value;
                   3486:     if ((secname == 'all') || (secname == 'none')) {
                   3487:         alert("'"+secname+"' may not be used as the name for a section, as it is a reserved word.\\nPlease choose a different section name.");
                   3488:         return 'error';
                   3489:     }
                   3490:     if (secname != '') {
                   3491:         for (var k=0; k<groups.length; k++) {
                   3492:             if (secname == groups[k]) {
                   3493:                 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.");
                   3494:                 return 'error';
                   3495:             }
                   3496:         }
                   3497:     }
                   3498:     return 'ok';
                   3499: }
                   3500: END
                   3501: }
                   3502: 
                   3503: sub set_login {
                   3504:     my ($dom,$authformkrb,$authformint,$authformloc) = @_;
                   3505:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3506:     my $response;
                   3507:     my ($authnum,%can_assign) =
                   3508:         &Apache::loncommon::get_assignable_auth($dom);
                   3509:     if ($authnum) {
                   3510:         $response = &Apache::loncommon::start_data_table();
                   3511:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
                   3512:             $response .= &Apache::loncommon::start_data_table_row().
                   3513:                          '<td>'.$authformkrb.'</td>'.
                   3514:                          &Apache::loncommon::end_data_table_row()."\n";
                   3515:         }
                   3516:         if ($can_assign{'int'}) {
                   3517:             $response .= &Apache::loncommon::start_data_table_row().
                   3518:                          '<td>'.$authformint.'</td>'.
                   3519:                          &Apache::loncommon::end_data_table_row()."\n"
                   3520:         }
                   3521:         if ($can_assign{'loc'}) {
                   3522:             $response .= &Apache::loncommon::start_data_table_row().
                   3523:                          '<td>'.$authformloc.'</td>'.
                   3524:                          &Apache::loncommon::end_data_table_row()."\n";
                   3525:         }
                   3526:         $response .= &Apache::loncommon::end_data_table();
                   3527:     }
                   3528:     return $response;
                   3529: }
                   3530: 
1.8       raeburn  3531: sub course_sections {
                   3532:     my ($sections_count,$role) = @_;
                   3533:     my $output = '';
                   3534:     my @sections = (sort {$a <=> $b} keys %{$sections_count});
                   3535:     if (scalar(@sections) == 1) {
                   3536:         $output = '<select name="currsec_'.$role.'" >'."\n".
                   3537:                   '  <option value="">Select</option>'."\n".
                   3538:                   '  <option value="">No section</option>'."\n".
                   3539:                   '  <option value="'.$sections[0].'" >'.$sections[0].'</option>'."\n";
                   3540:     } else {
                   3541:         $output = '<select name="currsec_'.$role.'" ';
                   3542:         my $multiple = 4;
                   3543:         if (scalar(@sections) < 4) { $multiple = scalar(@sections); }
                   3544:         $output .= 'multiple="multiple" size="'.$multiple.'">'."\n";
                   3545:         foreach my $sec (@sections) {
                   3546:             $output .= '<option value="'.$sec.'">'.$sec."</option>\n";
                   3547:         }
                   3548:     }
                   3549:     $output .= '</select>';
                   3550:     return $output;
                   3551: }
                   3552: 
                   3553: sub get_groupslist {
                   3554:     my $groupslist;
                   3555:     my %curr_groups = &Apache::longroup::coursegroups();
                   3556:     if (%curr_groups) {
                   3557:         $groupslist = join('","',sort(keys(%curr_groups)));
                   3558:         $groupslist = '"'.$groupslist.'"';
                   3559:     }
1.11    ! raeburn  3560:     return $groupslist; 
1.8       raeburn  3561: }
                   3562: 
                   3563: sub setsections_javascript {
                   3564:     my ($form,$groupslist) = @_;
                   3565:     my ($checkincluded,$finish,$roleplace,$setsection_js);
                   3566:     if ($form eq 'cu') {
                   3567:         $checkincluded = 'formname.elements[i-1].checked == true';
                   3568:         $finish = 'formname.submit()';
                   3569:         $roleplace = 3;
                   3570:     } else {
1.11    ! raeburn  3571:         $checkincluded = 'formname.name == "'.$form.'"'; 
1.8       raeburn  3572:         $finish = "seccheck = 'ok';";
                   3573:         $roleplace = 1;
1.11    ! raeburn  3574:         $setsection_js = "var seccheck = 'alert';"; 
1.8       raeburn  3575:     }
                   3576:     my %alerts = &Apache::lonlocal::texthash(
                   3577:                     secd => 'Section designations do not apply to Course Coordinator roles.',
                   3578:                     accr => 'A course coordinator role will be added with access to all sections.',
                   3579:                     inea => 'In each course, each user may only have one student role at a time.',
                   3580:                     youh => 'You had selected ',
                   3581:                     secs => 'sections.',
                   3582:                     plmo => 'Please modify your selections so they include no more than one section.',
                   3583:                     mayn => 'may not be used as the name for a section, as it is a reserved word.',
                   3584:                     plch => 'Please choose a different section name.',
                   3585:                     mnot => 'may not be used as a section name, as it is the name of a course group.',
                   3586:                     secn => 'Section names and group names must be distinct. Please choose a different section name.',
1.11    ! raeburn  3587:                  );                
1.8       raeburn  3588:     $setsection_js .= <<"ENDSECCODE";
                   3589: 
                   3590: function setSections(formname) {
                   3591:     var re1 = /^currsec_/;
                   3592:     var groups = new Array($groupslist);
                   3593:     for (var i=0;i<formname.elements.length;i++) {
                   3594:         var str = formname.elements[i].name;
                   3595:         var checkcurr = str.match(re1);
                   3596:         if (checkcurr != null) {
                   3597:             if ($checkincluded) {
                   3598:                 var match = str.split('_');
                   3599:                 var role = match[$roleplace];
                   3600:                 if (role == 'cc') {
                   3601:                     alert("$alerts{'secd'}\\n$alerts{'accr'}");
                   3602:                 }
                   3603:                 else {
                   3604:                     var sections = '';
                   3605:                     var numsec = 0;
                   3606:                     var sections;
                   3607:                     for (var j=0; j<formname.elements[i].length; j++) {
                   3608:                         if (formname.elements[i].options[j].selected == true ) {
                   3609:                             if (formname.elements[i].options[j].value != "") {
                   3610:                                 if (numsec == 0) {
                   3611:                                     if (formname.elements[i].options[j].value != "") {
                   3612:                                         sections = formname.elements[i].options[j].value;
                   3613:                                         numsec ++;
                   3614:                                     }
                   3615:                                 }
                   3616:                                 else {
                   3617:                                     sections = sections + "," +  formname.elements[i].options[j].value
                   3618:                                     numsec ++;
                   3619:                                 }
                   3620:                             }
                   3621:                         }
                   3622:                     }
                   3623:                     if (numsec > 0) {
                   3624:                         if (formname.elements[i+1].value != "" && formname.elements[i+1].value != null) {
                   3625:                             sections = sections + "," +  formname.elements[i+1].value;
                   3626:                         }
                   3627:                     }
                   3628:                     else {
                   3629:                         sections = formname.elements[i+1].value;
                   3630:                     }
                   3631:                     var newsecs = formname.elements[i+1].value;
                   3632:                     var numsplit;
                   3633:                     if (newsecs != null && newsecs != "") {
                   3634:                         numsplit = newsecs.split(/,/g);
                   3635:                         numsec = numsec + numsplit.length;
                   3636:                     }
                   3637: 
                   3638:                     if ((role == 'st') && (numsec > 1)) {
                   3639:                         alert("$alerts{'inea'} $alerts{'youh'} "+numsec+" $alerts{'secs'}\\n$alerts{'plmo'}")
                   3640:                         return;
                   3641:                     }
                   3642:                     else {
                   3643:                         if (numsplit != null) {
                   3644:                             for (var j=0; j<numsplit.length; j++) {
                   3645:                                 if ((numsplit[j] == 'all') ||
                   3646:                                     (numsplit[j] == 'none')) {
                   3647:                                     alert("'"+numsplit[j]+"' $alerts{'mayn'}\\n$alerts{'plch'}");
                   3648:                                     return;
                   3649:                                 }
                   3650:                                 for (var k=0; k<groups.length; k++) {
                   3651:                                     if (numsplit[j] == groups[k]) {
                   3652:                                         alert("'"+numsplit[j]+"' $alerts{'mnot'}\\n$alerts{'secn'}");
                   3653:                                         return;
                   3654:                                     }
                   3655:                                 }
                   3656:                             }
                   3657:                         }
                   3658:                         formname.elements[i+2].value = sections;
                   3659:                     }
                   3660:                 }
                   3661:             }
                   3662:         }
                   3663:     }
                   3664:     $finish
                   3665: }
                   3666: ENDSECCODE
1.11    ! raeburn  3667:     return $setsection_js; 
1.8       raeburn  3668: }
                   3669: 
1.1       raeburn  3670: 1;
                   3671: 

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