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

1.1       raeburn     1: # The LearningOnline Network with CAPA
                      2: # Utility functions for managing LON-CAPA user accounts
                      3: #
1.53    ! raeburn     4: # $Id: lonuserutils.pm,v 1.52 2008/04/30 23:16:19 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 {
1.52      raeburn    45:     my ($udom,$unam,$courseid,$csec,$desiredhost,$context)=@_;
1.1       raeburn    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
1.17      raeburn    49:     my ($cnum,$cdom) = &get_course_identity($courseid);
1.1       raeburn    50:     my %roles = &Apache::lonnet::dump('roles',$udom,$unam);
                     51:     my ($tmp) = keys(%roles);
                     52:     # Bail out if we were unable to get the students roles
                     53:     return "$1" if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                     54:     # Go through the roles looking for enrollment in this course
                     55:     my $result = '';
                     56:     foreach my $course (keys(%roles)) {
                     57:         if ($course=~m{^/\Q$cdom\E/\Q$cnum\E(?:\/)*(?:\s+)*(\w+)*\_st$}) {
                     58:             # We are in this course
                     59:             my $section=$1;
                     60:             $section='' if ($course eq "/$cdom/$cnum".'_st');
                     61:             if (defined($csec) && $section eq $csec) {
                     62:                 $result .= 'ok:';
                     63:             } elsif ( ((!$section) && (!$csec)) || ($section ne $csec) ) {
                     64:                 my (undef,$end,$start)=split(/\_/,$roles{$course});
                     65:                 my $now=time;
                     66:                 # if this is an active role
                     67:                 if (!($start && ($now<$start)) || !($end && ($now>$end))) {
                     68:                     my $reply=&Apache::lonnet::modifystudent
                     69:                         # dom  name  id mode pass     f     m     l     g
                     70:                         ($udom,$unam,'',  '',  '',undef,undef,undef,undef,
1.22      raeburn    71:                          $section,time,undef,undef,$desiredhost,'','manual',
1.52      raeburn    72:                          '',$courseid,'',$context);
1.1       raeburn    73:                     $result .= $reply.':';
                     74:                 }
                     75:             }
                     76:         }
                     77:     }
                     78:     if ($result eq '') {
1.37      raeburn    79:         $result = &mt('Unable to find section for this student');
1.1       raeburn    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.13      raeburn    99:     } elsif ($context eq 'author') {
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.22      raeburn   130:             $role =~ s/_/\//g;
1.1       raeburn   131:             $roleresult = &Apache::lonnet::assignrole($udom,$uname,$scope,
1.52      raeburn   132:                                                       $role,$end,$start,'',
                    133:                                                       '',$context);
1.1       raeburn   134:         }
                    135:     }
1.5       raeburn   136:     return ($userresult,$authresult,$roleresult,$idresult);
1.1       raeburn   137: }
                    138: 
1.5       raeburn   139: sub propagate_id_change {
                    140:     my ($uname,$udom,$user) = @_;
1.12      raeburn   141:     my (@types,@roles);
1.5       raeburn   142:     @types = ('active','future');
                    143:     @roles = ('st');
                    144:     my $idresult;
                    145:     my %roleshash = &Apache::lonnet::get_my_roles($uname,
1.12      raeburn   146:                         $udom,'userroles',\@types,\@roles);
                    147:     my %args = (
                    148:                 one_time => 1,
                    149:                );
1.5       raeburn   150:     foreach my $item (keys(%roleshash)) {
1.22      raeburn   151:         my ($cnum,$cdom,$role) = split(/:/,$item,-1);
1.5       raeburn   152:         my ($start,$end) = split(/:/,$roleshash{$item});
                    153:         if (&Apache::lonnet::is_course($cdom,$cnum)) {
1.12      raeburn   154:             my $result = &update_classlist($cdom,$cnum,$udom,$uname,$user);
                    155:             my %coursehash = 
                    156:                 &Apache::lonnet::coursedescription($cdom.'_'.$cnum,\%args);
                    157:             my $cdesc = $coursehash{'description'};
                    158:             if ($cdesc eq '') { 
                    159:                 $cdesc = $cdom.'_'.$cnum;
                    160:             }
1.5       raeburn   161:             if ($result eq 'ok') {
1.12      raeburn   162:                 $idresult .= &mt('Classlist update for "[_1]" in "[_2]".',$uname.':'.$udom,$cdesc).'<br />'."\n";
1.5       raeburn   163:             } else {
1.12      raeburn   164:                 $idresult .= &mt('Error: "[_1]" during classlist update for "[_2]" in "[_3]".',$result,$uname.':'.$udom,$cdesc).'<br />'."\n";
1.5       raeburn   165:             }
                    166:         }
                    167:     }
                    168:     return $idresult;
                    169: }
                    170: 
                    171: sub update_classlist {
                    172:     my ($cdom,$cnum,$udom,$uname,$user) = @_;
1.6       albertel  173:     my ($uid,$classlistentry);
1.5       raeburn   174:     my $fullname =
                    175:         &Apache::lonnet::format_name($user->{'firstname'},$user->{'middlename'},
                    176:                                      $user->{'lastname'},$user->{'generation'},
                    177:                                      'lastname');
                    178:     my %classhash = &Apache::lonnet::get('classlist',[$uname.':'.$udom],
                    179:                                          $cdom,$cnum);
                    180:     my @classinfo = split(/:/,$classhash{$uname.':'.$udom});
                    181:     my $ididx=&Apache::loncoursedata::CL_ID() - 2;
                    182:     my $nameidx=&Apache::loncoursedata::CL_FULLNAME() - 2;
                    183:     for (my $i=0; $i<@classinfo; $i++) {
                    184:         if ($i == $ididx) {
                    185:             if (defined($user->{'id'})) {
                    186:                 $classlistentry .= $user->{'id'}.':';
                    187:             } else {
                    188:                 $classlistentry .= $classinfo[$i].':';
                    189:             }
                    190:         } elsif ($i == $nameidx) {
                    191:             $classlistentry .= $fullname.':';
                    192:         } else {
                    193:             $classlistentry .= $classinfo[$i].':';
                    194:         }
                    195:     }
                    196:     $classlistentry =~ s/:$//;
                    197:     my $reply=&Apache::lonnet::cput('classlist',
                    198:                                     {"$uname:$udom" => $classlistentry},
                    199:                                     $cdom,$cnum);
                    200:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                    201:         return 'ok';
                    202:     } else {
                    203:         return 'error: '.$reply;
                    204:     }
                    205: }
                    206: 
                    207: 
1.1       raeburn   208: ###############################################################
                    209: ###############################################################
1.2       raeburn   210: # build a role type and role selection form
                    211: sub domain_roles_select {
                    212:     # Set up the role type and role selection boxes when in 
                    213:     # domain context   
                    214:     #
                    215:     # Role types
1.13      raeburn   216:     my @roletypes = ('domain','author','course');
1.2       raeburn   217:     my %lt = &role_type_names();
1.1       raeburn   218:     #
                    219:     # build up the menu information to be passed to
                    220:     # &Apache::loncommon::linked_select_forms
                    221:     my %select_menus;
1.2       raeburn   222:     if ($env{'form.roletype'} eq '') {
                    223:         $env{'form.roletype'} = 'domain';
                    224:     }
                    225:     foreach my $roletype (@roletypes) {
1.1       raeburn   226:         # set up the text for this domain
1.2       raeburn   227:         $select_menus{$roletype}->{'text'}= $lt{$roletype};
1.1       raeburn   228:         # we want a choice of 'default' as the default in the second menu
1.2       raeburn   229:         if ($env{'form.roletype'} ne '') {
                    230:             $select_menus{$roletype}->{'default'} = $env{'form.showrole'};
                    231:         } else { 
                    232:             $select_menus{$roletype}->{'default'} = 'Any';
                    233:         }
1.1       raeburn   234:         # Now build up the other items in the second menu
1.2       raeburn   235:         my @roles;
                    236:         if ($roletype eq 'domain') {
                    237:             @roles = &domain_roles();
1.13      raeburn   238:         } elsif ($roletype eq 'author') {
1.2       raeburn   239:             @roles = &construction_space_roles();
                    240:         } else {
1.17      raeburn   241:             my $custom = 1;
                    242:             @roles = &course_roles('domain',undef,$custom);
1.1       raeburn   243:         }
1.2       raeburn   244:         my $order = ['Any',@roles];
                    245:         $select_menus{$roletype}->{'order'} = $order; 
                    246:         foreach my $role (@roles) {
1.5       raeburn   247:             if ($role eq 'cr') {
                    248:                 $select_menus{$roletype}->{'select2'}->{$role} =
                    249:                               &mt('Custom role');
                    250:             } else {
                    251:                 $select_menus{$roletype}->{'select2'}->{$role} = 
                    252:                               &Apache::lonnet::plaintext($role);
                    253:             }
1.2       raeburn   254:         }
                    255:         $select_menus{$roletype}->{'select2'}->{'Any'} = &mt('Any');
1.1       raeburn   256:     }
1.2       raeburn   257:     my $result = &Apache::loncommon::linked_select_forms
                    258:         ('studentform',('&nbsp;'x3).&mt('Role: '),$env{'form.roletype'},
1.13      raeburn   259:          'roletype','showrole',\%select_menus,['domain','author','course']);
1.1       raeburn   260:     return $result;
                    261: }
                    262: 
                    263: ###############################################################
                    264: ###############################################################
                    265: sub hidden_input {
                    266:     my ($name,$value) = @_;
                    267:     return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
                    268: }
                    269: 
                    270: sub print_upload_manager_header {
1.22      raeburn   271:     my ($r,$datatoken,$distotal,$krbdefdom,$context,$permission)=@_;
1.1       raeburn   272:     my $javascript;
                    273:     #
                    274:     if (! exists($env{'form.upfile_associate'})) {
                    275:         $env{'form.upfile_associate'} = 'forward';
                    276:     }
                    277:     if ($env{'form.associate'} eq 'Reverse Association') {
                    278:         if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                    279:             $env{'form.upfile_associate'} = 'reverse';
                    280:         } else {
                    281:             $env{'form.upfile_associate'} = 'forward';
                    282:         }
                    283:     }
                    284:     if ($env{'form.upfile_associate'} eq 'reverse') {
                    285:         $javascript=&upload_manager_javascript_reverse_associate();
                    286:     } else {
                    287:         $javascript=&upload_manager_javascript_forward_associate();
                    288:     }
                    289:     #
                    290:     # Deal with restored settings
                    291:     my $password_choice = '';
                    292:     if (exists($env{'form.ipwd_choice'}) &&
                    293:         $env{'form.ipwd_choice'} ne '') {
                    294:         # If a column was specified for password, assume it is for an
                    295:         # internal password.  This is a bug waiting to be filed (could be
                    296:         # local or krb auth instead of internal) but I do not have the
                    297:         # time to mess around with this now.
                    298:         $password_choice = 'int';
                    299:     }
                    300:     #
1.22      raeburn   301:     my $groupslist;
                    302:     if ($context eq 'course') {
                    303:         $groupslist = &get_groupslist();
                    304:     }
1.1       raeburn   305:     my $javascript_validations =
1.22      raeburn   306:         &javascript_validations('upload',$krbdefdom,$password_choice,undef,
                    307:                                 $env{'request.role.domain'},$context,
1.33      raeburn   308:                                 $groupslist);
1.1       raeburn   309:     my $checked=(($env{'form.noFirstLine'})?' checked="checked" ':'');
                    310:     $r->print(&mt('Total number of records found in file: <b>[_1]</b>.',$distotal).
                    311:               "<br />\n");
                    312:     $r->print('<div class="LC_left_float"><h3>'.
                    313:               &mt('Identify fields in uploaded list')."</h3>\n");
                    314:     $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");
                    315:     $r->print(&hidden_input('action','upload').
                    316:               &hidden_input('state','got_file').
                    317:               &hidden_input('associate','').
                    318:               &hidden_input('datatoken',$datatoken).
                    319:               &hidden_input('fileupload',$env{'form.fileupload'}).
                    320:               &hidden_input('upfiletype',$env{'form.upfiletype'}).
                    321:               &hidden_input('upfile_associate',$env{'form.upfile_associate'}));
                    322:     $r->print('<br /><input type="button" value="Reverse Association" '.
                    323:               'name="'.&mt('Reverse Association').'" '.
                    324:               'onClick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />');
                    325:     $r->print('<label><input type="checkbox" name="noFirstLine"'.$checked.'/>'.
                    326:               &mt('Ignore First Line').'</label>');
                    327:     $r->print("<br /><br />\n".
                    328:               '<script type="text/javascript" language="Javascript">'."\n".
                    329:               $javascript."\n".$javascript_validations.'</script>');
                    330: }
                    331: 
                    332: ###############################################################
                    333: ###############################################################
                    334: sub javascript_validations {
1.22      raeburn   335:     my ($mode,$krbdefdom,$curr_authtype,$curr_authfield,$domain,
1.33      raeburn   336:         $context,$groupslist)=@_;
1.22      raeburn   337:     my %param = (
                    338:                   kerb_def_dom => $krbdefdom,
                    339:                   curr_authtype => $curr_authtype,
                    340:                 );
1.37      raeburn   341:     if ($mode eq 'upload') {
1.22      raeburn   342:         $param{'formname'} = 'studentform';
1.1       raeburn   343:     } elsif ($mode eq 'createcourse') {
1.22      raeburn   344:         $param{'formname'} = 'ccrs';
1.1       raeburn   345:     } elsif ($mode eq 'modifycourse') {
1.22      raeburn   346:         $param{'formname'} = 'cmod';
                    347:         $param{'mode'} = 'modifycourse',
                    348:         $param{'curr_autharg'} = $curr_authfield;
                    349:     }
                    350: 
                    351:     my ($setsection_call,$setsections_js);
                    352:     my $finish = "  vf.submit();\n";
                    353:     if ($mode eq 'upload') {
                    354:         if (($context eq 'course') || ($context eq 'domain')) {
                    355:             if ($context eq 'course') {
                    356:                 if ($env{'request.course.sec'} eq '') {
                    357:                     $setsection_call = 'setSections(document.'.$param{'formname'}.');';
                    358:                     $setsections_js =
                    359:                         &setsections_javascript($param{'formname'},$groupslist,
                    360:                                                 $mode);
                    361:                 } else {
                    362:                     $setsection_call = "'ok'";
                    363:                 }
                    364:             } elsif ($context eq 'domain') {
                    365:                 $setsection_call = 'setCourse()';
1.37      raeburn   366:                 $setsections_js = &dc_setcourse_js($param{'formname'},$mode,$context);
1.22      raeburn   367:             }
                    368:             $finish = "  var checkSec = $setsection_call\n".
                    369:                       "  if (checkSec == 'ok') {\n".
                    370:                       "      vf.submit();\n".
                    371:                       "   }\n";
                    372:         }
1.1       raeburn   373:     }
1.22      raeburn   374:     my $authheader = &Apache::loncommon::authform_header(%param);
1.1       raeburn   375: 
                    376:     my %alert = &Apache::lonlocal::texthash
                    377:         (username => 'You need to specify the username field.',
                    378:          authen   => 'You must choose an authentication type.',
                    379:          krb      => 'You need to specify the Kerberos domain.',
                    380:          ipass    => 'You need to specify the initial password.',
                    381:          name     => 'The optional name field was not specified.',
                    382:          snum     => 'The optional ID number field was not specified.',
                    383:          section  => 'The optional section field was not specified.',
                    384:          email    => 'The optional email address field was not specified.',
                    385:          role     => 'The optional role field was not specified.',
                    386:          continue => 'Continue adding users?',
                    387:          );
1.37      raeburn   388:     my $function_name = <<"END";
1.22      raeburn   389: $setsections_js
                    390: 
1.1       raeburn   391: function verify_message (vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail) {
                    392: END
                    393:     my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($domain);
                    394:     my $auth_checks;
                    395:     if ($mode eq 'createcourse') {
                    396:         $auth_checks .= (<<END);
                    397:     if (vf.autoadds[0].checked == true) {
                    398:         if (current.radiovalue == null || current.radiovalue == 'nochange') {
                    399:             alert('$alert{'authen'}');
                    400:             return;
                    401:         }
                    402:     }
                    403: END
                    404:     } else {
                    405:         $auth_checks .= (<<END);
                    406:     var foundatype=0;
                    407:     if (founduname==0) {
                    408:         alert('$alert{'username'}');
                    409:         return;
                    410:     }
                    411: 
                    412: END
                    413:         if ($authnum > 1) {
                    414:             $auth_checks .= (<<END);
                    415:     if (current.radiovalue == null || current.radiovalue == '' || current.radiovalue == 'nochange') {
                    416:         // They did not check any of the login radiobuttons.
                    417:         alert('$alert{'authen'}');
                    418:         return;
                    419:     }
                    420: END
                    421:         }
                    422:     }
                    423:     if ($mode eq 'createcourse') {
                    424:         $auth_checks .= "
                    425:     if ( (vf.autoadds[0].checked == true) &&
                    426:          (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') ) {
                    427: ";
                    428:     } elsif ($mode eq 'modifycourse') {
                    429:         $auth_checks .= "
                    430:     if (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') {
                    431: ";
                    432:     }
                    433:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
                    434:         $auth_checks .= (<<END);
                    435:         var alertmsg = '';
                    436:         switch (current.radiovalue) {
                    437:             case 'krb':
                    438:                 alertmsg = '$alert{'krb'}';
                    439:                 break;
                    440:             default:
                    441:                 alertmsg = '';
                    442:         }
                    443:         if (alertmsg != '') {
                    444:             alert(alertmsg);
                    445:             return;
                    446:         }
                    447:     }
                    448: END
                    449:     } else {
                    450:         $auth_checks .= (<<END);
                    451:     foundatype=1;
                    452:     if (current.argfield == null || current.argfield == '') {
                    453:         var alertmsg = '';
1.38      raeburn   454:         switch (current.radiovalue) {
1.1       raeburn   455:             case 'krb':
                    456:                 alertmsg = '$alert{'krb'}';
                    457:                 break;
                    458:             case 'loc':
                    459:             case 'fsys':
                    460:                 alertmsg = '$alert{'ipass'}';
                    461:                 break;
                    462:             case 'fsys':
                    463:                 alertmsg = '';
                    464:                 break;
                    465:             default:
                    466:                 alertmsg = '';
                    467:         }
                    468:         if (alertmsg != '') {
                    469:             alert(alertmsg);
                    470:             return;
                    471:         }
                    472:     }
                    473: END
                    474:     }
                    475:     my $section_checks;
                    476:     my $optional_checks = '';
                    477:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
                    478:         $optional_checks = (<<END);
                    479:     vf.submit();
                    480: }
                    481: END
                    482:     } else {
                    483:         $section_checks = &section_check_js();
                    484:         $optional_checks = (<<END);
                    485:     var message='';
                    486:     if (foundname==0) {
                    487:         message='$alert{'name'}';
                    488:     }
                    489:     if (foundid==0) {
                    490:         if (message!='') {
                    491:             message+='\\n';
                    492:         }
                    493:         message+='$alert{'snum'}';
                    494:     }
                    495:     if (foundsec==0) {
                    496:         if (message!='') {
                    497:             message+='\\n';
                    498:         }
                    499:     }
                    500:     if (foundemail==0) {
                    501:         if (message!='') {
                    502:             message+='\\n';
                    503:         }
                    504:         message+='$alert{'email'}';
                    505:     }
                    506:     if (message!='') {
                    507:         message+= '\\n$alert{'continue'}';
                    508:         if (confirm(message)) {
                    509:             vf.state.value='enrolling';
1.22      raeburn   510:             $finish
1.1       raeburn   511:         }
                    512:     } else {
                    513:         vf.state.value='enrolling';
1.22      raeburn   514:         $finish
1.1       raeburn   515:     }
                    516: }
                    517: END
                    518:     }
1.37      raeburn   519:     my $result = $function_name.$auth_checks.$optional_checks."\n".
                    520:                  $section_checks.$authheader;
1.1       raeburn   521:     return $result;
                    522: }
                    523: ###############################################################
                    524: ###############################################################
                    525: sub upload_manager_javascript_forward_associate {
                    526:     return(<<ENDPICK);
                    527: function verify(vf,sec_caller) {
                    528:     var founduname=0;
                    529:     var foundpwd=0;
                    530:     var foundname=0;
                    531:     var foundid=0;
                    532:     var foundsec=0;
                    533:     var foundemail=0;
                    534:     var foundrole=0;
                    535:     var tw;
                    536:     for (i=0;i<=vf.nfields.value;i++) {
                    537:         tw=eval('vf.f'+i+'.selectedIndex');
                    538:         if (tw==1) { founduname=1; }
                    539:         if ((tw>=2) && (tw<=6)) { foundname=1; }
                    540:         if (tw==7) { foundid=1; }
                    541:         if (tw==8) { foundsec=1; }
                    542:         if (tw==9) { foundpwd=1; }
                    543:         if (tw==10) { foundemail=1; }
                    544:         if (tw==11) { foundrole=1; }
                    545:     }
                    546:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole);
                    547: }
                    548: 
                    549: //
                    550: // vf = this.form
                    551: // tf = column number
                    552: //
                    553: // values of nw
                    554: //
                    555: // 0 = none
                    556: // 1 = username
                    557: // 2 = names (lastname, firstnames)
                    558: // 3 = fname (firstname)
                    559: // 4 = mname (middlename)
                    560: // 5 = lname (lastname)
                    561: // 6 = gen   (generation)
                    562: // 7 = id
                    563: // 8 = section
                    564: // 9 = ipwd  (password)
                    565: // 10 = email address
                    566: // 11 = role
                    567: 
                    568: function flip(vf,tf) {
                    569:    var nw=eval('vf.f'+tf+'.selectedIndex');
                    570:    var i;
                    571:    // make sure no other columns are labeled the same as this one
                    572:    for (i=0;i<=vf.nfields.value;i++) {
                    573:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                    574:           eval('vf.f'+i+'.selectedIndex=0;')
                    575:       }
                    576:    }
                    577:    // If we set this to 'lastname, firstnames', clear out all the ones
                    578:    // set to 'fname','mname','lname','gen' (3,4,5,6) currently.
                    579:    if (nw==2) {
                    580:       for (i=0;i<=vf.nfields.value;i++) {
                    581:          if ((eval('vf.f'+i+'.selectedIndex')>=3) &&
                    582:              (eval('vf.f'+i+'.selectedIndex')<=6)) {
                    583:              eval('vf.f'+i+'.selectedIndex=0;')
                    584:          }
                    585:       }
                    586:    }
                    587:    // If we set this to one of 'fname','mname','lname','gen' (3,4,5,6),
                    588:    // clear out any that are set to 'lastname, firstnames' (2)
                    589:    if ((nw>=3) && (nw<=6)) {
                    590:       for (i=0;i<=vf.nfields.value;i++) {
                    591:          if (eval('vf.f'+i+'.selectedIndex')==2) {
                    592:              eval('vf.f'+i+'.selectedIndex=0;')
                    593:          }
                    594:       }
                    595:    }
                    596:    // If we set the password, make the password form below correspond to
                    597:    // the new value.
                    598:    if (nw==9) {
                    599:        changed_radio('int',document.studentform);
                    600:        set_auth_radio_buttons('int',document.studentform);
                    601:        vf.intarg.value='';
                    602:        vf.krbarg.value='';
                    603:        vf.locarg.value='';
                    604:    }
                    605: }
                    606: 
                    607: function clearpwd(vf) {
                    608:     var i;
                    609:     for (i=0;i<=vf.nfields.value;i++) {
                    610:         if (eval('vf.f'+i+'.selectedIndex')==9) {
                    611:             eval('vf.f'+i+'.selectedIndex=0;')
                    612:         }
                    613:     }
                    614: }
                    615: 
                    616: ENDPICK
                    617: }
                    618: 
                    619: ###############################################################
                    620: ###############################################################
                    621: sub upload_manager_javascript_reverse_associate {
                    622:     return(<<ENDPICK);
                    623: function verify(vf,sec_caller) {
                    624:     var founduname=0;
                    625:     var foundpwd=0;
                    626:     var foundname=0;
                    627:     var foundid=0;
                    628:     var foundsec=0;
                    629:     var foundrole=0;
                    630:     var tw;
                    631:     for (i=0;i<=vf.nfields.value;i++) {
                    632:         tw=eval('vf.f'+i+'.selectedIndex');
                    633:         if (i==0 && tw!=0) { founduname=1; }
                    634:         if (((i>=1) && (i<=5)) && tw!=0 ) { foundname=1; }
                    635:         if (i==6 && tw!=0) { foundid=1; }
                    636:         if (i==7 && tw!=0) { foundsec=1; }
                    637:         if (i==8 && tw!=0) { foundpwd=1; }
                    638:         if (i==9 && tw!=0) { foundrole=1; }
                    639:     }
                    640:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundrole);
                    641: }
                    642: 
                    643: function flip(vf,tf) {
                    644:    var nw=eval('vf.f'+tf+'.selectedIndex');
                    645:    var i;
                    646:    // picked the all one name field, reset the other name ones to blank
                    647:    if (tf==1 && nw!=0) {
                    648:       for (i=2;i<=5;i++) {
                    649:          eval('vf.f'+i+'.selectedIndex=0;')
                    650:       }
                    651:    }
                    652:    //picked one of the piecewise name fields, reset the all in
                    653:    //one field to blank
                    654:    if ((tf>=2) && (tf<=5) && (nw!=0)) {
                    655:       eval('vf.f1.selectedIndex=0;')
                    656:    }
                    657:    // intial password specified, pick internal authentication
                    658:    if (tf==8 && nw!=0) {
                    659:        changed_radio('int',document.studentform);
                    660:        set_auth_radio_buttons('int',document.studentform);
                    661:        vf.krbarg.value='';
                    662:        vf.intarg.value='';
                    663:        vf.locarg.value='';
                    664:    }
                    665: }
                    666: 
                    667: function clearpwd(vf) {
                    668:     var i;
                    669:     if (eval('vf.f8.selectedIndex')!=0) {
                    670:         eval('vf.f8.selectedIndex=0;')
                    671:     }
                    672: }
                    673: ENDPICK
                    674: }
                    675: 
                    676: ###############################################################
                    677: ###############################################################
                    678: sub print_upload_manager_footer {
1.22      raeburn   679:     my ($r,$i,$keyfields,$defdom,$today,$halfyear,$context,$permission) = @_;
                    680:     my $form = 'document.studentform';
                    681:     my $formname = 'studentform';
1.1       raeburn   682:     my ($krbdef,$krbdefdom) =
                    683:         &Apache::loncommon::get_kerberos_defaults($defdom);
1.22      raeburn   684:     my %param = ( formname => $form,
1.1       raeburn   685:                   kerb_def_dom => $krbdefdom,
                    686:                   kerb_def_auth => $krbdef
                    687:                   );
                    688:     if (exists($env{'form.ipwd_choice'}) &&
                    689:         defined($env{'form.ipwd_choice'}) &&
                    690:         $env{'form.ipwd_choice'} ne '') {
                    691:         $param{'curr_authtype'} = 'int';
                    692:     }
                    693:     my $krbform = &Apache::loncommon::authform_kerberos(%param);
                    694:     my $intform = &Apache::loncommon::authform_internal(%param);
                    695:     my $locform = &Apache::loncommon::authform_local(%param);
1.22      raeburn   696:     my $date_table = &date_setting_table(undef,undef,$context,undef,
                    697:                                          $formname,$permission);
1.1       raeburn   698:     my $Str = "\n".'<div class="LC_left_float">';
                    699:     $Str .= &hidden_input('nfields',$i);
                    700:     $Str .= &hidden_input('keyfields',$keyfields);
                    701:     $Str .= "<h3>".&mt('Login Type')."</h3>\n";
                    702:     if ($context eq 'domain') {
                    703:         $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>'; 
                    704:     } else {
                    705:         $Str .= "<p>\n".
                    706:             &mt('Note: this will not take effect if the user already exists').
                    707:             &Apache::loncommon::help_open_topic('Auth_Options').
                    708:             "</p>\n";
                    709:     }
                    710:     $Str .= &set_login($defdom,$krbform,$intform,$locform);
                    711:     my ($home_server_pick,$numlib) =
                    712:         &Apache::loncommon::home_server_form_item($defdom,'lcserver',
                    713:                                                   'default','hide');
                    714:     if ($numlib > 1) {
                    715:         $Str .= '<h3>'.&mt('LON-CAPA Home Server for New Users')."</h3>\n".
                    716:                 &mt('LON-CAPA domain: [_1] with home server: [_2]',$defdom,
                    717:                 $home_server_pick).'<br />';
                    718:     } else {
                    719:         $Str .= $home_server_pick;
                    720:     }
                    721:     $Str .= '<h3>'.&mt('Starting and Ending Dates').
                    722:             "</h3>\n";
                    723:     $Str .= "<p>\n".$date_table."</p>\n";
                    724:     if ($context eq 'domain') {
                    725:         $Str .= '<h3>'.&mt('Settings for assigning roles:').'</h3>'."\n".
                    726:                 &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>';
                    727:     }
1.13      raeburn   728:     if ($context eq 'author') {
1.1       raeburn   729:         $Str .= '<h3>'.&mt('Default role')."</h3>\n".
1.25      raeburn   730:                 &mt('Choose the role to assign to users without a value specified in the uploaded file');
1.1       raeburn   731:     } elsif ($context eq 'course') {
                    732:         $Str .= '<h3>'.&mt('Default role and section')."</h3>\n".
1.25      raeburn   733:                 &mt('Choose the role and/or section(s) to assign to users without values specified in the uploaded file');
1.1       raeburn   734:     } else {
1.25      raeburn   735:         $Str .= '<br /><br /><b>'.&mt('Default role and/or section(s)')."</b><br />\n".
                    736:                 &mt('Role and/or section(s) for users without values specified in the uploaded file.');
1.1       raeburn   737:     }
1.22      raeburn   738:     $Str .= '<br />';
                    739:     if (($context eq 'domain') || ($context eq 'author')) {
                    740:         my ($options,$cb_script,$coursepick) = &default_role_selector($context,1);
                    741:         if ($context eq 'domain') {
                    742:             $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;
                    743:         } elsif ($context eq 'author') {
                    744:             $Str .= $options;
                    745:         }
1.1       raeburn   746:     } else {
1.22      raeburn   747:         my ($cnum,$cdom) = &get_course_identity();
                    748:         my $rowtitle = &mt('section');
                    749:         my $secbox = &section_picker($cdom,$cnum,'Any',$rowtitle,
                    750:                                      $permission,$context,'upload');
                    751:         $Str .= $secbox."<h3>".&mt('Full Update')."</h3>\n".
                    752:                 '<p><label><input type="checkbox" name="fullup" value="yes">'.
1.36      raeburn   753:                 ' '.&mt('Display students with current/future access who are not in the uploaded file.').'</label><br />'.&mt('Students selected from this list can be dropped.').'</p>'."\n";
1.1       raeburn   754:     }
1.5       raeburn   755:     if ($context eq 'course' || $context eq 'domain') {
                    756:         $Str .= &forceid_change($context);
                    757:     }
1.1       raeburn   758:     $Str .= '</div><div class="LC_clear_float_footer"><br /><input type="button"'.
                    759:               'onClick="javascript:verify(this.form,this.form.csec)" '.
                    760:         'value="Update Users" />'."<br />\n";
                    761:     if ($context eq 'course') {
                    762:         $Str .= &mt('Note: for large courses, this operation may be time '.
                    763:                     'consuming');
                    764:     }
                    765:     $Str .= '</div>';
                    766:     $r->print($Str);
                    767:     return;
                    768: }
                    769: 
1.5       raeburn   770: sub forceid_change {
                    771:     my ($context) = @_;
                    772:     my $output = 
                    773:         "<h3>".&mt('ID/Student Number')."</h3>\n".
                    774:         "<p>\n".'<label><input type="checkbox" name="forceid" value="yes">'.
                    775:         &mt('Disable ID/Student Number Safeguard and Force Change '.
                    776:         'of Conflicting IDs').'</label><br />'."\n".
1.25      raeburn   777:         &mt('(only do if you know what you are doing.)')."\n";
1.5       raeburn   778:     if ($context eq 'domain') {
1.25      raeburn   779:         $output .= '<br /><label><input type="checkbox" name="recurseid"'.
1.5       raeburn   780:                    ' value="yes">'. 
1.13      raeburn   781:   &mt('Update ID/Student Number in courses in which user is Active/Future student,<br />(if forcing change).').
1.25      raeburn   782:                    '</label>'."\n";
1.5       raeburn   783:     }
1.25      raeburn   784:     $output .= '</p>';
1.5       raeburn   785:     return $output;
                    786: }
                    787: 
1.1       raeburn   788: ###############################################################
                    789: ###############################################################
                    790: sub print_upload_manager_form {
1.21      raeburn   791:     my ($r,$context,$permission) = @_;
1.1       raeburn   792:     my $firstLine;
                    793:     my $datatoken;
                    794:     if (!$env{'form.datatoken'}) {
                    795:         $datatoken=&Apache::loncommon::upfile_store($r);
                    796:     } else {
                    797:         $datatoken=$env{'form.datatoken'};
                    798:         &Apache::loncommon::load_tmp_file($r);
                    799:     }
                    800:     my @records=&Apache::loncommon::upfile_record_sep();
                    801:     if($env{'form.noFirstLine'}){
                    802:         $firstLine=shift(@records);
                    803:     }
                    804:     my $total=$#records;
                    805:     my $distotal=$total+1;
                    806:     my $today=time;
                    807:     my $halfyear=$today+15552000;
                    808:     #
                    809:     # Restore memorized settings
                    810:     my $col_setting_names =  { 'username_choice' => 'scalar', # column settings
                    811:                                'names_choice' => 'scalar',
                    812:                                'fname_choice' => 'scalar',
                    813:                                'mname_choice' => 'scalar',
                    814:                                'lname_choice' => 'scalar',
                    815:                                'gen_choice' => 'scalar',
                    816:                                'id_choice' => 'scalar',
                    817:                                'sec_choice' => 'scalar',
                    818:                                'ipwd_choice' => 'scalar',
                    819:                                'email_choice' => 'scalar',
                    820:                                'role_choice' => 'scalar',
                    821:                              };
                    822:     my $defdom = $env{'request.role.domain'};
                    823:     if ($context eq 'course') {
                    824:         &Apache::loncommon::restore_course_settings('enrollment_upload',
                    825:                                                     $col_setting_names);
                    826:     } else {
                    827:         &Apache::loncommon::restore_settings($context,'user_upload',
                    828:                                              $col_setting_names);
                    829:     }
                    830:     #
                    831:     # Determine kerberos parameters as appropriate
                    832:     my ($krbdef,$krbdefdom) =
                    833:         &Apache::loncommon::get_kerberos_defaults($defdom);
                    834:     #
1.22      raeburn   835:     &print_upload_manager_header($r,$datatoken,$distotal,$krbdefdom,$context,
                    836:                                  $permission);
1.1       raeburn   837:     my $i;
                    838:     my $keyfields;
                    839:     if ($total>=0) {
                    840:         my @field=
                    841:             (['username',&mt('Username'),     $env{'form.username_choice'}],
                    842:              ['names',&mt('Last Name, First Names'),$env{'form.names_choice'}],
                    843:              ['fname',&mt('First Name'),      $env{'form.fname_choice'}],
                    844:              ['mname',&mt('Middle Names/Initials'),$env{'form.mname_choice'}],
                    845:              ['lname',&mt('Last Name'),       $env{'form.lname_choice'}],
                    846:              ['gen',  &mt('Generation'),      $env{'form.gen_choice'}],
                    847:              ['id',   &mt('ID/Student Number'),$env{'form.id_choice'}],
                    848:              ['sec',  &mt('Section'),          $env{'form.sec_choice'}],
                    849:              ['ipwd', &mt('Initial Password'),$env{'form.ipwd_choice'}],
                    850:              ['email',&mt('E-mail Address'),   $env{'form.email_choice'}],
                    851:              ['role',&mt('Role'),             $env{'form.role_choice'}]);
                    852:         if ($env{'form.upfile_associate'} eq 'reverse') {
                    853:             &Apache::loncommon::csv_print_samples($r,\@records);
                    854:             $i=&Apache::loncommon::csv_print_select_table($r,\@records,
                    855:                                                           \@field);
                    856:             foreach (@field) {
                    857:                 $keyfields.=$_->[0].',';
                    858:             }
                    859:             chop($keyfields);
                    860:         } else {
                    861:             unshift(@field,['none','']);
                    862:             $i=&Apache::loncommon::csv_samples_select_table($r,\@records,
                    863:                                                             \@field);
                    864:             my %sone=&Apache::loncommon::record_sep($records[0]);
                    865:             $keyfields=join(',',sort(keys(%sone)));
                    866:         }
                    867:     }
                    868:     $r->print('</div>');
                    869:     &print_upload_manager_footer($r,$i,$keyfields,$defdom,$today,$halfyear,
1.22      raeburn   870:                                  $context,$permission);
1.1       raeburn   871: }
                    872: 
                    873: sub setup_date_selectors {
1.22      raeburn   874:     my ($starttime,$endtime,$mode,$nolink,$formname) = @_;
                    875:     if ($formname eq '') {
                    876:         $formname = 'studentform';
                    877:     }
1.1       raeburn   878:     if (! defined($starttime)) {
                    879:         $starttime = time;
                    880:         unless ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
                    881:             if (exists($env{'course.'.$env{'request.course.id'}.
                    882:                             '.default_enrollment_start_date'})) {
                    883:                 $starttime = $env{'course.'.$env{'request.course.id'}.
                    884:                                   '.default_enrollment_start_date'};
                    885:             }
                    886:         }
                    887:     }
                    888:     if (! defined($endtime)) {
                    889:         $endtime = time+(6*30*24*60*60); # 6 months from now, approx
                    890:         unless ($mode eq 'createcourse') {
                    891:             if (exists($env{'course.'.$env{'request.course.id'}.
                    892:                             '.default_enrollment_end_date'})) {
                    893:                 $endtime = $env{'course.'.$env{'request.course.id'}.
                    894:                                 '.default_enrollment_end_date'};
                    895:             }
                    896:         }
                    897:     }
1.11      raeburn   898: 
                    899:     my $startdateform = 
1.22      raeburn   900:         &Apache::lonhtmlcommon::date_setter($formname,'startdate',$starttime,
1.11      raeburn   901:             undef,undef,undef,undef,undef,undef,undef,$nolink);
                    902: 
                    903:     my $enddateform = 
1.22      raeburn   904:         &Apache::lonhtmlcommon::date_setter($formname,'enddate',$endtime,
1.11      raeburn   905:             undef,undef,undef,undef,undef,undef,undef,$nolink);
                    906: 
1.1       raeburn   907:     if ($mode eq 'create_enrolldates') {
                    908:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    909:                                                             'startenroll',
                    910:                                                             $starttime);
                    911:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    912:                                                           'endenroll',
                    913:                                                           $endtime);
                    914:     }
                    915:     if ($mode eq 'create_defaultdates') {
                    916:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    917:                                                             'startaccess',
                    918:                                                             $starttime);
                    919:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                    920:                                                           'endaccess',
                    921:                                                           $endtime);
                    922:     }
                    923:     return ($startdateform,$enddateform);
                    924: }
                    925: 
                    926: 
                    927: sub get_dates_from_form {
                    928:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate');
                    929:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate');
                    930:     if ($env{'form.no_end_date'}) {
                    931:         $enddate = 0;
                    932:     }
                    933:     return ($startdate,$enddate);
                    934: }
                    935: 
                    936: sub date_setting_table {
1.22      raeburn   937:     my ($starttime,$endtime,$mode,$bulkaction,$formname,$permission) = @_;
1.11      raeburn   938:     my $nolink;
                    939:     if ($bulkaction) {
                    940:         $nolink = 1;
                    941:     }
                    942:     my ($startform,$endform) = 
1.22      raeburn   943:         &setup_date_selectors($starttime,$endtime,$mode,$nolink,$formname);
1.1       raeburn   944:     my $dateDefault;
                    945:     if ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
                    946:         $dateDefault = '&nbsp;';
1.13      raeburn   947:     } elsif ($mode ne 'author' && $mode ne 'domain') {
1.11      raeburn   948:         if (($bulkaction eq 'reenable') || 
                    949:             ($bulkaction eq 'activate') || 
1.22      raeburn   950:             ($bulkaction eq 'chgdates') ||
                    951:             ($env{'form.action'} eq 'upload')) {
                    952:             if ($env{'request.course.sec'} eq '') {
                    953:                 $dateDefault = '<span class="LC_nobreak">'.
1.25      raeburn   954:                     '<label><input type="checkbox" name="makedatesdefault" value="1" /> '.
1.22      raeburn   955:                     &mt('make these dates the default access dates for future student enrollment').
                    956:                     '</label></span>';
                    957:             }
1.11      raeburn   958:         }
1.1       raeburn   959:     }
1.11      raeburn   960:     my $perpetual = '<span class="LC_nobreak"><label><input type="checkbox" name="no_end_date"';
1.1       raeburn   961:     if (defined($endtime) && $endtime == 0) {
                    962:         $perpetual .= ' checked';
                    963:     }
1.11      raeburn   964:     $perpetual.= ' /> '.&mt('no ending date').'</label></span>';
1.1       raeburn   965:     if ($mode eq 'create_enrolldates') {
                    966:         $perpetual = '&nbsp;';
                    967:     }
1.11      raeburn   968:     my $result = &Apache::lonhtmlcommon::start_pick_box()."\n";
                    969:     $result .= &Apache::lonhtmlcommon::row_title(&mt('Starting Date'),
                    970:                                                      'LC_oddrow_value')."\n".
                    971:                $startform."\n".
                    972:                &Apache::lonhtmlcommon::row_closure(1).
                    973:                &Apache::lonhtmlcommon::row_title(&mt('Ending Date'), 
                    974:                                                      'LC_oddrow_value')."\n".
                    975:                $endform.'&nbsp;'.$perpetual.
                    976:                &Apache::lonhtmlcommon::row_closure(1).
1.22      raeburn   977:                &Apache::lonhtmlcommon::end_pick_box();
1.1       raeburn   978:     if ($dateDefault) {
                    979:         $result .=  $dateDefault.'<br />'."\n";
                    980:     }
                    981:     return $result;
                    982: }
                    983: 
                    984: sub make_dates_default {
                    985:     my ($startdate,$enddate,$context) = @_;
                    986:     my $result = '';
                    987:     if ($context eq 'course') {
1.17      raeburn   988:         my ($cnum,$cdom) = &get_course_identity();
1.1       raeburn   989:         my $put_result = &Apache::lonnet::put('environment',
                    990:                 {'default_enrollment_start_date'=>$startdate,
1.17      raeburn   991:                  'default_enrollment_end_date'  =>$enddate},$cdom,$cnum);
1.1       raeburn   992:         if ($put_result eq 'ok') {
1.25      raeburn   993:             $result .= &mt('Set default start and end access dates for course.').
1.11      raeburn   994:                        '<br />'."\n";
1.1       raeburn   995:             #
                    996:             # Refresh the course environment
                    997:             &Apache::lonnet::coursedescription($env{'request.course.id'},
                    998:                                                {'freshen_cache' => 1});
                    999:         } else {
1.25      raeburn  1000:             $result .= &mt('Unable to set default access dates for course.').":".$put_result.
1.1       raeburn  1001:                        '<br />';
                   1002:         }
                   1003:     }
                   1004:     return $result;
                   1005: }
                   1006: 
                   1007: sub default_role_selector {
1.2       raeburn  1008:     my ($context,$checkpriv) = @_;
1.1       raeburn  1009:     my %customroles;
                   1010:     my ($options,$coursepick,$cb_jscript);
1.13      raeburn  1011:     if ($context ne 'author') {
1.1       raeburn  1012:         %customroles = &my_custom_roles();
                   1013:     }
                   1014: 
                   1015:     my %lt=&Apache::lonlocal::texthash(
                   1016:                     'rol'  => "Role",
                   1017:                     'grs'  => "Section",
                   1018:                     'exs'  => "Existing sections",
                   1019:                     'new'  => "New section",
                   1020:                   );
                   1021:     $options = '<select name="defaultrole">'."\n".
                   1022:                ' <option value="">'.&mt('Please select').'</option>'."\n"; 
                   1023:     if ($context eq 'course') {
1.2       raeburn  1024:         $options .= &default_course_roles($context,$checkpriv,%customroles);
1.13      raeburn  1025:     } elsif ($context eq 'author') {
1.2       raeburn  1026:         my @roles = &construction_space_roles($checkpriv);
1.1       raeburn  1027:         foreach my $role (@roles) {
                   1028:            my $plrole=&Apache::lonnet::plaintext($role);
                   1029:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>'."\n";
                   1030:         }
                   1031:     } elsif ($context eq 'domain') {
1.2       raeburn  1032:         my @roles = &domain_roles($checkpriv);
1.1       raeburn  1033:         foreach my $role (@roles) {
                   1034:            my $plrole=&Apache::lonnet::plaintext($role);
                   1035:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>';
                   1036:         }
                   1037:         my $courseform = &Apache::loncommon::selectcourse_link
1.22      raeburn  1038:             ('studentform','dccourse','dcdomain','coursedesc',"$env{'request.role.domain'}",undef,'Course');
1.1       raeburn  1039:         $cb_jscript = 
1.22      raeburn  1040:             &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'},'currsec','studentform');
1.1       raeburn  1041:         $coursepick = &Apache::loncommon::start_data_table().
                   1042:                       &Apache::loncommon::start_data_table_header_row().
                   1043:                       '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th>'.
                   1044:                       '<th>'.$lt{'grs'}.'</th>'.
                   1045:                       &Apache::loncommon::end_data_table_header_row().
                   1046:                       &Apache::loncommon::start_data_table_row()."\n".
1.22      raeburn  1047:                       '<td><input type="text" name="coursedesc" value="" onFocus="this.blur();opencrsbrowser('."'studentform','dccourse','dcdomain','coursedesc',''".')" /></td>'."\n".
1.1       raeburn  1048:                       '<td><select name="courserole">'."\n".
1.2       raeburn  1049:                       &default_course_roles($context,$checkpriv,%customroles)."\n".
1.1       raeburn  1050:                       '</select></td><td>'.
                   1051:                       '<table class="LC_createuser">'.
                   1052:                       '<tr class="LC_section_row"><td valign"top">'.
1.22      raeburn  1053:                       $lt{'exs'}.'<br /><select name="currsec">'.
1.1       raeburn  1054:                       ' <option value=""><--'.&mt('Pick course first').
                   1055:                       '</select></td>'.
                   1056:                       '<td>&nbsp;&nbsp;</td>'.
                   1057:                       '<td valign="top">'.$lt{'new'}.'<br />'.
                   1058:                       '<input type="text" name="newsec" value="" size="5" />'.
1.22      raeburn  1059:                       '<input type="hidden" name="groups" value="" />'.
                   1060:                       '<input type="hidden" name="sections" value="" />'.
                   1061:                       '<input type="hidden" name="origdom" value="'.
                   1062:                       $env{'request.role.domain'}.'" />'.
                   1063:                       '<input type="hidden" name="dccourse" value="" />'.
                   1064:                       '<input type="hidden" name="dcdomain" value="" />'.
                   1065:                       '</td></tr></table></td>'.
1.1       raeburn  1066:                       &Apache::loncommon::end_data_table_row().
1.22      raeburn  1067:                       &Apache::loncommon::end_data_table()."\n";
1.1       raeburn  1068:     }
                   1069:     $options .= '</select>';
                   1070:     return ($options,$cb_jscript,$coursepick);
                   1071: }
                   1072: 
                   1073: sub default_course_roles {
1.2       raeburn  1074:     my ($context,$checkpriv,%customroles) = @_;
1.1       raeburn  1075:     my $output;
1.17      raeburn  1076:     my $custom = 1;
                   1077:     my @roles = &course_roles($context,$checkpriv,$custom);
1.1       raeburn  1078:     foreach my $role (@roles) {
1.22      raeburn  1079:         if ($role ne 'cr') {
                   1080:             my $plrole=&Apache::lonnet::plaintext($role);
                   1081:             $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
                   1082:         }
1.1       raeburn  1083:     }
                   1084:     if (keys(%customroles) > 0) {
1.22      raeburn  1085:         if (grep(/^cr$/,@roles)) {
                   1086:             foreach my $cust (sort(keys(%customroles))) {
                   1087:                 my $custrole='cr_'.$env{'user.domain'}.
                   1088:                              '_'.$env{'user.name'}.'_'.$cust;
                   1089:                 $output .= '  <option value="'.$custrole.'">'.$cust.'</option>';
                   1090:             }
1.1       raeburn  1091:         }
                   1092:     }
                   1093:     return $output;
                   1094: }
                   1095: 
                   1096: sub construction_space_roles {
1.2       raeburn  1097:     my ($checkpriv) = @_;
1.17      raeburn  1098:     my @allroles = &roles_by_context('author');
1.1       raeburn  1099:     my @roles;
1.2       raeburn  1100:     if ($checkpriv) {
                   1101:         foreach my $role (@allroles) {
                   1102:             if (&Apache::lonnet::allowed('c'.$role,$env{'user.domain'}.'/'.$env{'user.name'})) { 
                   1103:                 push(@roles,$role); 
                   1104:             }
1.1       raeburn  1105:         }
1.2       raeburn  1106:         return @roles;
                   1107:     } else {
                   1108:         return @allroles;
1.1       raeburn  1109:     }
                   1110: }
                   1111: 
                   1112: sub domain_roles {
1.2       raeburn  1113:     my ($checkpriv) = @_;
1.17      raeburn  1114:     my @allroles = &roles_by_context('domain');
1.1       raeburn  1115:     my @roles;
1.2       raeburn  1116:     if ($checkpriv) {
                   1117:         foreach my $role (@allroles) {
                   1118:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
                   1119:                 push(@roles,$role);
                   1120:             }
1.1       raeburn  1121:         }
1.2       raeburn  1122:         return @roles;
                   1123:     } else {
                   1124:         return @allroles;
1.1       raeburn  1125:     }
                   1126: }
                   1127: 
                   1128: sub course_roles {
1.17      raeburn  1129:     my ($context,$checkpriv,$custom) = @_;
                   1130:     my @allroles = &roles_by_context('course',$custom);
1.1       raeburn  1131:     my @roles;
                   1132:     if ($context eq 'domain') {
                   1133:         @roles = @allroles;
                   1134:     } elsif ($context eq 'course') {
                   1135:         if ($env{'request.course.id'}) {
1.2       raeburn  1136:             if ($checkpriv) { 
                   1137:                 foreach my $role (@allroles) {
                   1138:                     if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
                   1139:                         push(@roles,$role);
                   1140:                     } else {
1.22      raeburn  1141:                         if ($role ne 'cc' && $env{'request.course.sec'} ne '') {
                   1142:                             if (&Apache::lonnet::allowed('c'.$role,
1.2       raeburn  1143:                                              $env{'request.course.id'}.'/'.
1.22      raeburn  1144:                                              $env{'request.course.sec'})) {
1.2       raeburn  1145:                                 push(@roles,$role);
                   1146:                             }
1.1       raeburn  1147:                         }
                   1148:                     }
                   1149:                 }
1.2       raeburn  1150:             } else {
                   1151:                 @roles = @allroles;
1.1       raeburn  1152:             }
                   1153:         }
                   1154:     }
                   1155:     return @roles;
                   1156: }
                   1157: 
                   1158: sub curr_role_permissions {
1.2       raeburn  1159:     my ($context,$setting,$checkpriv) = @_; 
1.17      raeburn  1160:     my $custom = 1;
1.1       raeburn  1161:     my @roles;
1.13      raeburn  1162:     if ($context eq 'author') {
1.2       raeburn  1163:         @roles = &construction_space_roles($checkpriv);
1.1       raeburn  1164:     } elsif ($context eq 'domain') {
                   1165:         if ($setting eq 'course') {
1.17      raeburn  1166:             @roles = &course_roles($context,$checkpriv,$custom); 
1.1       raeburn  1167:         } else {
1.2       raeburn  1168:             @roles = &domain_roles($checkpriv);
1.1       raeburn  1169:         }
                   1170:     } elsif ($context eq 'course') {
1.17      raeburn  1171:         @roles = &course_roles($context,$checkpriv,$custom);
1.1       raeburn  1172:     }
                   1173:     return @roles;
                   1174: }
                   1175: 
                   1176: # ======================================================= Existing Custom Roles
                   1177: 
                   1178: sub my_custom_roles {
                   1179:     my %returnhash=();
                   1180:     my %rolehash=&Apache::lonnet::dump('roles');
                   1181:     foreach my $key (keys %rolehash) {
                   1182:         if ($key=~/^rolesdef\_(\w+)$/) {
                   1183:             $returnhash{$1}=$1;
                   1184:         }
                   1185:     }
                   1186:     return %returnhash;
                   1187: }
                   1188: 
1.2       raeburn  1189: sub print_userlist {
                   1190:     my ($r,$mode,$permission,$context,$formname,$totcodes,$codetitles,
                   1191:         $idlist,$idlist_titles) = @_;
                   1192:     my $format = $env{'form.output'};
1.1       raeburn  1193:     if (! exists($env{'form.sortby'})) {
                   1194:         $env{'form.sortby'} = 'username';
                   1195:     }
1.2       raeburn  1196:     if ($env{'form.Status'} !~ /^(Any|Expired|Active|Future)$/) {
                   1197:         $env{'form.Status'} = 'Active';
1.1       raeburn  1198:     }
                   1199:     my $status_select = &Apache::lonhtmlcommon::StatusOptions
1.2       raeburn  1200:         ($env{'form.Status'});
1.1       raeburn  1201: 
1.2       raeburn  1202:     if ($env{'form.showrole'} eq '') {
1.13      raeburn  1203:         if ($context eq 'course') {
                   1204:             $env{'form.showrole'} = 'st';
                   1205:         } else {
                   1206:             $env{'form.showrole'} = 'Any';            
                   1207:         }
1.2       raeburn  1208:     }
1.1       raeburn  1209:     if (! defined($env{'form.output'}) ||
                   1210:         $env{'form.output'} !~ /^(csv|excel|html)$/ ) {
                   1211:         $env{'form.output'} = 'html';
                   1212:     }
                   1213: 
1.2       raeburn  1214:     my @statuses;
                   1215:     if ($env{'form.Status'} eq 'Any') {
                   1216:         @statuses = ('previous','active','future');
                   1217:     } elsif ($env{'form.Status'} eq 'Expired') {
                   1218:         @statuses = ('previous');
                   1219:     } elsif ($env{'form.Status'} eq 'Active') {
                   1220:         @statuses = ('active');
                   1221:     } elsif ($env{'form.Status'} eq 'Future') {
                   1222:         @statuses = ('future');
                   1223:     }
1.1       raeburn  1224: 
1.2       raeburn  1225: #    if ($context eq 'course') { 
                   1226: #        $r->print(&display_adv_courseroles());
                   1227: #    }
1.1       raeburn  1228:     #
                   1229:     # Interface output
1.2       raeburn  1230:     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n".
                   1231:               '<input type="hidden" name="action" value="'.
1.1       raeburn  1232:               $env{'form.action'}.'" />');
                   1233:     $r->print("<p>\n");
                   1234:     if ($env{'form.action'} ne 'modifystudent') {
                   1235:         my %lt=&Apache::lonlocal::texthash('csv' => "CSV",
                   1236:                                            'excel' => "Excel",
                   1237:                                            'html'  => 'HTML');
                   1238:         my $output_selector = '<select size="1" name="output" >';
                   1239:         foreach my $outputformat ('html','csv','excel') {
                   1240:             my $option = '<option value="'.$outputformat.'" ';
                   1241:             if ($outputformat eq $env{'form.output'}) {
                   1242:                 $option .= 'selected ';
                   1243:             }
                   1244:             $option .='>'.$lt{$outputformat}.'</option>';
                   1245:             $output_selector .= "\n".$option;
                   1246:         }
                   1247:         $output_selector .= '</select>';
                   1248:         $r->print('<label>'.&mt('Output Format: [_1]',$output_selector).'</label>'.('&nbsp;'x3));
                   1249:     }
1.2       raeburn  1250:     $r->print('<label>'.&mt('User Status: [_1]',$status_select).'</label>'.('&nbsp;'x3)."\n");
                   1251:     my $roleselected = '';
                   1252:     if ($env{'form.showrole'} eq 'Any') {
                   1253:        $roleselected = ' selected="selected" '; 
                   1254:     }
1.53    ! raeburn  1255:     my ($cnum,$cdom);
        !          1256:     $r->print(&role_filter($context));
        !          1257:     if ($context eq 'course') {
        !          1258:         ($cnum,$cdom) = &get_course_identity();
        !          1259:         $r->print(&section_group_filter($cnum,$cdom));
1.2       raeburn  1260:     }
                   1261:     if (!(($context eq 'domain') && ($env{'form.roletype'} eq 'course'))) {
1.25      raeburn  1262:         $r->print('&nbsp;'.&list_submit_button(&mt('Update Display')).
                   1263:                   "\n</p>\n");
1.2       raeburn  1264:     }
                   1265:     my ($indexhash,$keylist) = &make_keylist_array();
                   1266:     my (%userlist,%userinfo);
1.3       raeburn  1267:     if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
                   1268:         my $courseform =
                   1269:             &Apache::lonhtmlcommon::course_selection($formname,$totcodes,
                   1270:                                          $codetitles,$idlist,$idlist_titles);
                   1271:         $r->print('<p>'.&Apache::lonhtmlcommon::start_pick_box()."\n".
                   1272:                   &Apache::lonhtmlcommon::start_pick_box()."\n".
                   1273:                   &Apache::lonhtmlcommon::row_title(&mt('Select Course(s)'),
                   1274:                                                     'LC_oddrow_value')."\n".
                   1275:                   $courseform."\n".
                   1276:                   &Apache::lonhtmlcommon::row_closure(1).
                   1277:                   &Apache::lonhtmlcommon::end_pick_box().'</p>'.
                   1278:                   '<p>'.&list_submit_button(&mt('Update Display')).
1.34      raeburn  1279:                   "\n".'</p><span class="LC_warning">'.&mt('Warning: data retrieval for multiple courses can take considerable time, as this operation is not currently optimized.').'</span>'."\n");
1.11      raeburn  1280:         if ($env{'form.coursepick'}) {
                   1281:             $r->print('<hr />'.&mt('Searching').' ...<br />&nbsp;<br />');
                   1282:         }
                   1283:     } else {
                   1284:         $r->print('<hr />'.&mt('Searching').' ...<br />&nbsp;<br />');
1.3       raeburn  1285:     }
                   1286:     $r->rflush();
1.1       raeburn  1287:     if ($context eq 'course') {
1.46      raeburn  1288:         if (($env{'form.showrole'} eq 'st') || ($env{'form.showrole'} eq 'Any')) { 
1.45      raeburn  1289:             my $classlist = &Apache::loncoursedata::get_classlist();
                   1290:             %userlist = %{$classlist};
                   1291:         }
1.43      raeburn  1292:         if ($env{'form.showrole'} ne 'st') {
                   1293:             my $showroles;
                   1294:             if ($env{'form.showrole'} ne 'Any') {
                   1295:                 $showroles = [$env{'form.showrole'}];
1.3       raeburn  1296:             } else {
1.43      raeburn  1297:                 $showroles = undef;
1.1       raeburn  1298:             }
1.43      raeburn  1299:             my $withsec = 1;
                   1300:             my $hidepriv = 1;
                   1301:             my %advrolehash = &Apache::lonnet::get_my_roles($cnum,$cdom,undef,
                   1302:                               \@statuses,$showroles,undef,$withsec,$hidepriv);
                   1303:             &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
                   1304:                              \%advrolehash,$permission);
1.1       raeburn  1305:         }
1.2       raeburn  1306:     } else {
                   1307:         my (%cstr_roles,%dom_roles);
1.13      raeburn  1308:         if ($context eq 'author') {
1.2       raeburn  1309:             # List co-authors and assistant co-authors
1.17      raeburn  1310:             my @possroles = &roles_by_context($context);
1.2       raeburn  1311:             %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
                   1312:                                               \@statuses,\@possroles);
                   1313:             &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
1.11      raeburn  1314:                              \%cstr_roles,$permission);
1.2       raeburn  1315:         } elsif ($context eq 'domain') {
                   1316:             if ($env{'form.roletype'} eq 'domain') {
                   1317:                 %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'});
                   1318:                 foreach my $key (keys(%dom_roles)) {
                   1319:                     if (ref($dom_roles{$key}) eq 'HASH') {
                   1320:                         &gather_userinfo($context,$format,\%userlist,$indexhash,
1.11      raeburn  1321:                                          \%userinfo,$dom_roles{$key},$permission);
1.2       raeburn  1322:                     }
                   1323:                 }
1.13      raeburn  1324:             } elsif ($env{'form.roletype'} eq 'author') {
1.2       raeburn  1325:                 my %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'},['au']);
                   1326:                 my %coauthors;
                   1327:                 foreach my $key (keys(%dom_roles)) {
                   1328:                     if (ref($dom_roles{$key}) eq 'HASH') {
                   1329:                         if ($env{'form.showrole'} eq 'au') {
                   1330:                             &gather_userinfo($context,$format,\%userlist,$indexhash,
1.11      raeburn  1331:                                              \%userinfo,$dom_roles{$key},$permission);
1.2       raeburn  1332:                         } else {
                   1333:                             my @possroles;
                   1334:                             if ($env{'form.showrole'} eq 'Any') {
1.22      raeburn  1335:                                 @possroles = &roles_by_context('author');
1.2       raeburn  1336:                             } else {
                   1337:                                 @possroles = ($env{'form.showrole'}); 
                   1338:                             }
                   1339:                             foreach my $author (sort(keys(%{$dom_roles{$key}}))) {
1.22      raeburn  1340:                                 my ($role,$authorname,$authordom) = split(/:/,$author,-1);
1.2       raeburn  1341:                                 my $extent = '/'.$authordom.'/'.$authorname;
                   1342:                                 %{$coauthors{$extent}} =
                   1343:                                     &Apache::lonnet::get_my_roles($authorname,
                   1344:                                        $authordom,undef,\@statuses,\@possroles);
                   1345:                             }
                   1346:                             &gather_userinfo($context,$format,\%userlist,
1.11      raeburn  1347:                                      $indexhash,\%userinfo,\%coauthors,$permission);
1.2       raeburn  1348:                         }
                   1349:                     }
                   1350:                 }
                   1351:             } elsif ($env{'form.roletype'} eq 'course') {
                   1352:                 if ($env{'form.coursepick'}) {
                   1353:                     my %courses = &process_coursepick();
1.39      raeburn  1354:                     my %allusers;
                   1355:                     my $hidepriv = 1;
1.2       raeburn  1356:                     foreach my $cid (keys(%courses)) {
1.17      raeburn  1357:                         my ($cnum,$cdom,$cdesc) = &get_course_identity($cid);
1.11      raeburn  1358:                         next if ($cnum eq '' || $cdom eq '');
1.17      raeburn  1359:                         my $custom = 1;
1.2       raeburn  1360:                         my (@roles,@sections,%access,%users,%userdata,
1.6       albertel 1361:                             %statushash);
1.2       raeburn  1362:                         if ($env{'form.showrole'} eq 'Any') {
1.17      raeburn  1363:                             @roles = &course_roles($context,undef,$custom);
1.2       raeburn  1364:                         } else {
                   1365:                             @roles = ($env{'form.showrole'});
                   1366:                         }
                   1367:                         foreach my $role (@roles) {
                   1368:                             %{$users{$role}} = ();
                   1369:                         }
                   1370:                         foreach my $type (@statuses) {
                   1371:                             $access{$type} = $type;
                   1372:                         }
1.39      raeburn  1373:                         &Apache::loncommon::get_course_users($cdom,$cnum,\%access,\@roles,\@sections,\%users,\%userdata,\%statushash,$hidepriv);
1.2       raeburn  1374:                         foreach my $user (keys(%userdata)) {
                   1375:                             next if (ref($userinfo{$user}) eq 'HASH');
                   1376:                             foreach my $item ('fullname','id') {
                   1377:                                 $userinfo{$user}{$item} = $userdata{$user}[$indexhash->{$item}];
                   1378:                             }
                   1379:                         }
                   1380:                         foreach my $role (keys(%users)) {
                   1381:                             foreach my $user (keys(%{$users{$role}})) {
                   1382:                                 my $uniqid = $user.':'.$role;
                   1383:                                 $allusers{$uniqid}{$cid} = { desc => $cdesc,
                   1384:                                                              secs  => $statushash{$user}{$role},
                   1385:                                                            };
                   1386:                             }
                   1387:                         }
                   1388:                     }
                   1389:                     &gather_userinfo($context,$format,\%userlist,$indexhash,
1.11      raeburn  1390:                                      \%userinfo,\%allusers,$permission);
1.2       raeburn  1391:                 } else {
1.10      raeburn  1392:                     $r->print('<input type="hidden" name="phase" value="'.
                   1393:                               $env{'form.phase'}.'" /></form>');
1.2       raeburn  1394:                     return;
                   1395:                 }
1.1       raeburn  1396:             }
                   1397:         }
1.3       raeburn  1398:     }
                   1399:     if (keys(%userlist) == 0) {
1.13      raeburn  1400:         if ($context eq 'author') {
1.3       raeburn  1401:             $r->print(&mt('There are no co-authors to display.')."\n");
                   1402:         } elsif ($context eq 'domain') {
                   1403:             if ($env{'form.roletype'} eq 'domain') {
                   1404:                 $r->print(&mt('There are no users with domain roles to display.')."\n");
1.13      raeburn  1405:             } elsif ($env{'form.roletype'} eq 'author') {
1.3       raeburn  1406:                 $r->print(&mt('There are no authors or co-authors to display.')."\n");
                   1407:             } elsif ($env{'form.roletype'} eq 'course') {
                   1408:                 $r->print(&mt('There are no course users to display')."\n"); 
1.2       raeburn  1409:             }
1.3       raeburn  1410:         } elsif ($context eq 'course') {
                   1411:             $r->print(&mt('There are no course users to display.')."\n");
                   1412:         }
                   1413:     } else {
                   1414:         # Print out the available choices
1.4       raeburn  1415:         my $usercount;
1.3       raeburn  1416:         if ($env{'form.action'} eq 'modifystudent') {
1.10      raeburn  1417:             ($usercount) = &show_users_list($r,$context,'view',$permission,
1.4       raeburn  1418:                                  $env{'form.Status'},\%userlist,$keylist);
1.1       raeburn  1419:         } else {
1.4       raeburn  1420:             ($usercount) = &show_users_list($r,$context,$env{'form.output'},
1.10      raeburn  1421:                                $permission,$env{'form.Status'},\%userlist,$keylist);
1.4       raeburn  1422:         }
                   1423:         if (!$usercount) {
                   1424:             $r->print('<br />'.&mt('There are no users matching the search criteria.')); 
1.2       raeburn  1425:         }
                   1426:     }
1.10      raeburn  1427:     $r->print('<input type="hidden" name="phase" value="'.
                   1428:               $env{'form.phase'}.'" /></form>');
1.2       raeburn  1429: }
                   1430: 
1.53    ! raeburn  1431: sub role_filter {
        !          1432:     my ($context) = @_;
        !          1433:     my $output;
        !          1434:     my $roleselected = '';
        !          1435:     if ($env{'form.showrole'} eq 'Any') {
        !          1436:        $roleselected = ' selected="selected" ';
        !          1437:     }
        !          1438:     my ($role_select);
        !          1439:     if ($context eq 'domain') {
        !          1440:         $role_select = &domain_roles_select();
        !          1441:         $output = '<label>'.&mt('Role Type: [_1]',$role_select).'</label>';
        !          1442:     } else {
        !          1443:         $role_select = '<select name="showrole">'."\n".
        !          1444:                        '<option value="Any" '.$roleselected.'>'.
        !          1445:                        &mt('Any role').'</option>';
        !          1446:         my @poss_roles = &curr_role_permissions($context);
        !          1447:         foreach my $role (@poss_roles) {
        !          1448:             $roleselected = '';
        !          1449:             if ($role eq $env{'form.showrole'}) {
        !          1450:                 $roleselected = ' selected="selected" ';
        !          1451:             }
        !          1452:             my $plrole;
        !          1453:             if ($role eq 'cr') {
        !          1454:                 $plrole = &mt('Custom role');
        !          1455:             } else {
        !          1456:                 $plrole=&Apache::lonnet::plaintext($role);
        !          1457:             }
        !          1458:             $role_select .= '<option value="'.$role.'"'.$roleselected.'>'.$plrole.'</option>';
        !          1459:         }
        !          1460:         $role_select .= '</select>';
        !          1461:         $output = '<label>'.&mt('Role: [_1]',$role_select).'</label>';
        !          1462:     }
        !          1463:     return $output;
        !          1464: }
        !          1465: 
1.33      raeburn  1466: sub section_group_filter {
                   1467:     my ($cnum,$cdom) = @_;
                   1468:     my @filters;
                   1469:     if ($env{'request.course.sec'} eq '') {
                   1470:         @filters = ('sec');
                   1471:     }
                   1472:     push(@filters,'grp');
                   1473:     my %name = (
                   1474:                  sec => 'secfilter',
                   1475:                  grp => 'grpfilter',
                   1476:                );
                   1477:     my %title = &Apache::lonlocal::texthash (
                   1478:                                               sec  => 'Section(s)',
                   1479:                                               grp  => 'Group(s)',
                   1480:                                               all  => 'all',
                   1481:                                               none => 'none',
                   1482:                                             );
1.47      raeburn  1483:     my $output;
1.33      raeburn  1484:     foreach my $item (@filters) {
1.47      raeburn  1485:         my ($markup,@options); 
1.33      raeburn  1486:         if ($env{'form.'.$name{$item}} eq '') {
                   1487:             $env{'form.'.$name{$item}} = 'all';
                   1488:         }
                   1489:         if ($item eq 'sec') {
                   1490:             if ($env{'form.showrole'} eq 'cc') {
                   1491:                 $env{'form.'.$name{$item}} = 'none';
                   1492:             }
                   1493:             my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
                   1494:             @options = sort(keys(%sections_count));
                   1495:         } elsif ($item eq 'grp') {
                   1496:             my %curr_groups = &Apache::longroup::coursegroups();
                   1497:             @options = sort(keys(%curr_groups));
                   1498:         }
                   1499:         if (@options > 0) {
                   1500:             my $currsel;
                   1501:             $markup = '<select name="'.$name{$item}.'" />'."\n";
                   1502:             foreach my $option ('all','none',@options) { 
                   1503:                 $currsel = '';
                   1504:                 if ($env{'form.'.$name{$item}} eq $option) {
                   1505:                     $currsel = ' selected="selected" ';
                   1506:                 }
                   1507:                 $markup .= ' <option value="'.$option.'"'.$currsel.'>';
                   1508:                 if (($option eq 'all') || ($option eq 'none')) {
                   1509:                     $markup .= $title{$option};
                   1510:                 } else {
                   1511:                     $markup .= $option;
                   1512:                 }   
                   1513:                 $markup .= '</option>'."\n";
                   1514:             }
                   1515:             $markup .= '</select>'."\n";
                   1516:             $output .= ('&nbsp;'x3).'<label>'.$title{$item}.': '.$markup.'</label>';
                   1517:         }
                   1518:     }
                   1519:     return $output;
                   1520: }
                   1521: 
1.2       raeburn  1522: sub list_submit_button {
                   1523:     my ($text) = @_;
1.11      raeburn  1524:     return '<input type="button" name="updatedisplay" value="'.$text.'" onclick="javascript:display_update()" />';
1.2       raeburn  1525: }
                   1526: 
                   1527: sub gather_userinfo {
1.11      raeburn  1528:     my ($context,$format,$userlist,$indexhash,$userinfo,$rolehash,$permission) = @_;
1.52      raeburn  1529:     my $viewablesec;
                   1530:     if ($context eq 'course') {
                   1531:         $viewablesec = &viewable_section($permission);
                   1532:     }
1.2       raeburn  1533:     foreach my $item (keys(%{$rolehash})) {
                   1534:         my %userdata;
1.22      raeburn  1535:         if ($context eq 'author') { 
1.2       raeburn  1536:             ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
                   1537:                 split(/:/,$item);
                   1538:             ($userdata{'start'},$userdata{'end'})=split(/:/,$rolehash->{$item});
1.24      raeburn  1539:             &build_user_record($context,\%userdata,$userinfo,$indexhash,
                   1540:                                $item,$userlist);
1.22      raeburn  1541:         } elsif ($context eq 'course') {
                   1542:             ($userdata{'username'},$userdata{'domain'},$userdata{'role'},
                   1543:              $userdata{'section'}) = split(/:/,$item,-1);
                   1544:             ($userdata{'start'},$userdata{'end'})=split(/:/,$rolehash->{$item});
                   1545:             if (($viewablesec ne '') && ($userdata{'section'} ne '')) {
                   1546:                 next if ($viewablesec ne $userdata{'section'});
                   1547:             }
1.24      raeburn  1548:             &build_user_record($context,\%userdata,$userinfo,$indexhash,
                   1549:                                $item,$userlist);
1.2       raeburn  1550:         } elsif ($context eq 'domain') {
                   1551:             if ($env{'form.roletype'} eq 'domain') {
                   1552:                 ($userdata{'role'},$userdata{'username'},$userdata{'domain'}) =
                   1553:                     split(/:/,$item);
                   1554:                 ($userdata{'end'},$userdata{'start'})=split(/:/,$rolehash->{$item});
1.24      raeburn  1555:                 &build_user_record($context,\%userdata,$userinfo,$indexhash,
                   1556:                                    $item,$userlist);
1.13      raeburn  1557:             } elsif ($env{'form.roletype'} eq 'author') {
1.2       raeburn  1558:                 if (ref($rolehash->{$item}) eq 'HASH') {
                   1559:                     $userdata{'extent'} = $item;
                   1560:                     foreach my $key (keys(%{$rolehash->{$item}})) {
                   1561:                         ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =  split(/:/,$key);
                   1562:                         ($userdata{'start'},$userdata{'end'}) = 
                   1563:                             split(/:/,$rolehash->{$item}{$key});
                   1564:                         my $uniqid = $key.':'.$item;
1.25      raeburn  1565:                         &build_user_record($context,\%userdata,$userinfo,
                   1566:                                            $indexhash,$uniqid,$userlist);
1.2       raeburn  1567:                     }
                   1568:                 }
                   1569:             } elsif ($env{'form.roletype'} eq 'course') {
                   1570:                 ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
                   1571:                     split(/:/,$item);
                   1572:                 if (ref($rolehash->{$item}) eq 'HASH') {
1.11      raeburn  1573:                     my $numcids = keys(%{$rolehash->{$item}});
1.2       raeburn  1574:                     foreach my $cid (sort(keys(%{$rolehash->{$item}}))) {
                   1575:                         if (ref($rolehash->{$item}{$cid}) eq 'HASH') {
                   1576:                             my $spanstart = '';
                   1577:                             my $spanend = '; ';
                   1578:                             my $space = ', ';
                   1579:                             if ($format eq 'html' || $format eq 'view') {
                   1580:                                 $spanstart = '<span class="LC_nobreak">';
1.23      raeburn  1581:                                 # FIXME: actions on courses disabled for now
                   1582: #                                if ($permission->{'cusr'}) {
                   1583: #                                    if ($numcids > 1) {
1.25      raeburn  1584: #                                        $spanstart .= '<input type="radio" name="'.$item.'" value="'.$cid.'" />&nbsp;';
1.23      raeburn  1585: #                                    } else {
1.25      raeburn  1586: #                                        $spanstart .= '<input type="hidden" name="'.$item.'" value="'.$cid.'" />&nbsp;';
1.23      raeburn  1587: #                                    }
                   1588: #                                }
1.2       raeburn  1589:                                 $spanend = '</span><br />';
                   1590:                                 $space = ',&nbsp;';
                   1591:                             }
                   1592:                             $userdata{'extent'} .= $spanstart.
                   1593:                                     $rolehash->{$item}{$cid}{'desc'}.$space;
                   1594:                             if (ref($rolehash->{$item}{$cid}{'secs'}) eq 'HASH') { 
                   1595:                                 foreach my $sec (sort(keys(%{$rolehash->{$item}{$cid}{'secs'}}))) {
1.25      raeburn  1596:                                     if (($env{'form.Status'} eq 'Any') ||
                   1597:                                         ($env{'form.Status'} eq $rolehash->{$item}{$cid}{'secs'}{$sec})) {
                   1598:                                         $userdata{'extent'} .= $sec.$space.$rolehash->{$item}{$cid}{'secs'}{$sec}.$spanend;
                   1599:                                         $userdata{'status'} = $rolehash->{$item}{$cid}{'secs'}{$sec};
                   1600:                                     }
1.2       raeburn  1601:                                 }
                   1602:                             }
                   1603:                         }
                   1604:                     }
                   1605:                 }
1.25      raeburn  1606:                 if ($userdata{'status'} ne '') {
                   1607:                     &build_user_record($context,\%userdata,$userinfo,
                   1608:                                        $indexhash,$item,$userlist);
                   1609:                 }
1.2       raeburn  1610:             }
                   1611:         }
                   1612:     }
                   1613:     return;
                   1614: }
                   1615: 
                   1616: sub build_user_record {
1.24      raeburn  1617:     my ($context,$userdata,$userinfo,$indexhash,$record_key,$userlist) = @_;
1.11      raeburn  1618:     next if ($userdata->{'start'} eq '-1' && $userdata->{'end'} eq '-1');
1.24      raeburn  1619:     if (!(($context eq 'domain') && ($env{'form.roletype'} eq 'course'))) {
                   1620:         &process_date_info($userdata);
                   1621:     }
1.2       raeburn  1622:     my $username = $userdata->{'username'};
                   1623:     my $domain = $userdata->{'domain'};
                   1624:     if (ref($userinfo->{$username.':'.$domain}) eq 'HASH') {
1.24      raeburn  1625:         $userdata->{'fullname'} = $userinfo->{$username.':'.$domain}{'fullname'};
1.2       raeburn  1626:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
                   1627:     } else {
                   1628:         &aggregate_user_info($domain,$username,$userinfo);
                   1629:         $userdata->{'fullname'} = $userinfo->{$username.':'.$domain}{'fullname'};
                   1630:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
                   1631:     }
                   1632:     foreach my $key (keys(%{$indexhash})) {
                   1633:         if (defined($userdata->{$key})) {
                   1634:             $userlist->{$record_key}[$indexhash->{$key}] = $userdata->{$key};
                   1635:         }
                   1636:     }
                   1637:     return;
                   1638: }
                   1639: 
                   1640: sub courses_selector {
                   1641:     my ($cdom,$formname) = @_;
                   1642:     my %coursecodes = ();
                   1643:     my %codes = ();
                   1644:     my @codetitles = ();
                   1645:     my %cat_titles = ();
                   1646:     my %cat_order = ();
                   1647:     my %idlist = ();
                   1648:     my %idnums = ();
                   1649:     my %idlist_titles = ();
                   1650:     my $caller = 'global';
                   1651:     my $format_reply;
                   1652:     my $jscript = '';
                   1653: 
1.7       albertel 1654:     my $totcodes = 0;
                   1655:     $totcodes =
1.2       raeburn  1656:         &Apache::courseclassifier::retrieve_instcodes(\%coursecodes,
                   1657:                                                       $cdom,$totcodes);
                   1658:     if ($totcodes > 0) {
                   1659:         $format_reply =
                   1660:              &Apache::lonnet::auto_instcode_format($caller,$cdom,\%coursecodes,
                   1661:                                 \%codes,\@codetitles,\%cat_titles,\%cat_order);
                   1662:         if ($format_reply eq 'ok') {
                   1663:             my $numtypes = @codetitles;
                   1664:             &Apache::courseclassifier::build_code_selections(\%codes,\@codetitles,\%cat_titles,\%cat_order,\%idlist,\%idnums,\%idlist_titles);
                   1665:             my ($scripttext,$longtitles) = &Apache::courseclassifier::javascript_definitions(\@codetitles,\%idlist,\%idlist_titles,\%idnums,\%cat_titles);
                   1666:             my $longtitles_str = join('","',@{$longtitles});
                   1667:             my $allidlist = $idlist{$codetitles[0]};
                   1668:             $jscript .= &Apache::courseclassifier::courseset_js_start($formname,$longtitles_str,$allidlist);
                   1669:             $jscript .= $scripttext;
                   1670:             $jscript .= &Apache::courseclassifier::javascript_code_selections($formname,@codetitles);
                   1671:         }
                   1672:     }
                   1673:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($cdom);
                   1674: 
                   1675:     my %elements = (
                   1676:                      Year => 'selectbox',
                   1677:                      coursepick => 'radio',
                   1678:                      coursetotal => 'text',
                   1679:                      courselist => 'text',
                   1680:                    );
                   1681:     $jscript .= &Apache::lonhtmlcommon::set_form_elements(\%elements);
                   1682:     if ($env{'form.coursepick'} eq 'category') {
                   1683:         $jscript .= qq|
                   1684: function setCourseCat(formname) {
                   1685:     if (formname.Year.options[formname.Year.selectedIndex].value == -1) {
                   1686:         return;
                   1687:     }
                   1688:     courseSet('Year');
                   1689:     for (var j=0; j<formname.Semester.length; j++) {
                   1690:         if (formname.Semester.options[j].value == "$env{'form.Semester'}") {
                   1691:             formname.Semester.options[j].selected = true;
                   1692:         }
                   1693:     }
                   1694:     if (formname.Semester.options[formname.Semester.selectedIndex].value == -1) {
                   1695:         return;
                   1696:     }
                   1697:     courseSet('Semester');
                   1698:     for (var j=0; j<formname.Department.length; j++) {
                   1699:         if (formname.Department.options[j].value == "$env{'form.Department'}") {            formname.Department.options[j].selected = true;
                   1700:         }
                   1701:     }
                   1702:     if (formname.Department.options[formname.Department.selectedIndex].value == -1) {
                   1703:         return;
                   1704:     }
                   1705:     courseSet('Department');
                   1706:     for (var j=0; j<formname.Number.length; j++) {
                   1707:         if (formname.Number.options[j].value == "$env{'form.Number'}") {
                   1708:             formname.Number.options[j].selected = true;
                   1709:         }
                   1710:     }
                   1711: }
                   1712: |;
                   1713:     }
                   1714:     return ($cb_jscript,$jscript,$totcodes,\@codetitles,\%idlist,
                   1715:             \%idlist_titles);
                   1716: }
                   1717: 
                   1718: sub course_selector_loadcode {
                   1719:     my ($formname) = @_;
                   1720:     my $loadcode;
                   1721:     if ($env{'form.coursepick'} ne '') {
                   1722:         $loadcode = 'javascript:setFormElements(document.'.$formname.')';
                   1723:         if ($env{'form.coursepick'} eq 'category') {
                   1724:             $loadcode .= ';javascript:setCourseCat(document.'.$formname.')';
                   1725:         }
                   1726:     }
                   1727:     return $loadcode;
                   1728: }
                   1729: 
                   1730: sub process_coursepick {
                   1731:     my $coursefilter = $env{'form.coursepick'};
                   1732:     my $cdom = $env{'request.role.domain'};
                   1733:     my %courses;
                   1734:     if ($coursefilter eq 'all') {
                   1735:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.','.','.','.',
                   1736:                                                  undef,undef,'Course');
                   1737:     } elsif ($coursefilter eq 'category') {
                   1738:         my $instcode = &instcode_from_coursefilter();
                   1739:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.',$instcode,'.','.',
                   1740:                                                  undef,undef,'Course');
                   1741:     } elsif ($coursefilter eq 'specific') {
                   1742:         if ($env{'form.coursetotal'} > 1) {
                   1743:             my @course_ids = split(/&&/,$env{'form.courselist'});
                   1744:             foreach my $cid (@course_ids) {
                   1745:                 $courses{$cid} = '';
1.1       raeburn  1746:             }
1.2       raeburn  1747:         } else {
                   1748:             $courses{$env{'form.courselist'}} = '';
1.1       raeburn  1749:         }
1.2       raeburn  1750:     }
                   1751:     return %courses;
                   1752: }
                   1753: 
                   1754: sub instcode_from_coursefilter {
                   1755:     my $instcode = '';
                   1756:     my @cats = ('Semester','Year','Department','Number');
                   1757:     foreach my $category (@cats) {
                   1758:         if (defined($env{'form.'.$category})) {
                   1759:             unless ($env{'form.'.$category} eq '-1') {
                   1760:                 $instcode .= $env{'form.'.$category};
                   1761:            }
                   1762:         }
                   1763:     }
                   1764:     if ($instcode eq '') {
                   1765:         $instcode = '.';
                   1766:     }
                   1767:     return $instcode;
                   1768: }
                   1769: 
                   1770: sub display_adv_courseroles {
                   1771:     my $output;
                   1772:     #
                   1773:     # List course personnel
                   1774:     my %coursepersonnel = 
                   1775:        &Apache::lonnet::get_course_adv_roles($env{'request.course.id'});
                   1776:     #
                   1777:     $output = '<br />'.&Apache::loncommon::start_data_table();
                   1778:     foreach my $role (sort(keys(%coursepersonnel))) {
                   1779:         next if ($role =~ /^\s*$/);
                   1780:         $output .= &Apache::loncommon::start_data_table_row().
                   1781:                   '<td>'.$role.'</td><td>';
                   1782:         foreach my $user (split(',',$coursepersonnel{$role})) {
                   1783:             my ($puname,$pudom)=split(':',$user);
                   1784:             $output .= ' '.&Apache::loncommon::aboutmewrapper(
                   1785:                        &Apache::loncommon::plainname($puname,$pudom),
                   1786:                        $puname,$pudom);
                   1787:         }
                   1788:         $output .= '</td>'.&Apache::loncommon::end_data_table_row();
                   1789:     }
                   1790:     $output .= &Apache::loncommon::end_data_table();
                   1791: }
                   1792: 
                   1793: sub make_keylist_array {
                   1794:     my ($index,$keylist);
                   1795:     $index->{'domain'} = &Apache::loncoursedata::CL_SDOM();
                   1796:     $index->{'username'} = &Apache::loncoursedata::CL_SNAME();
                   1797:     $index->{'end'} = &Apache::loncoursedata::CL_END();
                   1798:     $index->{'start'} = &Apache::loncoursedata::CL_START();
                   1799:     $index->{'id'} = &Apache::loncoursedata::CL_ID();
                   1800:     $index->{'section'} = &Apache::loncoursedata::CL_SECTION();
                   1801:     $index->{'fullname'} = &Apache::loncoursedata::CL_FULLNAME();
                   1802:     $index->{'status'} = &Apache::loncoursedata::CL_STATUS();
                   1803:     $index->{'type'} = &Apache::loncoursedata::CL_TYPE();
                   1804:     $index->{'lockedtype'} = &Apache::loncoursedata::CL_LOCKEDTYPE();
                   1805:     $index->{'groups'} = &Apache::loncoursedata::CL_GROUP();
                   1806:     $index->{'email'} = &Apache::loncoursedata::CL_PERMANENTEMAIL();
                   1807:     $index->{'role'} = &Apache::loncoursedata::CL_ROLE();
                   1808:     $index->{'extent'} = &Apache::loncoursedata::CL_EXTENT();
1.44      raeburn  1809:     $index->{'photo'} = &Apache::loncoursedata::CL_PHOTO();
1.47      raeburn  1810:     $index->{'thumbnail'} = &Apache::loncoursedata::CL_THUMBNAIL();
1.2       raeburn  1811:     foreach my $key (keys(%{$index})) {
                   1812:         $keylist->[$index->{$key}] = $key;
                   1813:     }
                   1814:     return ($index,$keylist);
                   1815: }
                   1816: 
                   1817: sub aggregate_user_info {
                   1818:     my ($udom,$uname,$userinfo) = @_;
                   1819:     my %info=&Apache::lonnet::get('environment',
                   1820:                                   ['firstname','middlename',
                   1821:                                    'lastname','generation','id'],
                   1822:                                    $udom,$uname);
                   1823:     my ($tmp) = keys(%info);
                   1824:     my ($fullname,$id);
                   1825:     if ($tmp =~/^(con_lost|error|no_such_host)/i) {
                   1826:         $fullname = 'not available';
                   1827:         $id = 'not available';
                   1828:         &Apache::lonnet::logthis('unable to retrieve environment '.
                   1829:                                  'for '.$uname.':'.$udom);
1.1       raeburn  1830:     } else {
1.2       raeburn  1831:         $fullname = &Apache::lonnet::format_name(@info{qw/firstname middlename lastname generation/},'lastname');
                   1832:         $id = $info{'id'};
                   1833:     }
                   1834:     $userinfo->{$uname.':'.$udom} = { 
                   1835:                                       fullname => $fullname,
                   1836:                                       id       => $id,
                   1837:                                     };
                   1838:     return;
                   1839: }
1.1       raeburn  1840: 
1.2       raeburn  1841: sub process_date_info {
                   1842:     my ($userdata) = @_;
                   1843:     my $now = time;
                   1844:     $userdata->{'status'} = 'Active';
                   1845:     if ($userdata->{'start'} > 0) {
                   1846:         if ($now < $userdata->{'start'}) {
                   1847:             $userdata->{'status'} = 'Future';
                   1848:         }
1.1       raeburn  1849:     }
1.2       raeburn  1850:     if ($userdata->{'end'} > 0) {
                   1851:         if ($now > $userdata->{'end'}) {
                   1852:             $userdata->{'status'} = 'Expired';
                   1853:         }
                   1854:     }
                   1855:     return;
1.1       raeburn  1856: }
                   1857: 
                   1858: sub show_users_list {
1.10      raeburn  1859:     my ($r,$context,$mode,$permission,$statusmode,$userlist,$keylist)=@_;
1.1       raeburn  1860:     #
                   1861:     # Variables for excel output
                   1862:     my ($excel_workbook, $excel_sheet, $excel_filename,$row,$format);
                   1863:     #
                   1864:     # Variables for csv output
                   1865:     my ($CSVfile,$CSVfilename);
                   1866:     #
                   1867:     my $sortby = $env{'form.sortby'};
1.3       raeburn  1868:     my @sortable = ('username','domain','id','fullname','start','end','email','role');
1.2       raeburn  1869:     if ($context eq 'course') {
1.3       raeburn  1870:         push(@sortable,('section','groups','type'));
1.2       raeburn  1871:     } else {
1.3       raeburn  1872:         push(@sortable,'extent');
                   1873:     }
                   1874:     if (!grep(/^\Q$sortby\E$/,@sortable)) {
                   1875:         $sortby = 'username';
1.1       raeburn  1876:     }
1.22      raeburn  1877:     my $setting = $env{'form.roletype'};
1.35      raeburn  1878:     my ($cid,$cdom,$cnum,$classgroups,$displayphotos,$displayclickers);
1.1       raeburn  1879:     if ($context eq 'course') {
1.22      raeburn  1880:         $cid = $env{'request.course.id'};
1.17      raeburn  1881:         ($cnum,$cdom) = &get_course_identity($cid);
1.2       raeburn  1882:         ($classgroups) = &Apache::loncoursedata::get_group_memberships(
                   1883:                                      $userlist,$keylist,$cdom,$cnum);
1.16      raeburn  1884:         if ($mode eq 'autoenroll') {
                   1885:             $env{'form.showrole'} = 'st';
                   1886:         } else {
                   1887:             if (! exists($env{'form.displayphotos'})) {
                   1888:                 $env{'form.displayphotos'} = 'off';
                   1889:             }
                   1890:             $displayphotos = $env{'form.displayphotos'};
                   1891:             if (! exists($env{'form.displayclickers'})) {
                   1892:                 $env{'form.displayclickers'} = 'off';
                   1893:             }
                   1894:             $displayclickers = $env{'form.displayclickers'};
                   1895:             if ($env{'course.'.$cid.'.internal.showphoto'}) {
                   1896:                 $r->print('
1.1       raeburn  1897: <script type="text/javascript">
                   1898: function photowindow(photolink) {
                   1899:     var title = "Photo_Viewer";
                   1900:     var options = "scrollbars=1,resizable=1,menubar=0";
                   1901:     options += ",width=240,height=240";
                   1902:     stdeditbrowser = open(photolink,title,options,"1");
                   1903:     stdeditbrowser.focus();
                   1904: }
                   1905: </script>
1.16      raeburn  1906:                ');
                   1907:             }
                   1908:             $r->print(<<END);
1.1       raeburn  1909: <input type="hidden" name="displayphotos" value="$displayphotos" />
                   1910: <input type="hidden" name="displayclickers" value="$displayclickers" />
                   1911: END
1.16      raeburn  1912:         }
1.1       raeburn  1913:     }
1.16      raeburn  1914:     if ($mode ne 'autoenroll') {
1.11      raeburn  1915:         my $check_uncheck_js = &Apache::loncommon::check_uncheck_jscript();
                   1916:         my $alert = &mt("You must select at least one user by checking a user's 'Select' checkbox");
1.25      raeburn  1917:         my $singconfirm = &mt(' for a single user?');
                   1918:         my $multconfirm = &mt(' for multiple users?');
1.40      raeburn  1919:         my $date_sec_selector = &date_section_javascript($context,$setting,$statusmode);
                   1920:         my %lt = &Apache::lonlocal::texthash( 
                   1921:               acwi => 'Access will be set to start immediately',
                   1922:               asyo => 'as you did not select an end date in the pop-up window',
                   1923:               accw => 'Access will be set to continue indefinitely',
                   1924:               asyd => 'as you did not select an end date in the pop-up window',
                   1925:               sewi => "Sections will be switched to 'No section'",
                   1926:               ayes => "as you either selected the 'No section' option",
                   1927:               oryo => 'or you did not select a section in the pop-up window',
                   1928:               arol => 'A role with no section will be added',
                   1929:               swbs => 'Sections will be switched to:',
                   1930:               rwba => 'Roles will be added for section(s):',
                   1931:         );
1.1       raeburn  1932:         $r->print(<<END);
1.10      raeburn  1933: 
                   1934: <script type="text/javascript" language="Javascript">
1.11      raeburn  1935: $check_uncheck_js
                   1936: 
                   1937: function verify_action (field) {
                   1938:     var numchecked = 0;
                   1939:     var singconf = '$singconfirm';
                   1940:     var multconf = '$multconfirm';
                   1941:     if (field.length > 0) {
                   1942:         for (i = 0; i < field.length; i++) {
                   1943:             if (field[i].checked == true) {
                   1944:                numchecked ++;
                   1945:             }
                   1946:         }
                   1947:     } else {
                   1948:         if (field.checked == true) {
                   1949:             numchecked ++;
                   1950:         }
                   1951:     }
                   1952:     if (numchecked == 0) {
                   1953:         alert("$alert");
                   1954:     } 
                   1955:     else {
                   1956:         var message = document.studentform.bulkaction[document.studentform.bulkaction.selectedIndex].text;
1.40      raeburn  1957:         var choice = document.studentform.bulkaction[document.studentform.bulkaction.selectedIndex].value;
1.11      raeburn  1958:         if (numchecked == 1) { 
                   1959:             message += singconf;
                   1960:         } 
                   1961:         else {
                   1962:             message += multconf; 
                   1963:         }
1.40      raeburn  1964:         if (choice == 'chgdates' || choice == 'reenable' || choice == 'activate') {
                   1965:             var datemsg = '';
                   1966:             if ((document.studentform.startdate_month.value == '') && 
                   1967:                 (document.studentform.startdate_day.value  == '') &&
                   1968:                 (document.studentform.startdate_year.value == '')) {
                   1969:                 datemsg = "\\n$lt{'acwi'},\\n$lt{'asyo'}.\\n";
                   1970:             }
                   1971:             if ((document.studentform.enddate_month.value == '') &&
                   1972:                 (document.studentform.enddate_day.value  == '') &&
                   1973:                 (document.studentform.enddate_year.value == '')) {
                   1974:                 datemsg += "\\n$lt{'accw'},\\n$lt{'asyd'}.\\n";
                   1975:             }
                   1976:             if (datemsg != '') {
                   1977:                 message += "\\n"+datemsg;
                   1978:             }
                   1979:         }
                   1980:         if (choice == 'chgsec') {
                   1981:             var rolefilter = document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value;
                   1982:             var retained =  document.studentform.retainsec.value;
                   1983:             var secshow = document.studentform.newsecs.value;
                   1984:             if (secshow == '') {
                   1985:                 if (rolefilter == 'st' || retained == 0 || retained == "") {
                   1986:                     message += "\\n\\n$lt{'sewi'},\\n$lt{'ayes'},\\n$lt{'oryo'}.\\n"; 
                   1987:                 } else {
                   1988:                     message += "\\n\\n$lt{'arol'}\\n$lt{'ayes'},\\n$lt{'oryo'}.\\n";
                   1989:                 }
                   1990:             } else {
                   1991:                 if (rolefilter == 'st' || retained == 0 || retained == "") {
                   1992:                     message += "\\n\\n$lt{'swbs'} "+secshow+".\\n";
                   1993:                 } else {
                   1994:                     message += "\\n\\n$lt{'rwba'} "+secshow+".\\n";
                   1995:                 }
                   1996:             }
                   1997:         }
1.11      raeburn  1998:         if (confirm(message)) {
                   1999:             document.studentform.phase.value = 'bulkchange';
                   2000:             document.studentform.submit();
                   2001:         }
                   2002:     }
                   2003: }
1.10      raeburn  2004: 
                   2005: function username_display_launch(username,domain) {
                   2006:     var target;
                   2007:     for (var i=0; i<document.studentform.usernamelink.length; i++) {
                   2008:         if (document.studentform.usernamelink[i].checked) {
                   2009:             target = document.studentform.usernamelink[i].value;
                   2010:         }
                   2011:     }
                   2012:     if (target == 'modify') {
1.50      raeburn  2013:         if (document.studentform.userwin.checked == true) {
                   2014:             var url = '/adm/createuser?srchterm='+username+'&srchdomain='+domain+'&phase=get_user_info&action=singleuser&srchin=dom&srchby=uname&srchtype=exact&popup=1';
                   2015:             var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2016:             modifywin = window.open(url,'',options,1);
                   2017:             modifywin.focus();
                   2018:             return;
                   2019:         } else {
                   2020:             document.studentform.srchterm.value=username;
                   2021:             document.studentform.srchdomain.value=domain;
                   2022:             document.studentform.phase.value='get_user_info';
                   2023:             document.studentform.action.value = 'singleuser';
                   2024:             document.studentform.submit();
                   2025:         }
1.10      raeburn  2026:     }
1.48      raeburn  2027:     if (target == 'aboutme') {
1.50      raeburn  2028:         if (document.studentform.userwin.checked == true) {
                   2029:             var url = '/adm/'+domain+'/'+username+'/aboutme?popup=1';
                   2030:             var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2031:             aboutmewin = window.open(url,'',options,1);
                   2032:             aboutmewin.focus();
                   2033:             return;
                   2034:         } else {
                   2035:             document.location.href = '/adm/'+domain+'/'+username+'/aboutme';
                   2036:         }
1.48      raeburn  2037:     }
1.10      raeburn  2038: }
                   2039: </script>
1.11      raeburn  2040: $date_sec_selector
1.1       raeburn  2041: <input type="hidden" name="state" value="$env{'form.state'}" />
                   2042: END
                   2043:     }
                   2044:     $r->print(<<END);
                   2045: <input type="hidden" name="sortby" value="$sortby" />
                   2046: END
                   2047: 
                   2048:     my %lt=&Apache::lonlocal::texthash(
                   2049:                        'username'   => "username",
                   2050:                        'domain'     => "domain",
                   2051:                        'id'         => 'ID',
                   2052:                        'fullname'   => "name",
                   2053:                        'section'    => "section",
                   2054:                        'groups'     => "active groups",
                   2055:                        'start'      => "start date",
                   2056:                        'end'        => "end date",
                   2057:                        'status'     => "status",
1.2       raeburn  2058:                        'role'       => "role",
1.1       raeburn  2059:                        'type'       => "enroll type/action",
                   2060:                        'email'      => "email address",
                   2061:                        'clicker'    => "clicker id",
                   2062:                        'photo'      => "photo",
1.2       raeburn  2063:                        'extent'     => "extent",
1.41      raeburn  2064:                        'go'         => "go",
1.11      raeburn  2065:                        'pr'         => "Proceed",
                   2066:                        'ca'         => "check all",
                   2067:                        'ua'         => "uncheck all",
                   2068:                        'ac'         => "Action to take for selected users",
1.10      raeburn  2069:                        'link'       => "Behavior of username links",
                   2070:                        'aboutme'    => "Display a user's personal page",
1.50      raeburn  2071:                        'owin'       => "Open in a new window",
1.10      raeburn  2072:                        'modify'     => "Modify a user's information",
1.1       raeburn  2073:                       );
1.2       raeburn  2074:     if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
                   2075:         $lt{'extent'} = &mt('Course(s): description, section(s), status');
1.13      raeburn  2076:     } elsif ($context eq 'author') {
1.2       raeburn  2077:         $lt{'extent'} = &mt('Author'); 
                   2078:     }
1.1       raeburn  2079:     my @cols = ('username','domain','id','fullname');
                   2080:     if ($context eq 'course') {
                   2081:         push(@cols,'section');
                   2082:     }
1.2       raeburn  2083:     if (!($context eq 'domain' && $env{'form.roletype'} eq 'course')) { 
                   2084:         push(@cols,('start','end'));
                   2085:     }
1.3       raeburn  2086:     if ($env{'form.showrole'} eq 'Any' || $env{'form.showrole'} eq 'cr') {
1.2       raeburn  2087:         push(@cols,'role');
                   2088:     }
1.13      raeburn  2089:     if ($context eq 'domain' && ($env{'form.roletype'} eq 'author' ||
1.2       raeburn  2090:                                 $env{'form.roletype'} eq 'course')) {
                   2091:         push (@cols,'extent');
                   2092:     }
                   2093:     if (($statusmode eq 'Any') && 
                   2094:         (!($context eq 'domain' && $env{'form.roletype'} eq 'course'))) {
1.1       raeburn  2095:         push(@cols,'status');
                   2096:     }
                   2097:     if ($context eq 'course') {
                   2098:         push(@cols,'groups');
                   2099:     }
                   2100:     push(@cols,'email');
                   2101: 
1.4       raeburn  2102:     my $rolefilter = $env{'form.showrole'};
1.5       raeburn  2103:     if ($env{'form.showrole'} eq 'cr') {
                   2104:         $rolefilter = &mt('custom');  
                   2105:     } elsif ($env{'form.showrole'} ne 'Any') {
1.2       raeburn  2106:         $rolefilter = &Apache::lonnet::plaintext($env{'form.showrole'});
                   2107:     }
1.16      raeburn  2108:     my $results_description;
                   2109:     if ($mode ne 'autoenroll') {
                   2110:         $results_description = &results_header_row($rolefilter,$statusmode,
1.24      raeburn  2111:                                                    $context,$permission,$mode);
1.16      raeburn  2112:         $r->print('<b>'.$results_description.'</b><br />');
                   2113:     }
1.26      raeburn  2114:     my ($output,$actionselect,%canchange,%canchangesec);
1.16      raeburn  2115:     if ($mode eq 'html' || $mode eq 'view' || $mode eq 'autoenroll') {
                   2116:         if ($mode ne 'autoenroll') {
                   2117:             if ($permission->{'cusr'}) {
                   2118:                 $actionselect = &select_actions($context,$setting,$statusmode);
                   2119:             }
                   2120:             $r->print(<<END);
1.10      raeburn  2121: <input type="hidden" name="srchby"  value="uname" />
                   2122: <input type="hidden" name="srchin"   value="dom" />
                   2123: <input type="hidden" name="srchtype" value="exact" />
                   2124: <input type="hidden" name="srchterm" value="" />
1.11      raeburn  2125: <input type="hidden" name="srchdomain" value="" /> 
1.1       raeburn  2126: END
1.16      raeburn  2127:             $output = '<p>';
1.50      raeburn  2128:             my @linkdests = ('aboutme');
1.16      raeburn  2129:             if ($permission->{'cusr'}) {
1.48      raeburn  2130:                 unshift (@linkdests,'modify');
                   2131:             }
                   2132:             $output .= '<span class="LC_nobreak">'.$lt{'link'}.':&nbsp;';
                   2133:             my $usernamelink = $env{'form.usernamelink'};
                   2134:             if ($usernamelink eq '') {
                   2135:                 $usernamelink = 'aboutme';
                   2136:             }
                   2137:             foreach my $item (@linkdests) {
                   2138:                 my $checkedstr = '';
                   2139:                 if ($item eq $usernamelink) {
                   2140:                     $checkedstr = ' checked="checked" ';
1.16      raeburn  2141:                 }
1.48      raeburn  2142:                 $output .= '<label><input type="radio" name="usernamelink" value="'.$item.'"'.$checkedstr.'>&nbsp;'.$lt{$item}.'</label>&nbsp;&nbsp;';
1.16      raeburn  2143:             }
1.50      raeburn  2144:             my $checkwin;
                   2145:             if ($env{'form.userwin'}) { 
                   2146:                 $checkwin = 'checked = "checked"'; 
                   2147:             }
                   2148:             $output .= '&nbsp;&nbsp;&nbsp;&nbsp;<input type="checkbox" name="userwin" value="1" $checkwin />'.$lt{'owin'}.'</span><br />';
1.16      raeburn  2149:             if ($actionselect) {
1.41      raeburn  2150:                 $output .= <<"END";
                   2151: $lt{'ac'}:&nbsp;$actionselect <input type="button" value="$lt{'go'}" onclick="javascript:opendatebrowser(this.form,'studentform','go')" /></p>
1.11      raeburn  2152: <p><input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.actionlist)" /> &nbsp;
1.41      raeburn  2153: <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.actionlist)" /><br /><br /><input type="button" value="$lt{'pr'}" onclick="javascript:verify_action(document.studentform.actionlist)" />
1.11      raeburn  2154: END
1.26      raeburn  2155:                 my @allroles;
                   2156:                 if ($env{'form.showrole'} eq 'Any') {
                   2157:                     my $custom = 1;
                   2158:                     if ($context eq 'domain') {
                   2159:                         @allroles = &roles_by_context($setting,$custom);
                   2160:                     } else {
                   2161:                         @allroles = &roles_by_context($context,$custom);
                   2162:                     }
                   2163:                 } else {
                   2164:                     @allroles = ($env{'form.showrole'});
                   2165:                 }
                   2166:                 foreach my $role (@allroles) {
                   2167:                     if ($context eq 'domain') {
                   2168:                         if ($setting eq 'domain') {
                   2169:                             if (&Apache::lonnet::allowed('c'.$role,
                   2170:                                     $env{'request.role.domain'})) {
                   2171:                                 $canchange{$role} = 1;
                   2172:                             }
1.31      raeburn  2173:                         } elsif ($setting eq 'author') {
                   2174:                             if (&Apache::lonnet::allowed('c'.$role,
                   2175:                                     $env{'request.role.domain'})) {
                   2176:                                 $canchange{$role} = 1;
                   2177:                             }
1.26      raeburn  2178:                         }
                   2179:                     } elsif ($context eq 'author') {
                   2180:                         if (&Apache::lonnet::allowed('c'.$role,
                   2181:                             $env{'user.domain'}.'/'.$env{'user.name'})) {
                   2182:                             $canchange{$role} = 1;
                   2183:                         }
                   2184:                     } elsif ($context eq 'course') {
                   2185:                         if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
                   2186:                             $canchange{$role} = 1;
                   2187:                         } elsif ($env{'request.course.sec'} ne '') {
                   2188:                             if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
                   2189:                                 $canchangesec{$role} = $env{'request.course.sec'};
                   2190:                             }
                   2191:                         }
                   2192:                     }
                   2193:                 }
1.16      raeburn  2194:             }
1.4       raeburn  2195:         }
                   2196:         $output .= "\n<p>\n".
1.1       raeburn  2197:                   &Apache::loncommon::start_data_table().
1.4       raeburn  2198:                   &Apache::loncommon::start_data_table_header_row();
1.1       raeburn  2199:         if ($mode eq 'autoenroll') {
1.4       raeburn  2200:             $output .= "
1.1       raeburn  2201:  <th><a href=\"javascript:document.studentform.sortby.value='type';document.studentform.submit();\">$lt{'type'}</a></th>
1.4       raeburn  2202:             ";
1.1       raeburn  2203:         } else {
1.11      raeburn  2204:             $output .= "\n".'<th>'.&mt('Count').'</th>'."\n";
                   2205:             if ($actionselect) {
                   2206:                 $output .= '<th>'.&mt('Select').'</th>'."\n";
                   2207:             }
1.1       raeburn  2208:         }
                   2209:         foreach my $item (@cols) {
1.4       raeburn  2210:             $output .= "<th><a href=\"javascript:document.studentform.sortby.value='$item';document.studentform.submit();\">$lt{$item}</a></th>\n";
1.1       raeburn  2211:         }
1.2       raeburn  2212:         my %role_types = &role_type_names();
1.16      raeburn  2213:         if ($context eq 'course' && $mode ne 'autoenroll') {
1.4       raeburn  2214:             if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
                   2215:                 # Clicker display on or off?
                   2216:                 my %clicker_options = &Apache::lonlocal::texthash(
                   2217:                                                             'on' => 'Show',
                   2218:                                                             'off' => 'Hide',
                   2219:                                                            );
                   2220:                 my $clickerchg = 'on';
                   2221:                 if ($displayclickers eq 'on') {
                   2222:                     $clickerchg = 'off';
                   2223:                 }
                   2224:                 $output .= '    <th>'."\n".'     '.
                   2225:                     '<a href="javascript:document.studentform.displayclickers.value='.
1.1       raeburn  2226:                       "'".$clickerchg."'".';document.studentform.submit();">'.
                   2227:                       $clicker_options{$clickerchg}.'</a>&nbsp;'.$lt{'clicker'}."\n".
1.4       raeburn  2228:                       '    </th>'."\n";
1.1       raeburn  2229: 
1.4       raeburn  2230:                 # Photo display on or off?
                   2231:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
                   2232:                     my %photo_options = &Apache::lonlocal::texthash(
                   2233:                                                             'on' => 'Show',
                   2234:                                                             'off' => 'Hide',
                   2235:                                                                 );
                   2236:                     my $photochg = 'on';
                   2237:                     if ($displayphotos eq 'on') {
                   2238:                         $photochg = 'off';
                   2239:                     }
                   2240:                     $output .= '    <th>'."\n".'     '.
                   2241:                 '<a href="javascript:document.studentform.displayphotos.value='.
1.1       raeburn  2242:                       "'".$photochg."'".';document.studentform.submit();">'.
                   2243:                       $photo_options{$photochg}.'</a>&nbsp;'.$lt{'photo'}."\n".
1.4       raeburn  2244:                       '    </th>'."\n";
                   2245:                 }
1.1       raeburn  2246:             }
1.4       raeburn  2247:         }
1.16      raeburn  2248:         $output .= &Apache::loncommon::end_data_table_header_row();
1.1       raeburn  2249: # Done with the HTML header line
                   2250:     } elsif ($mode eq 'csv') {
                   2251:         #
                   2252:         # Open a file
                   2253:         $CSVfilename = '/prtspool/'.
1.2       raeburn  2254:                        $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
                   2255:                        time.'_'.rand(1000000000).'.csv';
1.1       raeburn  2256:         unless ($CSVfile = Apache::File->new('>/home/httpd'.$CSVfilename)) {
                   2257:             $r->log_error("Couldn't open $CSVfilename for output $!");
                   2258:             $r->print("Problems occured in writing the csv file.  ".
                   2259:                       "This error has been logged.  ".
                   2260:                       "Please alert your LON-CAPA administrator.");
                   2261:             $CSVfile = undef;
                   2262:         }
                   2263:         #
                   2264:         # Write headers and data to file
1.2       raeburn  2265:         print $CSVfile '"'.$results_description.'"'."\n"; 
1.1       raeburn  2266:         print $CSVfile '"'.join('","',map {
                   2267:             &Apache::loncommon::csv_translate($lt{$_})
                   2268:             } (@cols)).'"'."\n";
                   2269:     } elsif ($mode eq 'excel') {
                   2270:         # Create the excel spreadsheet
                   2271:         ($excel_workbook,$excel_filename,$format) =
                   2272:             &Apache::loncommon::create_workbook($r);
                   2273:         return if (! defined($excel_workbook));
                   2274:         $excel_sheet = $excel_workbook->addworksheet('userlist');
1.2       raeburn  2275:         $excel_sheet->write($row++,0,$results_description,$format->{'h2'});
1.1       raeburn  2276:         #
                   2277:         my @colnames = map {$lt{$_}} (@cols);
                   2278:         $excel_sheet->write($row++,0,\@colnames,$format->{'bold'});
                   2279:     }
                   2280: 
                   2281: # Done with header lines in all formats
                   2282:     my %index;
                   2283:     my $i;
1.2       raeburn  2284:     foreach my $idx (@$keylist) {
                   2285:         $index{$idx} = $i++;
                   2286:     }
1.4       raeburn  2287:     my $usercount = 0;
1.33      raeburn  2288:     my ($secfilter,$grpfilter);
                   2289:     if ($context eq 'course') {
                   2290:         $secfilter = $env{'form.secfilter'};
                   2291:         $grpfilter = $env{'form.grpfilter'};
                   2292:         if ($secfilter eq '') {
                   2293:             $secfilter = 'all';
                   2294:         }
                   2295:         if ($grpfilter eq '') {
                   2296:             $grpfilter = 'all';
                   2297:         }
                   2298:     }
1.2       raeburn  2299:     # Get groups, role, permanent e-mail so we can sort on them if
                   2300:     # necessary.
                   2301:     foreach my $user (keys(%{$userlist})) {
1.43      raeburn  2302:         if ($user eq '' ) {
                   2303:             delete($userlist->{$user});
                   2304:             next;
                   2305:         }
1.11      raeburn  2306:         if ($context eq 'domain' &&  $user eq $env{'request.role.domain'}.'-domainconfig:'.$env{'request.role.domain'}) {
                   2307:             delete($userlist->{$user});
                   2308:             next;
                   2309:         }
1.2       raeburn  2310:         my ($uname,$udom,$role,$groups,$email);
1.5       raeburn  2311:         if (($statusmode ne 'Any') && 
                   2312:                  ($userlist->{$user}->[$index{'status'}] ne $statusmode)) {
                   2313:             delete($userlist->{$user});
                   2314:             next;
                   2315:         }
1.2       raeburn  2316:         if ($context eq 'domain') {
                   2317:             if ($env{'form.roletype'} eq 'domain') {
                   2318:                 ($role,$uname,$udom) = split(/:/,$user);
1.11      raeburn  2319:                 if (($uname eq $env{'request.role.domain'}.'-domainconfig') &&
                   2320:                     ($udom eq $env{'request.role.domain'})) {
                   2321:                     delete($userlist->{$user});
                   2322:                     next;
                   2323:                 }
1.13      raeburn  2324:             } elsif ($env{'form.roletype'} eq 'author') {
1.2       raeburn  2325:                 ($uname,$udom,$role) = split(/:/,$user,-1);
                   2326:             } elsif ($env{'form.roletype'} eq 'course') {
                   2327:                 ($uname,$udom,$role) = split(/:/,$user);
                   2328:             }
                   2329:         } else {
                   2330:             ($uname,$udom,$role) = split(/:/,$user,-1);
                   2331:             if (($context eq 'course') && $role eq '') {
                   2332:                 $role = 'st';
                   2333:             }
                   2334:         }
                   2335:         $userlist->{$user}->[$index{'role'}] = $role;
                   2336:         if (($env{'form.showrole'} ne 'Any') && (!($env{'form.showrole'}  eq 'cr' && $role =~ /^cr\//)) && ($role ne $env{'form.showrole'})) {
                   2337:             delete($userlist->{$user});
                   2338:             next;
                   2339:         }
1.33      raeburn  2340:         if ($context eq 'course') {
                   2341:             my @ac_groups;
                   2342:             if (ref($classgroups) eq 'HASH') {
                   2343:                 $groups = $classgroups->{$user};
                   2344:             }
                   2345:             if (ref($groups->{'active'}) eq 'HASH') {
                   2346:                 @ac_groups = keys(%{$groups->{'active'}});
                   2347:                 $userlist->{$user}->[$index{'groups'}] = join(', ',@ac_groups);
                   2348:             }
                   2349:             if ($mode ne 'autoenroll') {
                   2350:                 my $section = $userlist->{$user}->[$index{'section'}];
1.43      raeburn  2351:                 if (($env{'request.course.sec'} ne '') && 
                   2352:                     ($section ne $env{'request.course.sec'})) {
                   2353:                     if ($role eq 'st') {
                   2354:                         delete($userlist->{$user});
                   2355:                         next;
                   2356:                     }
                   2357:                 }
1.33      raeburn  2358:                 if ($secfilter eq 'none') {
                   2359:                     if ($section ne '') {
                   2360:                         delete($userlist->{$user});
                   2361:                         next;
                   2362:                     }
                   2363:                 } elsif ($secfilter ne 'all') {
                   2364:                     if ($section ne $secfilter) {
                   2365:                         delete($userlist->{$user});
                   2366:                         next;
                   2367:                     }
                   2368:                 }
                   2369:                 if ($grpfilter eq 'none') {
                   2370:                     if (@ac_groups > 0) {
                   2371:                         delete($userlist->{$user});
                   2372:                         next;
                   2373:                     }
                   2374:                 } elsif ($grpfilter ne 'all') {
                   2375:                     if (!grep(/^\Q$grpfilter\E$/,@ac_groups)) {
                   2376:                         delete($userlist->{$user});
                   2377:                         next;
                   2378:                     }
                   2379:                 }
1.44      raeburn  2380:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
                   2381:                     if (($displayphotos eq 'on') && ($role eq 'st')) {
                   2382:                         $userlist->{$user}->[$index{'photo'}] =
1.47      raeburn  2383:                             &Apache::lonnet::retrievestudentphoto($udom,$uname,'jpg');
                   2384:                         $userlist->{$user}->[$index{'thumbnail'}] =
1.44      raeburn  2385:                             &Apache::lonnet::retrievestudentphoto($udom,$uname,
                   2386:                                                                 'gif','thumbnail');
                   2387:                     }
                   2388:                 }
1.33      raeburn  2389:             }
1.2       raeburn  2390:         }
                   2391:         my %emails   = &Apache::loncommon::getemails($uname,$udom);
                   2392:         if ($emails{'permanentemail'} =~ /\S/) {
                   2393:             $userlist->{$user}->[$index{'email'}] = $emails{'permanentemail'};
                   2394:         }
1.4       raeburn  2395:         $usercount ++;
                   2396:     }
                   2397:     my $autocount = 0;
                   2398:     my $manualcount = 0;
                   2399:     my $lockcount = 0;
                   2400:     my $unlockcount = 0;
                   2401:     if ($usercount) {
                   2402:         $r->print($output);
                   2403:     } else {
                   2404:         if ($mode eq 'autoenroll') {
                   2405:             return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
                   2406:         } else {
                   2407:             return;
                   2408:         }
1.1       raeburn  2409:     }
1.2       raeburn  2410:     #
                   2411:     # Sort the users
1.1       raeburn  2412:     my $index  = $index{$sortby};
                   2413:     my $second = $index{'username'};
                   2414:     my $third  = $index{'domain'};
1.2       raeburn  2415:     my @sorted_users = sort {
                   2416:         lc($userlist->{$a}->[$index])  cmp lc($userlist->{$b}->[$index])
1.1       raeburn  2417:             ||
1.2       raeburn  2418:         lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second])            ||
                   2419:         lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
                   2420:         } (keys(%$userlist));
1.4       raeburn  2421:     my $rowcount = 0;
1.2       raeburn  2422:     foreach my $user (@sorted_users) {
1.4       raeburn  2423:         my %in;
1.2       raeburn  2424:         my $sdata = $userlist->{$user};
1.4       raeburn  2425:         $rowcount ++; 
1.2       raeburn  2426:         foreach my $item (@{$keylist}) {
                   2427:             $in{$item} = $sdata->[$index{$item}];
                   2428:         }
1.11      raeburn  2429:         my $role = $in{'role'};
1.2       raeburn  2430:         $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}]); 
                   2431:         if (! defined($in{'start'}) || $in{'start'} == 0) {
                   2432:             $in{'start'} = &mt('none');
                   2433:         } else {
                   2434:             $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
1.1       raeburn  2435:         }
1.2       raeburn  2436:         if (! defined($in{'end'}) || $in{'end'} == 0) {
                   2437:             $in{'end'} = &mt('none');
1.1       raeburn  2438:         } else {
1.2       raeburn  2439:             $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
1.1       raeburn  2440:         }
1.2       raeburn  2441:         if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll') {
                   2442:             $r->print(&Apache::loncommon::start_data_table_row());
1.11      raeburn  2443:             my $checkval;
1.16      raeburn  2444:             if ($mode eq 'autoenroll') {
                   2445:                 my $cellentry;
                   2446:                 if ($in{'type'} eq 'auto') {
                   2447:                     $cellentry = '<b>'.&mt('auto').'</b>&nbsp;<label><input type="checkbox" name="chgauto" value="'.$in{'username'}.':'.$in{'domain'}.'" />&nbsp;Change</label>';
                   2448:                     $autocount ++;
                   2449:                 } else {
                   2450:                     $cellentry = '<table border="0" cellspacing="0"><tr><td rowspan="2"><b>'.&mt('manual').'</b></td><td><nobr><label><input type="checkbox" name="chgmanual" value="'.$in{'username'}.':'.$in{'domain'}.'" />&nbsp;Change</label></nobr></td></tr><tr><td><nobr>';
                   2451:                     $manualcount ++;
                   2452:                     if ($in{'lockedtype'}) {
                   2453:                         $cellentry .= '<label><input type="checkbox" name="unlockchg" value="'.$in{'username'}.':'.$in{'domain'}.'" />&nbsp;'.&mt('Unlock').'</label>';
                   2454:                         $unlockcount ++;
                   2455:                     } else {
                   2456:                         $cellentry .= '<label><input type="checkbox" name="lockchg" value="'.$in{'username'}.':'.$in{'domain'}.'" />&nbsp;'.&mt('Lock').'</label>';
                   2457:                         $lockcount ++;
1.11      raeburn  2458:                     }
1.16      raeburn  2459:                     $cellentry .= '</nobr></td></tr></table>';
                   2460:                 }
                   2461:                 $r->print("<td>$cellentry</td>\n");
                   2462:             } else {
                   2463:                 $r->print("<td>$rowcount</td>\n");
                   2464:                 if ($actionselect) {
1.26      raeburn  2465:                     my $showcheckbox;
                   2466:                     if ($role =~ /^cr\//) {
                   2467:                         $showcheckbox = $canchange{'cr'};
                   2468:                     } else {
                   2469:                         $showcheckbox = $canchange{$role};
                   2470:                     }
                   2471:                     if (!$showcheckbox) {
                   2472:                         if ($context eq 'course') {
                   2473:                             if ($canchangesec{$role} ne '') {
                   2474:                                 if ($canchangesec{$role} eq $in{'section'}) {
                   2475:                                     $showcheckbox = 1;
                   2476:                                 }
                   2477:                             }
1.16      raeburn  2478:                         }
1.26      raeburn  2479:                     }
                   2480:                     if ($showcheckbox) {
                   2481:                         $checkval = $user; 
                   2482:                         if ($context eq 'course') {
                   2483:                             if ($role eq 'st') {
                   2484:                                 $checkval .= ':st';
                   2485:                             }
                   2486:                             $checkval .= ':'.$in{'section'};
                   2487:                             if ($role eq 'st') {
                   2488:                                 $checkval .= ':'.$in{'type'}.':'.
                   2489:                                              $in{'lockedtype'};
                   2490:                             }
1.16      raeburn  2491:                         }
1.26      raeburn  2492:                         $r->print('<td><input type="checkbox" name="'.
                   2493:                                   'actionlist" value="'.$checkval.'"></td>');
                   2494:                     } else {
                   2495:                         $r->print('<td>&nbsp;</td>');
1.16      raeburn  2496:                     }
1.11      raeburn  2497:                 }
                   2498:             }
1.2       raeburn  2499:             foreach my $item (@cols) {
1.10      raeburn  2500:                 if ($item eq 'username') {
1.48      raeburn  2501:                     $r->print('<td>'.&print_username_link($mode,\%in).'</td>');
1.16      raeburn  2502:                 } elsif (($item eq 'start' || $item eq 'end') && ($actionselect)) {
1.11      raeburn  2503:                     $r->print('<td>'.$in{$item}.'<input type="hidden" name="'.$checkval.'_'.$item.'" value="'.$sdata->[$index{$item}].'" /></td>'."\n");
1.10      raeburn  2504:                 } else {
                   2505:                     $r->print('<td>'.$in{$item}.'</td>'."\n");
                   2506:                 }
1.2       raeburn  2507:             }
1.16      raeburn  2508:             if (($context eq 'course') && ($mode ne 'autoenroll')) {
1.4       raeburn  2509:                 if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
                   2510:                     if ($displayclickers eq 'on') {
                   2511:                         my $clickers =
1.2       raeburn  2512:                    (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
1.4       raeburn  2513:                         if ($clickers!~/\w/) { $clickers='-'; }
                   2514:                         $r->print('<td>'.$clickers.'</td>');
1.2       raeburn  2515:                     } else {
                   2516:                         $r->print('    <td>&nbsp;</td>  ');
                   2517:                     }
1.4       raeburn  2518:                     if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.44      raeburn  2519:                         if ($displayphotos eq 'on' && $role eq 'st' && $in{'photo'} ne '') {
1.47      raeburn  2520:                             $r->print('    <td align="right"><a href="javascript:photowindow('."'".$in{'photo'}."'".')"><img src="'.$in{'thumbnail'}.'" border="1"></a></td>');
1.4       raeburn  2521:                         } else {
                   2522:                             $r->print('    <td>&nbsp;</td>  ');
                   2523:                         }
                   2524:                     }
1.2       raeburn  2525:                 }
                   2526:             }
                   2527:             $r->print(&Apache::loncommon::end_data_table_row());
                   2528:         } elsif ($mode eq 'csv') {
                   2529:             next if (! defined($CSVfile));
                   2530:             # no need to bother with $linkto
                   2531:             if (! defined($in{'start'}) || $in{'start'} == 0) {
                   2532:                 $in{'start'} = &mt('none');
                   2533:             } else {
                   2534:                 $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
                   2535:             }
                   2536:             if (! defined($in{'end'}) || $in{'end'} == 0) {
                   2537:                 $in{'end'} = &mt('none');
                   2538:             } else {
                   2539:                 $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
                   2540:             }
                   2541:             my @line = ();
                   2542:             foreach my $item (@cols) {
                   2543:                 push @line,&Apache::loncommon::csv_translate($in{$item});
                   2544:             }
                   2545:             print $CSVfile '"'.join('","',@line).'"'."\n";
                   2546:         } elsif ($mode eq 'excel') {
                   2547:             my $col = 0;
                   2548:             foreach my $item (@cols) {
                   2549:                 if ($item eq 'start' || $item eq 'end') {
                   2550:                     if (defined($item) && $item != 0) {
                   2551:                         $excel_sheet->write($row,$col++,
                   2552:                             &Apache::lonstathelpers::calc_serial($in{item}),
                   2553:                                     $format->{'date'});
                   2554:                     } else {
                   2555:                         $excel_sheet->write($row,$col++,'none');
                   2556:                     }
                   2557:                 } else {
                   2558:                     $excel_sheet->write($row,$col++,$in{$item});
                   2559:                 }
                   2560:             }
                   2561:             $row++;
1.1       raeburn  2562:         }
                   2563:     }
1.2       raeburn  2564:     if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll') {
                   2565:             $r->print(&Apache::loncommon::end_data_table().'<br />');
                   2566:     } elsif ($mode eq 'excel') {
                   2567:         $excel_workbook->close();
                   2568:         $r->print('<p><a href="'.$excel_filename.'">'.
                   2569:                   &mt('Your Excel spreadsheet').'</a> '.&mt('is ready for download').'.</p>'."\n");
                   2570:     } elsif ($mode eq 'csv') {
                   2571:         close($CSVfile);
                   2572:         $r->print('<a href="'.$CSVfilename.'">'.
                   2573:                   &mt('Your CSV file').'</a> is ready for download.'.
                   2574:                   "\n");
                   2575:         $r->rflush();
                   2576:     }
                   2577:     if ($mode eq 'autoenroll') {
                   2578:         return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
1.4       raeburn  2579:     } else {
                   2580:         return ($usercount);
1.2       raeburn  2581:     }
1.1       raeburn  2582: }
                   2583: 
1.10      raeburn  2584: sub print_username_link {
1.48      raeburn  2585:     my ($mode,$in) = @_;
1.10      raeburn  2586:     my $output;
1.16      raeburn  2587:     if ($mode eq 'autoenroll') {
                   2588:         $output = $in->{'username'};
1.10      raeburn  2589:     } else {
                   2590:         $output = '<a href="javascript:username_display_launch('.
                   2591:                   "'$in->{'username'}','$in->{'domain'}'".')" />'.
                   2592:                   $in->{'username'}.'</a>';
                   2593:     }
                   2594:     return $output;
                   2595: }
                   2596: 
1.2       raeburn  2597: sub role_type_names {
                   2598:     my %lt = &Apache::lonlocal::texthash (
1.13      raeburn  2599:                          'domain' => 'Domain Roles',
                   2600:                          'author' => 'Co-Author Roles',
                   2601:                          'course' => 'Course Roles',
1.2       raeburn  2602:              );
                   2603:     return %lt;
                   2604: }
                   2605: 
1.11      raeburn  2606: sub select_actions {
                   2607:     my ($context,$setting,$statusmode) = @_;
                   2608:     my %lt = &Apache::lonlocal::texthash(
                   2609:                 revoke   => "Revoke user roles",
                   2610:                 delete   => "Delete user roles",
                   2611:                 reenable => "Re-enable expired user roles",
                   2612:                 activate => "Make future user roles active now",
                   2613:                 chgdates  => "Change starting/ending dates",
                   2614:                 chgsec   => "Change section associated with user roles",
                   2615:     );
                   2616:     my ($output,$options,%choices);
1.23      raeburn  2617:     # FIXME Disable actions for now for roletype=course in domain context
                   2618:     if ($context eq 'domain' && $setting eq 'course') {
                   2619:         return;
                   2620:     }
1.26      raeburn  2621:     if ($context eq 'course') {
                   2622:         if ($env{'form.showrole'} ne 'Any') {
                   2623:              if (!&Apache::lonnet::allowed('c'.$env{'form.showrole'},
                   2624:                                            $env{'request.course.id'})) {
                   2625:                  if ($env{'request.course.sec'} eq '') {
                   2626:                      return;
                   2627:                  } else {
                   2628:                      if (!&Apache::lonnet::allowed('c'.$env{'form.showrole'},$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
                   2629:                          return;
                   2630:                      }
                   2631:                  }
                   2632:             }
                   2633:         }
                   2634:     }
1.11      raeburn  2635:     if ($statusmode eq 'Any') {
                   2636:         $options .= '
                   2637: <option value="chgdates">'.$lt{'chgdates'}.'</option>';
                   2638:         $choices{'dates'} = 1;
                   2639:     } else {
                   2640:         if ($statusmode eq 'Future') {
                   2641:             $options .= '
                   2642: <option value="activate">'.$lt{'activate'}.'</option>';
                   2643:             $choices{'dates'} = 1;
                   2644:         } elsif ($statusmode eq 'Expired') {
                   2645:             $options .= '
                   2646: <option value="reenable">'.$lt{'reenable'}.'</option>';
                   2647:             $choices{'dates'} = 1;
                   2648:         }
1.13      raeburn  2649:         if ($statusmode eq 'Active' || $statusmode eq 'Future') {
                   2650:             $options .= '
                   2651: <option value="chgdates">'.$lt{'chgdates'}.'</option>
                   2652: <option value="revoke">'.$lt{'revoke'}.'</option>';
                   2653:             $choices{'dates'} = 1;
                   2654:         }
1.11      raeburn  2655:     }
                   2656:     if ($context eq 'domain') {
                   2657:         $options .= '
                   2658: <option value="delete">'.$lt{'delete'}.'</option>';
                   2659:     }
                   2660:     if (($context eq 'course') || ($context eq 'domain' && $setting eq 'course')) {
1.26      raeburn  2661:         if (($statusmode ne 'Expired') && ($env{'request.course.sec'} eq '')) {
1.11      raeburn  2662:             $options .= '
                   2663: <option value="chgsec">'.$lt{'chgsec'}.'</option>';
                   2664:             $choices{'sections'} = 1;
                   2665:         }
                   2666:     }
                   2667:     if ($options) {
1.41      raeburn  2668:         $output = '<select name="bulkaction" onchange="javascript:opendatebrowser(this.form,'."'studentform','change'".')" />'."\n".
1.11      raeburn  2669:                   '<option value="" selected="selected">'.
                   2670:                   &mt('Please select').'</option>'."\n".$options."\n".'</select>';
                   2671:         if ($choices{'dates'}) {
                   2672:             $output .= 
                   2673:                 '<input type="hidden" name="startdate_month" value="" />'."\n".
                   2674:                 '<input type="hidden" name="startdate_day" value="" />'."\n".
                   2675:                 '<input type="hidden" name="startdate_year" value="" />'."\n".
                   2676:                 '<input type="hidden" name="startdate_hour" value="" />'."\n".
                   2677:                 '<input type="hidden" name="startdate_minute" value="" />'."\n".
                   2678:                 '<input type="hidden" name="startdate_second" value="" />'."\n".
                   2679:                 '<input type="hidden" name="enddate_month" value="" />'."\n".
                   2680:                 '<input type="hidden" name="enddate_day" value="" />'."\n".
                   2681:                 '<input type="hidden" name="enddate_year" value="" />'."\n".
                   2682:                 '<input type="hidden" name="enddate_hour" value="" />'."\n".
                   2683:                 '<input type="hidden" name="enddate_minute" value="" />'."\n".
                   2684:                 '<input type="hidden" name="enddate_second" value="" />'."\n";
                   2685:             if ($context eq 'course') {
                   2686:                 $output .= '<input type="hidden" name="makedatesdefault" value="" />'."\n";
                   2687:             }
                   2688:         }
                   2689:         if ($choices{'sections'}) {
                   2690:             $output .= '<input type="hidden" name="retainsec" value= "" />'."\n".
                   2691:                        '<input type="hidden" name="newsecs" value= "" />'."\n";
                   2692:         }
                   2693:     }
                   2694:     return $output;
                   2695: }
                   2696: 
                   2697: sub date_section_javascript {
                   2698:     my ($context,$setting) = @_;
1.49      raeburn  2699:     my $title = 'Date_And_Section_Selector';
1.41      raeburn  2700:     my %nopopup = &Apache::lonlocal::texthash (
                   2701:         revoke => "Check the boxes for any users for whom roles are to be revoked, and click 'Proceed'",
                   2702:         delete => "Check the boxes for any users for whom roles are to be deleted, and click 'Proceed'",
                   2703:         none   => "Choose an action to take for selected users",
                   2704:     );  
1.11      raeburn  2705:     my $output = '
1.49      raeburn  2706: <script type="text/javascript">'."\n";
1.11      raeburn  2707:     $output .= <<"ENDONE";
1.41      raeburn  2708:     function opendatebrowser(callingform,formname,calledby) {
1.11      raeburn  2709:         var bulkaction = callingform.bulkaction.options[callingform.bulkaction.selectedIndex].value;
                   2710:         if (bulkaction == 'revoke' || bulkaction == 'delete' || bulkaction == '') {
1.41      raeburn  2711:             if (calledby == 'go') {
                   2712:                 if (bulkaction == 'revoke') {
                   2713:                     alert("$nopopup{'revoke'}");
                   2714:                 }
                   2715:                 if (bulkaction == 'delete') {
                   2716:                     alert("$nopopup{'delete'}"); 
                   2717:                 }
                   2718:                 if (bulkaction == '') {
                   2719:                     alert("$nopopup{'none'}");
                   2720:                 }
                   2721:             }
1.11      raeburn  2722:             return;
                   2723:         }
                   2724:         var url = '/adm/createuser?';
                   2725:         var type = '';
                   2726:         var showrole = callingform.showrole.options[callingform.showrole.selectedIndex].value;
                   2727: ENDONE
                   2728:     if ($context eq 'domain') {
                   2729:         $output .= '
                   2730:         type = callingform.roletype.options[callingform.roletype.selectedIndex].value;
                   2731: ';
                   2732:     }
                   2733:     my $width= '700';
                   2734:     my $height = '400';
                   2735:     $output .= <<"ENDTWO";
                   2736:         url += 'action=dateselect&callingform=' + formname + 
                   2737:                '&roletype='+type+'&showrole='+showrole +'&bulkaction='+bulkaction;
                   2738:         var title = '$title';
                   2739:         var options = 'scrollbars=1,resizable=1,menubar=0';
                   2740:         options += ',width=$width,height=$height';
                   2741:         stdeditbrowser = open(url,title,options,'1');
                   2742:         stdeditbrowser.focus();
                   2743:     }
                   2744: </script>
                   2745: ENDTWO
                   2746:     return $output;
                   2747: }
                   2748: 
                   2749: sub date_section_selector {
1.21      raeburn  2750:     my ($context,$permission) = @_;
1.11      raeburn  2751:     my $callingform = $env{'form.callingform'};
                   2752:     my $formname = 'dateselect';  
                   2753:     my $groupslist = &get_groupslist();
                   2754:     my $sec_js = &setsections_javascript($formname,$groupslist);
                   2755:     my $output = <<"END";
                   2756: <script type="text/javascript">
                   2757: 
                   2758: $sec_js
                   2759: 
                   2760: function saveselections(formname) {
                   2761: 
                   2762: END
                   2763:     if ($env{'form.bulkaction'} eq 'chgsec') {
                   2764:         $output .= <<"END";
1.40      raeburn  2765:         if (formname.retainsec.length > 1) {  
                   2766:             for (var i=0; i<formname.retainsec.length; i++) {
                   2767:                 if (formname.retainsec[i].checked == true) {
                   2768:                     opener.document.$callingform.retainsec.value = formname.retainsec[i].value;
                   2769:                 }
                   2770:             }
                   2771:         } else {
                   2772:             opener.document.$callingform.retainsec.value = formname.retainsec.value;
                   2773:         }
1.11      raeburn  2774:         setSections(formname);
                   2775:         if (seccheck == 'ok') {
                   2776:             opener.document.$callingform.newsecs.value = formname.sections.value;
                   2777:             window.close();
                   2778:         }
                   2779:         return;
                   2780: END
                   2781:     } else {
                   2782:         if ($context eq 'course') {
                   2783:             if (($env{'form.bulkaction'} eq 'reenable') || 
                   2784:                 ($env{'form.bulkaction'} eq 'activate') || 
                   2785:                 ($env{'form.bulkaction'} eq 'chgdates')) {
1.26      raeburn  2786:                 if ($env{'request.course.sec'} eq '') {
                   2787:                     $output .= <<"END";
1.11      raeburn  2788:  
                   2789:         if (formname.makedatesdefault.checked == true) {
                   2790:             opener.document.$callingform.makedatesdefault.value = 1;
                   2791:         }
                   2792:         else {
                   2793:             opener.document.$callingform.makedatesdefault.value = 0;
                   2794:         }
                   2795: 
                   2796: END
1.26      raeburn  2797:                 }
1.11      raeburn  2798:             }
                   2799:         }
                   2800:         $output .= <<"END";
                   2801:     opener.document.$callingform.startdate_month.value =  formname.startdate_month.options[formname.startdate_month.selectedIndex].value;
                   2802:     opener.document.$callingform.startdate_day.value =  formname.startdate_day.value;
                   2803:     opener.document.$callingform.startdate_year.value = formname.startdate_year.value;
                   2804:     opener.document.$callingform.startdate_hour.value =  formname.startdate_hour.options[formname.startdate_hour.selectedIndex].value;
                   2805:     opener.document.$callingform.startdate_minute.value =  formname.startdate_minute.value;
                   2806:     opener.document.$callingform.startdate_second.value = formname.startdate_second.value;
                   2807:     opener.document.$callingform.enddate_month.value =  formname.enddate_month.options[formname.enddate_month.selectedIndex].value;
                   2808:     opener.document.$callingform.enddate_day.value =  formname.enddate_day.value;
                   2809:     opener.document.$callingform.enddate_year.value = formname.enddate_year.value;
                   2810:     opener.document.$callingform.enddate_hour.value =  formname.enddate_hour.options[formname.enddate_hour.selectedIndex].value;
                   2811:     opener.document.$callingform.enddate_minute.value =  formname.enddate_minute.value;
                   2812:     opener.document.$callingform.enddate_second.value = formname.enddate_second.value;
                   2813:     window.close();
                   2814: END
                   2815:     }
                   2816:     $output .= '
                   2817: }
                   2818: </script>
                   2819: ';
                   2820:     my %lt = &Apache::lonlocal::texthash (
                   2821:                  chac => 'Access dates to apply for selected users',
                   2822:                  chse => 'Changes in section affiliation to apply to selected users',
                   2823:                  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.',
                   2824:                  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.',
                   2825:                  reta => "Retain each user's current section affiliations?", 
                   2826:                  dnap => '(Does not apply to student roles).', 
                   2827:             );
                   2828:     my ($date_items,$headertext);
                   2829:     if ($env{'form.bulkaction'} eq 'chgsec') {
                   2830:         $headertext = $lt{'chse'};
                   2831:     } else {
                   2832:         $headertext = $lt{'chac'};
                   2833:         my $starttime;
                   2834:         if (($env{'form.bulkaction'} eq 'activate') || 
                   2835:             ($env{'form.bulkaction'} eq 'reenable')) {
                   2836:             $starttime = time;
                   2837:         }
                   2838:         $date_items = &date_setting_table($starttime,undef,$context,
1.21      raeburn  2839:                                           $env{'form.bulkaction'},$formname,
                   2840:                                           $permission);
1.11      raeburn  2841:     }
                   2842:     $output .= '<h3>'.$headertext.'</h3>'.
                   2843:                '<form name="'.$formname.'" method="post">'."\n".
                   2844:                 $date_items;
                   2845:     if ($context eq 'course' && $env{'form.bulkaction'} eq 'chgsec') {
1.17      raeburn  2846:         my ($cnum,$cdom) = &get_course_identity();
1.11      raeburn  2847:         my $info;
                   2848:         if ($env{'form.showrole'} eq 'st') {
                   2849:             $output .= '<p>'.$lt{'fors'}.'</p>'; 
1.26      raeburn  2850:         } elsif ($env{'form.showrole'} eq 'Any') {
1.11      raeburn  2851:             $output .= '<p>'.$lt{'fors'}.'</p>'.
                   2852:                        '<p>'.$lt{'forn'}.'&nbsp;';
                   2853:             $info = $lt{'reta'};
                   2854:         } else {
                   2855:             $output .= '<p>'.$lt{'forn'}.'&nbsp;';
                   2856:             $info = $lt{'reta'};
                   2857:         }
                   2858:         if ($info) {
                   2859:             $info .= '<span class="LC_nobreak">'.
                   2860:                      '<label><input type="radio" name="retainsec" value="1" '.
                   2861:                      'checked="checked" />'.&mt('Yes').'</label>&nbsp;&nbsp;'.
                   2862:                      '<label><input type="radio" name="retainsec" value="0" />'.
                   2863:                      &mt('No').'</label></span>';
                   2864:             if ($env{'form.showrole'} eq 'Any') {
                   2865:                 $info .= '<br />'.$lt{'dnap'};
                   2866:             }
                   2867:             $info .= '</p>';
                   2868:         } else {
                   2869:             $info = '<input type="hidden" name="retainsec" value="0" />'; 
                   2870:         }
1.21      raeburn  2871:         my $rowtitle = &mt('New section to assign');
                   2872:         my $secbox = &section_picker($cdom,$cnum,$env{'form.showrole'},$rowtitle,$permission,$context);
1.11      raeburn  2873:         $output .= $info.$secbox;
                   2874:     }
                   2875:     $output .= '<p>'.
                   2876: &mt('Use "Save" to update the main window with your selections.').'<br /><br />'.
                   2877: '<input type="button" name="dateselection" value="'.&mt('Save').'" onclick="javascript:saveselections(this.form)" /></p>'."\n".
                   2878: '</form>';
                   2879:     return $output;
                   2880: }
                   2881: 
1.17      raeburn  2882: sub section_picker {
                   2883:     my ($cdom,$cnum,$role,$rowtitle,$permission,$context,$mode) = @_;
                   2884:     my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
                   2885:     my $sections_select .= &course_sections(\%sections_count,$role);
                   2886:     my $secbox = '<p>'.&Apache::lonhtmlcommon::start_pick_box()."\n";
                   2887:     if ($mode eq 'upload') {
                   2888:         my ($options,$cb_script,$coursepick) =
                   2889:             &default_role_selector($context,1);
                   2890:         $secbox .= &Apache::lonhtmlcommon::row_title('role','LC_oddrow_value').
                   2891:                    $options. &Apache::lonhtmlcommon::row_closure(1)."\n";
                   2892:     }
                   2893:     $secbox .= &Apache::lonhtmlcommon::row_title($rowtitle,'LC_oddrow_value')."\n";
                   2894:     if ($env{'request.course.sec'} eq '') {
                   2895:         $secbox .= '<table class="LC_createuser"><tr class="LC_section_row">'."\n".
                   2896:                    '<td align="center">'.&mt('Existing sections')."\n".
                   2897:                    '<br />'.$sections_select.'</td><td align="center">'.
                   2898:                    &mt('New section').'<br />'."\n".
                   2899:                    '<input type="text" name="newsec" size="15" />'."\n".
                   2900:                    '<input type="hidden" name="sections" value="" />'."\n".
                   2901:                    '</td></tr></table>'."\n";
                   2902:     } else {
                   2903:        $secbox .= '<input type="hidden" name="sections" value="'.
                   2904:                    $env{'request.course.sec'}.'" />'.
                   2905:                    $env{'request.course.sec'};
                   2906:     }
                   2907:     $secbox .= &Apache::lonhtmlcommon::row_closure(1)."\n".
                   2908:                &Apache::lonhtmlcommon::end_pick_box().'</p>';
                   2909:     return $secbox;
                   2910: }
                   2911: 
1.2       raeburn  2912: sub results_header_row {
1.24      raeburn  2913:     my ($rolefilter,$statusmode,$context,$permission,$mode) = @_;
1.5       raeburn  2914:     my ($description,$showfilter);
                   2915:     if ($rolefilter ne 'Any') {
                   2916:         $showfilter = $rolefilter;
                   2917:     }
1.2       raeburn  2918:     if ($context eq 'course') {
1.24      raeburn  2919:         if ($mode eq 'csv' || $mode eq 'excel') {
                   2920:             $description = &mt('Course - ').$env{'course.'.$env{'request.course.id'}.'.description'}.': ';
                   2921:         }
1.2       raeburn  2922:         if ($statusmode eq 'Expired') {
1.5       raeburn  2923:             $description .= &mt('Users in course with expired [_1] roles',$showfilter);
1.11      raeburn  2924:         } elsif ($statusmode eq 'Future') {
1.5       raeburn  2925:             $description .= &mt('Users in course with future [_1] roles',$showfilter);
1.2       raeburn  2926:         } elsif ($statusmode eq 'Active') {
1.5       raeburn  2927:             $description .= &mt('Users in course with active [_1] roles',$showfilter);
1.2       raeburn  2928:         } else {
                   2929:             if ($rolefilter eq 'Any') {
                   2930:                 $description .= &mt('All users in course');
                   2931:             } else {
                   2932:                 $description .= &mt('All users in course with [_1] roles',$rolefilter);
                   2933:             }
                   2934:         }
1.33      raeburn  2935:         my $constraint;
1.26      raeburn  2936:         my $viewablesec = &viewable_section($permission);
                   2937:         if ($viewablesec ne '') {
1.15      raeburn  2938:             if ($env{'form.showrole'} eq 'st') {
1.33      raeburn  2939:                 $constraint = &mt('only users in section "[_1]"',$viewablesec);
1.26      raeburn  2940:             } elsif ($env{'form.showrole'} ne 'cc') {
1.33      raeburn  2941:                 $constraint = &mt('only users affiliated with no section or section "[_1]"',$viewablesec);
                   2942:             }
                   2943:             if (($env{'form.grpfilter'} ne 'all') && ($env{'form.grpfilter'} ne '')) {
                   2944:                 if ($env{'form.grpfilter'} eq 'none') {
                   2945:                     $constraint .= &mt(' and not in any group');
                   2946:                 } else {
                   2947:                     $constraint .= &mt(' and members of group: "[_1]"',$env{'form.grpfilter'});
                   2948:                 }
                   2949:             }
                   2950:         } else {
                   2951:             if (($env{'form.secfilter'} ne 'all') && ($env{'form.secfilter'} ne '')) {
                   2952:                 if ($env{'form.secfilter'} eq 'none') {
                   2953:                     $constraint = &mt('only users affiliated with no section');
                   2954:                 } else {
                   2955:                     $constraint = &mt('only users affiliated with section "[_1]"',$env{'form.secfilter'});
                   2956:                 }
                   2957:             }
                   2958:             if (($env{'form.grpfilter'} ne 'all') && ($env{'form.grpfilter'} ne '')) {
                   2959:                 if ($env{'form.grpfilter'} eq 'none') {
                   2960:                     if ($constraint eq '') {
                   2961:                         $constraint = &mt('only users not in any group');
                   2962:                     } else {
                   2963:                         $constraint .= &mt(' and also not in any group'); 
                   2964:                     }
                   2965:                 } else {
                   2966:                     if ($constraint eq '') {
                   2967:                         $constraint = &mt('only members of group: "[_1]"',$env{'form.grpfilter'});
                   2968:                     } else {
                   2969:                         $constraint .= &mt(' and also members of group: "[_1]"'.$env{'form.grpfilter'});
                   2970:                     }
                   2971:                 }
1.15      raeburn  2972:             }
                   2973:         }
1.33      raeburn  2974:         if ($constraint ne '') {
                   2975:             $description .= ' ('.$constraint.')';
                   2976:         } 
1.13      raeburn  2977:     } elsif ($context eq 'author') {
1.14      raeburn  2978:         $description = 
                   2979:             &mt('Author space for <span class="LC_cusr_emph">[_1]</span>',
                   2980:         &Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'})).':&nbsp;&nbsp;';
1.2       raeburn  2981:         if ($statusmode eq 'Expired') {
1.5       raeburn  2982:             $description .= &mt('Co-authors with expired [_1] roles',$showfilter);
1.2       raeburn  2983:         } elsif ($statusmode eq 'Future') {
1.5       raeburn  2984:             $description .= &mt('Co-authors with future [_1] roles',$showfilter);
1.2       raeburn  2985:         } elsif ($statusmode eq 'Active') {
1.5       raeburn  2986:             $description .= &mt('Co-authors with active [_1] roles',$showfilter);
1.2       raeburn  2987:         } else {
                   2988:             if ($rolefilter eq 'Any') {
1.5       raeburn  2989:                 $description .= &mt('All co-authors');
1.2       raeburn  2990:             } else {
                   2991:                 $description .= &mt('All co-authors with [_1] roles',$rolefilter);
                   2992:             }
                   2993:         }
                   2994:     } elsif ($context eq 'domain') {
                   2995:         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
                   2996:         $description = &mt('Domain - ').$domdesc.': ';
                   2997:         if ($env{'form.roletype'} eq 'domain') {
                   2998:             if ($statusmode eq 'Expired') {
1.5       raeburn  2999:                 $description .= &mt('Users in domain with expired [_1] roles',$showfilter);
1.2       raeburn  3000:             } elsif ($statusmode eq 'Future') {
1.5       raeburn  3001:                 $description .= &mt('Users in domain with future [_1] roles',$showfilter);
1.2       raeburn  3002:             } elsif ($statusmode eq 'Active') {
1.5       raeburn  3003:                 $description .= &mt('Users in domain with active [_1] roles',$showfilter);
1.2       raeburn  3004:             } else {
                   3005:                 if ($rolefilter eq 'Any') {
1.5       raeburn  3006:                     $description .= &mt('All users in domain');
1.2       raeburn  3007:                 } else {
                   3008:                     $description .= &mt('All users in domain with [_1] roles',$rolefilter);
                   3009:                 }
                   3010:             }
1.13      raeburn  3011:         } elsif ($env{'form.roletype'} eq 'author') {
1.2       raeburn  3012:             if ($statusmode eq 'Expired') {
1.5       raeburn  3013:                 $description .= &mt('Co-authors in domain with expired [_1] roles',$showfilter);
1.2       raeburn  3014:             } elsif ($statusmode eq 'Future') {
1.5       raeburn  3015:                 $description .= &mt('Co-authors in domain with future [_1] roles',$showfilter);
1.2       raeburn  3016:             } elsif ($statusmode eq 'Active') {
1.5       raeburn  3017:                $description .= &mt('Co-authors in domain with active [_1] roles',$showfilter);
1.2       raeburn  3018:             } else {
                   3019:                 if ($rolefilter eq 'Any') {
1.5       raeburn  3020:                     $description .= &mt('All users with co-author roles in domain',$showfilter);
1.2       raeburn  3021:                 } else {
                   3022:                     $description .= &mt('All co-authors in domain  with [_1] roles',$rolefilter);
                   3023:                 }
                   3024:             }
                   3025:         } elsif ($env{'form.roletype'} eq 'course') {
                   3026:             my $coursefilter = $env{'form.coursepick'};
                   3027:             if ($coursefilter eq 'category') {
                   3028:                 my $instcode = &instcode_from_coursefilter();
                   3029:                 if ($instcode eq '.') {
                   3030:                     $description .= &mt('All courses in domain').' - ';
                   3031:                 } else {
                   3032:                     $description .= &mt('Courses in domain with institutional code: [_1]',$instcode).' - ';
                   3033:                 }
                   3034:             } elsif ($coursefilter eq 'selected') {
                   3035:                 $description .= &mt('Selected courses in domain').' - ';
                   3036:             } elsif ($coursefilter eq 'all') {
                   3037:                 $description .= &mt('All courses in domain').' - ';
                   3038:             }
                   3039:             if ($statusmode eq 'Expired') {
1.5       raeburn  3040:                 $description .= &mt('users with expired [_1] roles',$showfilter);
1.2       raeburn  3041:             } elsif ($statusmode eq 'Future') {
1.5       raeburn  3042:                 $description .= &mt('users with future [_1] roles',$showfilter);
1.2       raeburn  3043:             } elsif ($statusmode eq 'Active') {
1.5       raeburn  3044:                 $description .= &mt('users with active [_1] roles',$showfilter);
1.2       raeburn  3045:             } else {
                   3046:                 if ($rolefilter eq 'Any') {
                   3047:                     $description .= &mt('all users');
                   3048:                 } else {
                   3049:                     $description .= &mt('users with [_1] roles',$rolefilter);
                   3050:                 }
                   3051:             }
                   3052:         }
                   3053:     }
                   3054:     return $description;
                   3055: }
1.22      raeburn  3056: 
                   3057: sub viewable_section {
                   3058:     my ($permission) = @_;
                   3059:     my $viewablesec;
                   3060:     if (ref($permission) eq 'HASH') {
                   3061:         if (exists($permission->{'view_section'})) {
                   3062:             $viewablesec = $permission->{'view_section'};
                   3063:         } elsif (exists($permission->{'cusr_section'})) {
                   3064:             $viewablesec = $permission->{'cusr_section'};
                   3065:         }
                   3066:     }
                   3067:     return $viewablesec;
                   3068: }
                   3069: 
1.2       raeburn  3070:     
1.1       raeburn  3071: #################################################
                   3072: #################################################
                   3073: sub show_drop_list {
1.30      raeburn  3074:     my ($r,$classlist,$nosort,$permission) = @_;
1.29      raeburn  3075:     my $cid = $env{'request.course.id'};
1.17      raeburn  3076:     my ($cnum,$cdom) = &get_course_identity($cid);
1.1       raeburn  3077:     if (! exists($env{'form.sortby'})) {
                   3078:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   3079:                                                 ['sortby']);
                   3080:     }
                   3081:     my $sortby = $env{'form.sortby'};
                   3082:     if ($sortby !~ /^(username|domain|section|groups|fullname|id|start|end)$/) {
                   3083:         $sortby = 'username';
                   3084:     }
                   3085:     my $action = "drop";
1.17      raeburn  3086:     my $check_uncheck_js = &Apache::loncommon::check_uncheck_jscript();
1.1       raeburn  3087:     $r->print(<<END);
                   3088: <input type="hidden" name="sortby" value="$sortby" />
                   3089: <input type="hidden" name="action" value="$action" />
                   3090: <input type="hidden" name="state"  value="done" />
1.17      raeburn  3091: <script type="text/javascript" language="Javascript">
                   3092: $check_uncheck_js
1.1       raeburn  3093: </script>
                   3094: <p>
                   3095: <input type="hidden" name="phase" value="four">
                   3096: END
1.30      raeburn  3097:     my ($indexhash,$keylist) = &make_keylist_array();
                   3098:     my $studentcount = 0;
                   3099:     if (ref($classlist) eq 'HASH') {
                   3100:         foreach my $student (keys(%{$classlist})) {
                   3101:             my $sdata = $classlist->{$student}; 
                   3102:             my $status = $sdata->[$indexhash->{'status'}];
                   3103:             my $section = $sdata->[$indexhash->{'section'}];
                   3104:             if ($status ne 'Active') {
                   3105:                 delete($classlist->{$student});
                   3106:                 next;
                   3107:             }
                   3108:             if ($env{'request.course.sec'} ne '') {
                   3109:                 if ($section ne $env{'request.course.sec'}) {
                   3110:                     delete($classlist->{$student});
                   3111:                     next;
                   3112:                 }
                   3113:             }
                   3114:             $studentcount ++;
                   3115:         }
                   3116:     }
                   3117:     if (!$studentcount) {
                   3118:         $r->print(&mt('There are no students to drop.'));
                   3119:         return;
                   3120:     }
                   3121:     my ($classgroups) = &Apache::loncoursedata::get_group_memberships(
                   3122:                                               $classlist,$keylist,$cdom,$cnum);
                   3123:     my %lt=&Apache::lonlocal::texthash('usrn'   => "username",
                   3124:                                        'dom'    => "domain",
                   3125:                                        'sn'     => "student name",
                   3126:                                        'sec'    => "section",
                   3127:                                        'start'  => "start date",
                   3128:                                        'end'    => "end date",
                   3129:                                        'groups' => "active groups",
                   3130:                                       );
1.1       raeburn  3131:     if ($nosort) {
1.17      raeburn  3132:         $r->print(&Apache::loncommon::start_data_table().
                   3133:                   &Apache::loncommon::start_data_table_header_row());
1.1       raeburn  3134:         $r->print(<<END);
                   3135:     <th>&nbsp;</th>
                   3136:     <th>$lt{'usrn'}</th>
                   3137:     <th>$lt{'dom'}</th>
                   3138:     <th>ID</th>
                   3139:     <th>$lt{'sn'}</th>
                   3140:     <th>$lt{'sec'}</th>
                   3141:     <th>$lt{'start'}</th>
                   3142:     <th>$lt{'end'}</th>
                   3143:     <th>$lt{'groups'}</th>
                   3144: END
1.17      raeburn  3145:         $r->print(&Apache::loncommon::end_data_table_header_row());
1.1       raeburn  3146:     } else  {
1.17      raeburn  3147:         $r->print(&Apache::loncommon::start_data_table().
                   3148:                   &Apache::loncommon::start_data_table_header_row());
1.1       raeburn  3149:         $r->print(<<END);
1.17      raeburn  3150:     <th>&nbsp;</th>
1.1       raeburn  3151:     <th>
1.17      raeburn  3152:        <a href="/adm/createuser?action=$action&sortby=username">$lt{'usrn'}</a>
1.1       raeburn  3153:     </th><th>
1.17      raeburn  3154:        <a href="/adm/createuser?action=$action&sortby=domain">$lt{'dom'}</a>
1.1       raeburn  3155:     </th><th>
1.17      raeburn  3156:        <a href="/adm/createuser?action=$action&sortby=id">ID</a>
1.1       raeburn  3157:     </th><th>
1.17      raeburn  3158:        <a href="/adm/createuser?action=$action&sortby=fullname">$lt{'sn'}</a>
1.1       raeburn  3159:     </th><th>
1.17      raeburn  3160:        <a href="/adm/createuser?action=$action&sortby=section">$lt{'sec'}</a>
1.1       raeburn  3161:     </th><th>
1.17      raeburn  3162:        <a href="/adm/createuser?action=$action&sortby=start">$lt{'start'}</a>
1.1       raeburn  3163:     </th><th>
1.17      raeburn  3164:        <a href="/adm/createuser?action=$action&sortby=end">$lt{'end'}</a>
1.1       raeburn  3165:     </th><th>
1.17      raeburn  3166:        <a href="/adm/createuser?action=$action&sortby=groups">$lt{'groups'}</a>
1.1       raeburn  3167:     </th>
                   3168: END
1.17      raeburn  3169:         $r->print(&Apache::loncommon::end_data_table_header_row());
1.1       raeburn  3170:     }
                   3171:     #
                   3172:     # Sort the students
1.30      raeburn  3173:     my $index  = $indexhash->{$sortby};
                   3174:     my $second = $indexhash->{'username'};
                   3175:     my $third  = $indexhash->{'domain'};
1.1       raeburn  3176:     my @Sorted_Students = sort {
                   3177:         lc($classlist->{$a}->[$index])  cmp lc($classlist->{$b}->[$index])
                   3178:             ||
                   3179:         lc($classlist->{$a}->[$second]) cmp lc($classlist->{$b}->[$second])
                   3180:             ||
                   3181:         lc($classlist->{$a}->[$third]) cmp lc($classlist->{$b}->[$third])
1.30      raeburn  3182:         } (keys(%{$classlist}));
1.1       raeburn  3183:     foreach my $student (@Sorted_Students) {
                   3184:         my $error;
                   3185:         my $sdata = $classlist->{$student};
1.30      raeburn  3186:         my $username = $sdata->[$indexhash->{'username'}];
                   3187:         my $domain   = $sdata->[$indexhash->{'domain'}];
                   3188:         my $section  = $sdata->[$indexhash->{'section'}];
                   3189:         my $name     = $sdata->[$indexhash->{'fullname'}];
                   3190:         my $id       = $sdata->[$indexhash->{'id'}];
                   3191:         my $start    = $sdata->[$indexhash->{'start'}];
                   3192:         my $end      = $sdata->[$indexhash->{'end'}];
1.1       raeburn  3193:         my $groups = $classgroups->{$student};
                   3194:         my $active_groups;
                   3195:         if (ref($groups->{active}) eq 'HASH') {
                   3196:             $active_groups = join(', ',keys(%{$groups->{'active'}}));
                   3197:         }
                   3198:         if (! defined($start) || $start == 0) {
                   3199:             $start = &mt('none');
                   3200:         } else {
                   3201:             $start = &Apache::lonlocal::locallocaltime($start);
                   3202:         }
                   3203:         if (! defined($end) || $end == 0) {
                   3204:             $end = &mt('none');
                   3205:         } else {
                   3206:             $end = &Apache::lonlocal::locallocaltime($end);
                   3207:         }
1.17      raeburn  3208:         my $studentkey = $student.':'.$section;
1.30      raeburn  3209:         my $startitem = '<input type="hidden" name="'.$studentkey.'_start" value="'.$sdata->[$indexhash->{'start'}].'" />';
1.1       raeburn  3210:         #
                   3211:         $r->print(&Apache::loncommon::start_data_table_row());
                   3212:         $r->print(<<"END");
1.29      raeburn  3213:     <td><input type="checkbox" name="droplist" value="$studentkey"></td>
1.1       raeburn  3214:     <td>$username</td>
                   3215:     <td>$domain</td>
                   3216:     <td>$id</td>
                   3217:     <td>$name</td>
                   3218:     <td>$section</td>
1.29      raeburn  3219:     <td>$start $startitem</td>
1.1       raeburn  3220:     <td>$end</td>
                   3221:     <td>$active_groups</td>
                   3222: END
                   3223:         $r->print(&Apache::loncommon::end_data_table_row());
                   3224:     }
                   3225:     $r->print(&Apache::loncommon::end_data_table().'<br />');
                   3226:     %lt=&Apache::lonlocal::texthash(
1.29      raeburn  3227:                        'dp'   => "Drop Students",
1.1       raeburn  3228:                        'ca'   => "check all",
                   3229:                        'ua'   => "uncheck all",
                   3230:                                        );
                   3231:     $r->print(<<"END");
                   3232: </p><p>
                   3233: <input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.droplist)"> &nbsp;
                   3234: <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.droplist)">
                   3235: <p><input type=submit value="$lt{'dp'}"></p>
                   3236: END
                   3237:     return;
                   3238: }
                   3239: 
                   3240: #
                   3241: # Print out the initial form to get the file containing a list of users
                   3242: #
                   3243: sub print_first_users_upload_form {
                   3244:     my ($r,$context) = @_;
                   3245:     my $str;
                   3246:     $str  = '<input type="hidden" name="phase" value="two">';
                   3247:     $str .= '<input type="hidden" name="action" value="upload" />';
                   3248:     $str .= '<input type="hidden"   name="state"  value="got_file" />';
1.2       raeburn  3249:     $str .= "<h3>".&mt('Upload a file containing information about users')."</h3>\n";
1.1       raeburn  3250:     $str .= &Apache::loncommon::upfile_select_html();
                   3251:     $str .= "<p>\n";
                   3252:     $str .= '<input type="submit" name="fileupload" value="'.
1.2       raeburn  3253:         &mt('Upload file of users').'">'."\n";
1.1       raeburn  3254:     $str .= '<label><input type="checkbox" name="noFirstLine" /> '.
                   3255:         &mt('Ignore First Line')."</label></p>\n";
                   3256:     $str .= &Apache::loncommon::help_open_topic("Course_Create_Class_List",
                   3257:                          &mt("How do I create a users list from a spreadsheet")).
                   3258:                              "<br />\n";
                   3259:     $str .= &Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3260:                            &mt("How do I create a CSV file from a spreadsheet")).
                   3261:                                "<br />\n";
                   3262:     $str .= &Apache::loncommon::end_page();
                   3263:     $r->print($str);
                   3264:     return;
                   3265: }
                   3266: 
                   3267: # ================================================= Drop/Add from uploaded file
                   3268: sub upfile_drop_add {
1.21      raeburn  3269:     my ($r,$context,$permission) = @_;
1.1       raeburn  3270:     &Apache::loncommon::load_tmp_file($r);
                   3271:     my @userdata=&Apache::loncommon::upfile_record_sep();
                   3272:     if($env{'form.noFirstLine'}){shift(@userdata);}
                   3273:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3274:     my %fields=();
                   3275:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3276:         if ($env{'form.upfile_associate'} eq 'reverse') {
                   3277:             if ($env{'form.f'.$i} ne 'none') {
                   3278:                 $fields{$keyfields[$i]}=$env{'form.f'.$i};
                   3279:             }
                   3280:         } else {
                   3281:             $fields{$env{'form.f'.$i}}=$keyfields[$i];
                   3282:         }
                   3283:     }
1.29      raeburn  3284:     if ($env{'form.fullup'} ne 'yes') {
                   3285:         $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n".
                   3286:                   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />');
                   3287:     }
1.1       raeburn  3288:     #
                   3289:     # Store the field choices away
                   3290:     foreach my $field (qw/username names
                   3291:                        fname mname lname gen id sec ipwd email role/) {
                   3292:         $env{'form.'.$field.'_choice'}=$fields{$field};
                   3293:     }
                   3294:     &Apache::loncommon::store_course_settings('enrollment_upload',
                   3295:                                               { 'username_choice' => 'scalar',
                   3296:                                                 'names_choice' => 'scalar',
                   3297:                                                 'fname_choice' => 'scalar',
                   3298:                                                 'mname_choice' => 'scalar',
                   3299:                                                 'lname_choice' => 'scalar',
                   3300:                                                 'gen_choice' => 'scalar',
                   3301:                                                 'id_choice' => 'scalar',
                   3302:                                                 'sec_choice' => 'scalar',
                   3303:                                                 'ipwd_choice' => 'scalar',
                   3304:                                                 'email_choice' => 'scalar',
                   3305:                                                 'role_choice'  => 'scalar' });
                   3306:     #
                   3307:     my ($startdate,$enddate) = &get_dates_from_form();
                   3308:     if ($env{'form.makedatesdefault'}) {
1.27      raeburn  3309:         $r->print(&make_dates_default($startdate,$enddate,$context));
1.1       raeburn  3310:     }
                   3311:     # Determine domain and desired host (home server)
                   3312:     my $domain=$env{'request.role.domain'};
                   3313:     my $desiredhost = $env{'form.lcserver'};
                   3314:     if (lc($desiredhost) eq 'default') {
                   3315:         $desiredhost = undef;
                   3316:     } else {
                   3317:         my %home_servers = &Apache::lonnet::get_servers($domain,'library');
                   3318:         if (! exists($home_servers{$desiredhost})) {
                   3319:             $r->print('<span class="LC_error">'.&mt('Error').
                   3320:                       &mt('Invalid home server specified').'</span>');
                   3321:             $r->print(&Apache::loncommon::end_page());
                   3322:             return;
                   3323:         }
                   3324:     }
                   3325:     # Determine authentication mechanism
                   3326:     my $changeauth;
                   3327:     if ($context eq 'domain') {
                   3328:         $changeauth = $env{'form.changeauth'};
                   3329:     }
                   3330:     my $amode  = '';
                   3331:     my $genpwd = '';
                   3332:     if ($env{'form.login'} eq 'krb') {
                   3333:         $amode='krb';
                   3334:         $amode.=$env{'form.krbver'};
                   3335:         $genpwd=$env{'form.krbarg'};
                   3336:     } elsif ($env{'form.login'} eq 'int') {
                   3337:         $amode='internal';
                   3338:         if ((defined($env{'form.intarg'})) && ($env{'form.intarg'})) {
                   3339:             $genpwd=$env{'form.intarg'};
                   3340:         }
                   3341:     } elsif ($env{'form.login'} eq 'loc') {
                   3342:         $amode='localauth';
                   3343:         if ((defined($env{'form.locarg'})) && ($env{'form.locarg'})) {
                   3344:             $genpwd=$env{'form.locarg'};
                   3345:         }
                   3346:     }
                   3347:     if ($amode =~ /^krb/) {
                   3348:         if (! defined($genpwd) || $genpwd eq '') {
                   3349:             $r->print('<span class="Error">'.
                   3350:                       &mt('Unable to enroll users').' '.
                   3351:                       &mt('No Kerberos domain was specified.').'</span></p>');
                   3352:             $amode = ''; # This causes the loop below to be skipped
                   3353:         }
                   3354:     }
                   3355:     my ($cid,$defaultsec,$defaultrole,$setting);
                   3356:     if ($context eq 'domain') {
                   3357:         $setting = $env{'form.roleaction'};
                   3358:         if ($setting eq 'domain') {
                   3359:             $defaultrole = $env{'form.defaultrole'};
                   3360:         } elsif ($setting eq 'course') {
                   3361:             $defaultrole = $env{'form.courserole'};
1.27      raeburn  3362:             $defaultsec = $env{'form.sections'};
1.1       raeburn  3363:         }  
1.13      raeburn  3364:     } elsif ($context eq 'author') {
1.1       raeburn  3365:         $defaultrole = $env{'form.defaultrole'};
1.27      raeburn  3366:     } elsif ($context eq 'course') {
                   3367:         $defaultrole = $env{'form.defaultrole'};
                   3368:         $defaultsec = $env{'form.sections'};
1.1       raeburn  3369:     }
1.27      raeburn  3370:     if ($env{'request.course.id'} ne '') {
                   3371:         $cid = $env{'request.course.id'};
                   3372:     } elsif ($setting eq 'course') {
                   3373:         if (&Apache::lonnet::is_course($env{'form.dcdomain'},$env{'form.dccourse'})) {
                   3374:             $cid = $env{'form.dcdomain'}.'_'.$env{'form.dccourse'};
1.1       raeburn  3375:         }
                   3376:     }
1.27      raeburn  3377:     # Check to see if user information can be changed
                   3378:     my @userinfo = ('firstname','middlename','lastname','generation',
                   3379:                     'permanentemail','id');
                   3380:     my %canmodify;
                   3381:     if (&Apache::lonnet::allowed('mau',$domain)) {
                   3382:         foreach my $field (@userinfo) {
                   3383:             $canmodify{$field} = 1;
                   3384:         }
                   3385:     }
                   3386:     my (%userlist,%modifiable_fields,@poss_roles);
                   3387:     my $secidx = &Apache::loncoursedata::CL_SECTION();
                   3388:     my @courseroles = &roles_by_context('course',1);
                   3389:     if (!&Apache::lonnet::allowed('mau',$domain)) {
                   3390:         if ($context eq 'course' || $context eq 'author') {
                   3391:             @poss_roles =  &curr_role_permissions($context);
                   3392:             my @statuses = ('active','future');
                   3393:             my ($indexhash,$keylist) = &make_keylist_array();
                   3394:             my %info;
                   3395:             foreach my $role (@poss_roles) {
                   3396:                 %{$modifiable_fields{$role}} = &can_modify_userinfo($context,$domain,
                   3397:                                                         \@userinfo,[$role]);
                   3398:             }
                   3399:             if ($context eq 'course') {
                   3400:                 my ($cnum,$cdom) = &get_course_identity();
                   3401:                 my $roster = &Apache::loncoursedata::get_classlist();
                   3402:                 %userlist = %{$roster};
                   3403:                 my %advrolehash = &Apache::lonnet::get_my_roles($cnum,$cdom,undef,
                   3404:                                                          \@statuses,\@poss_roles);
                   3405:                 &gather_userinfo($context,'view',\%userlist,$indexhash,\%info,
                   3406:                                 \%advrolehash,$permission);
                   3407:             } elsif ($context eq 'author') {
                   3408:                 my %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
                   3409:                                                   \@statuses,\@poss_roles);
                   3410:                 &gather_userinfo($context,'view',\%userlist,$indexhash,\%info,
                   3411:                              \%cstr_roles,$permission);
                   3412: 
                   3413:             }
                   3414:         }
1.1       raeburn  3415:     }
                   3416:     if ( $domain eq &LONCAPA::clean_domain($domain)
                   3417:         && ($amode ne '')) {
                   3418:         #######################################
                   3419:         ##         Add/Modify Users          ##
                   3420:         #######################################
                   3421:         if ($context eq 'course') {
                   3422:             $r->print('<h3>'.&mt('Enrolling Users')."</h3>\n<p>\n");
1.13      raeburn  3423:         } elsif ($context eq 'author') {
1.1       raeburn  3424:             $r->print('<h3>'.&mt('Updating Co-authors')."</h3>\n<p>\n");
                   3425:         } else {
                   3426:             $r->print('<h3>'.&mt('Adding/Modifying Users')."</h3>\n<p>\n");
                   3427:         }
                   3428:         my %counts = (
                   3429:                        user => 0,
                   3430:                        auth => 0,
                   3431:                        role => 0,
                   3432:                      );
                   3433:         my $flushc=0;
                   3434:         my %student=();
1.42      raeburn  3435:         my (%curr_groups,@sections,@cleansec,$defaultwarn,$groupwarn);
1.1       raeburn  3436:         my %userchg;
1.27      raeburn  3437:         if ($context eq 'course' || $setting eq 'course') {
                   3438:             if ($context eq 'course') {
                   3439:                 # Get information about course groups
                   3440:                 %curr_groups = &Apache::longroup::coursegroups();
                   3441:             } elsif ($setting eq 'course') {
                   3442:                 if ($cid) {
                   3443:                     %curr_groups =
                   3444:                         &Apache::longroup::coursegroups($env{'form.dcdomain'},
                   3445:                                                         $env{'form.dccourse'});
                   3446:                 }
                   3447:             }
                   3448:             # determine section number
                   3449:             if ($defaultsec =~ /,/) {
                   3450:                 push(@sections,split(/,/,$defaultsec));
                   3451:             } else {
                   3452:                 push(@sections,$defaultsec);
                   3453:             }
                   3454:             # remove non alphanumeric values from section
                   3455:             foreach my $item (@sections) {
                   3456:                 $item =~ s/\W//g;
                   3457:                 if ($item eq "none" || $item eq 'all') {
                   3458:                     $defaultwarn = &mt('Default section name [_1] could not be used as it is a reserved word.',$item);
                   3459:                 } elsif ($item ne ''  && exists($curr_groups{$item})) {
                   3460:                     $groupwarn = &mt('Default section name "[_1]" is the name of a course group. Section names and group names must be distinct.',$item);
                   3461:                 } elsif ($item ne '') {
                   3462:                     push(@cleansec,$item);
                   3463:                 }
                   3464:             }
                   3465:             if ($defaultwarn) {
                   3466:                 $r->print($defaultwarn.'<br />');
                   3467:             }
                   3468:             if ($groupwarn) {
                   3469:                 $r->print($groupwarn.'<br />');
                   3470:             }
1.1       raeburn  3471:         }
1.5       raeburn  3472:         my (%curr_rules,%got_rules,%alerts);
1.27      raeburn  3473:         my %customroles = &my_custom_roles();
1.42      raeburn  3474:         my @permitted_roles = &roles_on_upload($context,$setting,%customroles); 
1.1       raeburn  3475:         # Get new users list
1.27      raeburn  3476:         foreach my $line (@userdata) {
1.42      raeburn  3477:             my @secs;
1.27      raeburn  3478:             my %entries=&Apache::loncommon::record_sep($line);
1.1       raeburn  3479:             # Determine user name
                   3480:             unless (($entries{$fields{'username'}} eq '') ||
                   3481:                     (!defined($entries{$fields{'username'}}))) {
                   3482:                 my ($fname, $mname, $lname,$gen) = ('','','','');
                   3483:                 if (defined($fields{'names'})) {
                   3484:                     ($lname,$fname,$mname)=($entries{$fields{'names'}}=~
                   3485:                                             /([^\,]+)\,\s*(\w+)\s*(.*)$/);
                   3486:                 } else {
                   3487:                     if (defined($fields{'fname'})) {
                   3488:                         $fname=$entries{$fields{'fname'}};
                   3489:                     }
                   3490:                     if (defined($fields{'mname'})) {
                   3491:                         $mname=$entries{$fields{'mname'}};
                   3492:                     }
                   3493:                     if (defined($fields{'lname'})) {
                   3494:                         $lname=$entries{$fields{'lname'}};
                   3495:                     }
                   3496:                     if (defined($fields{'gen'})) {
                   3497:                         $gen=$entries{$fields{'gen'}};
                   3498:                     }
                   3499:                 }
                   3500:                 if ($entries{$fields{'username'}}
                   3501:                     ne &LONCAPA::clean_username($entries{$fields{'username'}})) {
                   3502:                     $r->print('<br />'.
                   3503:       &mt('<b>[_1]</b>: Unacceptable username for user [_2] [_3] [_4] [_5]',
                   3504:           $entries{$fields{'username'}},$fname,$mname,$lname,$gen).
                   3505:                               '</b>');
1.27      raeburn  3506:                     next;
1.1       raeburn  3507:                 } else {
1.5       raeburn  3508:                     my $username = $entries{$fields{'username'}};
1.27      raeburn  3509:                     if (defined($fields{'sec'})) {
                   3510:                         if (defined($entries{$fields{'sec'}})) {
1.42      raeburn  3511:                             $entries{$fields{'sec'}} =~ s/\W//g;
1.27      raeburn  3512:                             my $item = $entries{$fields{'sec'}};
                   3513:                             if ($item eq "none" || $item eq 'all') {
                   3514:                                 $r->print('<br />'.&mt('<b>[_1]</b>: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]" - this is a reserved word.',$username,$fname,$mname,$lname,$gen,$item));
                   3515:                                 next;
                   3516:                             } elsif (exists($curr_groups{$item})) {
                   3517:                                 $r->print('<br />'.&mt('<b>[_1]</b>: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]" - this is a course group.',$username,$fname,$mname,$lname,$gen,$item).' '.&mt('Section names and group names must be distinct.'));
                   3518:                                 next;
                   3519:                             } else {
                   3520:                                 push(@secs,$item);
                   3521:                             }
                   3522:                         }
                   3523:                     }
                   3524:                     if ($env{'request.course.sec'} ne '') {
                   3525:                         @secs = ($env{'request.course.sec'});
                   3526:                         if (ref($userlist{$username.':'.$domain}) eq 'ARRAY') {
                   3527:                             my $currsec = $userlist{$username.':'.$domain}[$secidx];
                   3528:                             if ($currsec ne $env{'request.course.sec'}) {
                   3529:                                 $r->print('<br />'.&mt('<b>[_1]</b>: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]".',$username,$fname,$mname,$lname,$gen,$secs[0]).'<br />');
                   3530:                                 if ($currsec eq '') {
                   3531:                                     $r->print(&mt('This user already has an active/future student role in the course, unaffiliated to any section.'));
                   3532: 
                   3533:                                 } else {
                   3534:                                     $r->print(&mt('This user already has an active/future role in section "[_1]" of the course.',$currsec));
                   3535:                                 }
                   3536:                                 $r->print('<br />'.&mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments in other sections.',$secs[0]).'<br />');
                   3537:                                 next;
1.1       raeburn  3538:                             }
                   3539:                         }
1.27      raeburn  3540:                     } elsif ($context eq 'course' || $setting eq 'course') {
                   3541:                         if (@secs == 0) {
                   3542:                             @secs = @cleansec;
1.1       raeburn  3543:                         }
                   3544:                     }
                   3545:                     # determine id number
                   3546:                     my $id='';
                   3547:                     if (defined($fields{'id'})) {
                   3548:                         if (defined($entries{$fields{'id'}})) {
                   3549:                             $id=$entries{$fields{'id'}};
                   3550:                         }
                   3551:                         $id=~tr/A-Z/a-z/;
                   3552:                     }
                   3553:                     # determine email address
                   3554:                     my $email='';
                   3555:                     if (defined($fields{'email'})) {
                   3556:                         if (defined($entries{$fields{'email'}})) {
                   3557:                             $email=$entries{$fields{'email'}};
                   3558:                             unless ($email=~/^[^\@]+\@[^\@]+$/) { $email=''; }                        }
                   3559:                     }
                   3560:                     # determine user password
                   3561:                     my $password = $genpwd;
                   3562:                     if (defined($fields{'ipwd'})) {
                   3563:                         if ($entries{$fields{'ipwd'}}) {
                   3564:                             $password=$entries{$fields{'ipwd'}};
                   3565:                         }
                   3566:                     }
                   3567:                     # determine user role
                   3568:                     my $role = '';
                   3569:                     if (defined($fields{'role'})) {
                   3570:                         if ($entries{$fields{'role'}}) {
1.42      raeburn  3571:                             $entries{$fields{'role'}}  =~ s/(\s+$|^\s+)//g;
                   3572:                             if ($entries{$fields{'role'}} ne '') {
                   3573:                                 if (grep(/^\Q$entries{$fields{'role'}}\E$/,@permitted_roles)) {
                   3574:                                     $role = $entries{$fields{'role'}};
1.27      raeburn  3575:                                 }
                   3576:                             }
                   3577:                             if ($role eq '') {
                   3578:                                 my $rolestr = join(', ',@permitted_roles);
1.1       raeburn  3579:                                 $r->print('<br />'.
                   3580:       &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");
                   3581:                                 next;
                   3582:                             }
                   3583:                         }
                   3584:                     }
                   3585:                     if ($role eq '') {
                   3586:                         $role = $defaultrole;
                   3587:                     }
                   3588:                     # Clean up whitespace
                   3589:                     foreach (\$domain,\$username,\$id,\$fname,\$mname,
1.27      raeburn  3590:                              \$lname,\$gen) {
1.1       raeburn  3591:                         $$_ =~ s/(\s+$|^\s+)//g;
                   3592:                     }
1.5       raeburn  3593:                     # check against rules
                   3594:                     my $checkid = 0;
                   3595:                     my $newuser = 0;
                   3596:                     my (%rulematch,%inst_results,%idinst_results);
                   3597:                     my $uhome=&Apache::lonnet::homeserver($username,$domain);
                   3598:                     if ($uhome eq 'no_host') {
                   3599:                         $checkid = 1;
                   3600:                         $newuser = 1;
                   3601:                         my $checkhash;
                   3602:                         my $checks = { 'username' => 1 };
                   3603:                         $checkhash->{$username.':'.$domain} = { 'newuser' => 1, };
                   3604:                         &Apache::loncommon::user_rule_check($checkhash,$checks,
                   3605:                             \%alerts,\%rulematch,\%inst_results,\%curr_rules,
                   3606:                             \%got_rules);
                   3607:                         if (ref($alerts{'username'}) eq 'HASH') {
                   3608:                             if (ref($alerts{'username'}{$domain}) eq 'HASH') {
                   3609:                                 next if ($alerts{'username'}{$domain}{$username});
                   3610:                             }
                   3611:                         }
1.13      raeburn  3612:                     } else {
1.27      raeburn  3613:                         if ($context eq 'course' || $context eq 'author') {
                   3614:                             if ($role eq '') {
                   3615:                                 my @checkroles;
                   3616:                                 foreach my $role (@poss_roles) {
                   3617:                                     my $endkey;
                   3618:                                     if ($role ne 'st') {
                   3619:                                         $endkey = ':'.$role;
                   3620:                                     }
                   3621:                                     if (exists($userlist{$username.':'.$domain.$endkey})) {
                   3622:                                         if (!grep(/^\Q$role\E$/,@checkroles)) {
                   3623:                                             push(@checkroles,$role);
                   3624:                                         }
                   3625:                                     }
                   3626:                                 }
                   3627:                                 if (@checkroles > 0) {
                   3628:                                     %canmodify = &can_modify_userinfo($context,$domain,\@userinfo,\@checkroles);
                   3629:                                 }
                   3630:                             } elsif (ref($modifiable_fields{$role}) eq 'HASH') {
                   3631:                                 %canmodify = %{$modifiable_fields{$role}};
                   3632:                             }
                   3633:                         }
                   3634:                         my @newinfo = (\$fname,\$mname,\$lname,\$gen,\$email,\$id);
                   3635:                         for (my $i=0; $i<@userinfo; $i++) {
                   3636:                             if (${$newinfo[$i]} ne '') {
                   3637:                                 if (!$canmodify{$userinfo[$i]}) {
                   3638:                                     ${$newinfo[$i]} = '';
                   3639:                                 }
                   3640:                             }
                   3641:                         }
1.5       raeburn  3642:                     }
                   3643:                     if ($id ne '') {
                   3644:                         if (!$newuser) {
                   3645:                             my %idhash = &Apache::lonnet::idrget($domain,($username));
                   3646:                             if ($idhash{$username} ne $id) {
                   3647:                                 $checkid = 1;
                   3648:                             }
                   3649:                         }
                   3650:                         if ($checkid) {
                   3651:                             my $checkhash;
                   3652:                             my $checks = { 'id' => 1 };
                   3653:                             $checkhash->{$username.':'.$domain} = { 'newuser' => $newuser,
                   3654:                                                                     'id'  => $id };
                   3655:                             &Apache::loncommon::user_rule_check($checkhash,$checks,
                   3656:                                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,
                   3657:                                 \%got_rules);
                   3658:                             if (ref($alerts{'id'}) eq 'HASH') {
                   3659:                                 if (ref($alerts{'id'}{$domain}) eq 'HASH') {
                   3660:                                     next if ($alerts{'id'}{$domain}{$id});
                   3661:                                 }
                   3662:                             }
                   3663:                         }
                   3664:                     }
1.1       raeburn  3665:                     if ($password || $env{'form.login'} eq 'loc') {
1.27      raeburn  3666:                         my $multiple = 0;
                   3667:                         my ($userresult,$authresult,$roleresult,$idresult);
                   3668:                         my (%userres,%authres,%roleres,%idres);
1.42      raeburn  3669:                         my $singlesec = '';
1.1       raeburn  3670:                         if ($role eq 'st') {
1.27      raeburn  3671:                             my $sec;
1.42      raeburn  3672:                             if (@secs > 0) {
                   3673:                                 $sec = $secs[0];
1.27      raeburn  3674:                             }
1.42      raeburn  3675:                             &modifystudent($domain,$username,$cid,$sec,
1.52      raeburn  3676:                                            $desiredhost,$context);
1.42      raeburn  3677:                             $roleresult =
                   3678:                                 &Apache::lonnet::modifystudent
                   3679:                                     ($domain,$username,$id,$amode,$password,
                   3680:                                      $fname,$mname,$lname,$gen,$sec,$enddate,
                   3681:                                      $startdate,$env{'form.forceid'},
1.52      raeburn  3682:                                      $desiredhost,$email,'manual','',$cid,
                   3683:                                      '',$context);
1.42      raeburn  3684:                             $userresult = $roleresult;
1.1       raeburn  3685:                         } else {
1.42      raeburn  3686:                             if ($role ne '') { 
                   3687:                                 if ($context eq 'course' || $setting eq 'course') {
                   3688:                                     if ($customroles{$role}) {
                   3689:                                         $role = 'cr_'.$env{'user.domain'}.'_'.
                   3690:                                                 $env{'user.name'}.'_'.$role;
                   3691:                                     }
                   3692:                                     if ($role ne 'cc') { 
                   3693:                                         if (@secs > 1) {
                   3694:                                             $multiple = 1;
                   3695:                                             foreach my $sec (@secs) {
                   3696:                                                 ($userres{$sec},$authres{$sec},$roleres{$sec},$idres{$sec}) =
                   3697:                                                 &modifyuserrole($context,$setting,
                   3698:                                                     $changeauth,$cid,$domain,$username,
                   3699:                                                     $id,$amode,$password,$fname,
                   3700:                                                     $mname,$lname,$gen,$sec,
                   3701:                                                     $env{'form.forceid'},$desiredhost,
                   3702:                                                     $email,$role,$enddate,
                   3703:                                                     $startdate,$checkid);
                   3704:                                             }
                   3705:                                         } elsif (@secs > 0) {
                   3706:                                             $singlesec = $secs[0];
                   3707:                                         }
1.27      raeburn  3708:                                     }
                   3709:                                 }
                   3710:                             }
                   3711:                             if (!$multiple) {
1.28      raeburn  3712:                                 ($userresult,$authresult,$roleresult,$idresult) = 
1.27      raeburn  3713:                                     &modifyuserrole($context,$setting,
1.42      raeburn  3714:                                                     $changeauth,$cid,$domain,$username, 
                   3715:                                                     $id,$amode,$password,$fname,
                   3716:                                                     $mname,$lname,$gen,$singlesec,
                   3717:                                                     $env{'form.forceid'},$desiredhost,
                   3718:                                                     $email,$role,$enddate,$startdate,$checkid);
1.27      raeburn  3719:                             }
                   3720:                         }
                   3721:                         if ($multiple) {
                   3722:                             foreach my $sec (sort(keys(%userres))) {
1.42      raeburn  3723:                                 $flushc =
1.27      raeburn  3724:                                 &user_change_result($r,$userres{$sec},$authres{$sec},
                   3725:                                                     $roleres{$sec},$idres{$sec},\%counts,$flushc,
                   3726:                                                     $username,\%userchg);
                   3727: 
                   3728:                             }
                   3729:                         } else {
                   3730:                             $flushc = 
                   3731:                                 &user_change_result($r,$userresult,$authresult,
1.28      raeburn  3732:                                                     $roleresult,$idresult,\%counts,$flushc,
1.29      raeburn  3733:                                                     $username,\%userchg);
1.1       raeburn  3734:                         }
                   3735:                     } else {
                   3736:                         if ($context eq 'course') {
                   3737:                             $r->print('<br />'. 
                   3738:       &mt('<b>[_1]</b>: Unable to enroll.  No password specified.',$username)
                   3739:                                      );
1.13      raeburn  3740:                         } elsif ($context eq 'author') {
1.1       raeburn  3741:                             $r->print('<br />'.
                   3742:       &mt('<b>[_1]</b>: Unable to add co-author.  No password specified.',$username)
                   3743:                                      );
                   3744:                         } else {
                   3745:                             $r->print('<br />'.
                   3746:       &mt('<b>[_1]</b>: Unable to add user.  No password specified.',$username)
                   3747:                                      );
                   3748:                         }
                   3749:                     }
                   3750:                 }
                   3751:             }
                   3752:         } # end of foreach (@userdata)
                   3753:         # Flush the course logs so reverse user roles immediately updated
1.5       raeburn  3754:         &Apache::lonnet::flushcourselogs();
1.29      raeburn  3755:         $r->print("</p>\n<p>\n".&mt('Processed [quant,_1,user].',$counts{'user'}).
1.1       raeburn  3756:                   "</p>\n");
                   3757:         if ($counts{'role'} > 0) {
                   3758:             $r->print("<p>\n".
1.29      raeburn  3759:                       &mt('Roles added for [quant,_1,user].',$counts{'role'}).' '.&mt('If a user is currently logged-in to LON-CAPA, any new roles which are active will be available when the user next logs in.')."</p>\n");
                   3760:         } else {
                   3761:             $r->print('<p>'.&mt('No roles added').'</p>');
1.1       raeburn  3762:         }
                   3763:         if ($counts{'auth'} > 0) {
                   3764:             $r->print("<p>\n".
                   3765:                       &mt('Authentication changed for [_1] existing users.',
                   3766:                           $counts{'auth'})."</p>\n");
                   3767:         }
1.13      raeburn  3768:         $r->print(&print_namespacing_alerts($domain,\%alerts,\%curr_rules));
1.1       raeburn  3769:         #####################################
1.29      raeburn  3770:         # Display list of students to drop  #
1.1       raeburn  3771:         #####################################
                   3772:         if ($env{'form.fullup'} eq 'yes') {
1.29      raeburn  3773:             $r->print('<h3>'.&mt('Students to Drop')."</h3>\n");
1.1       raeburn  3774:             #  Get current classlist
1.30      raeburn  3775:             my $classlist = &Apache::loncoursedata::get_classlist();
1.1       raeburn  3776:             if (! defined($classlist)) {
1.29      raeburn  3777:                 $r->print('<form name="studentform" method="post" action="/adm/createuser" />'.
                   3778:                           '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
                   3779:                           &mt('There are no students with current/future access to the course.').
                   3780:                           '</form>'."\n");
1.1       raeburn  3781:             } else {
                   3782:                 # Remove the students we just added from the list of students.
1.30      raeburn  3783:                 foreach my $line (@userdata) {
                   3784:                     my %entries=&Apache::loncommon::record_sep($line);
1.1       raeburn  3785:                     unless (($entries{$fields{'username'}} eq '') ||
                   3786:                             (!defined($entries{$fields{'username'}}))) {
                   3787:                         delete($classlist->{$entries{$fields{'username'}}.
                   3788:                                                 ':'.$domain});
                   3789:                     }
                   3790:                 }
                   3791:                 # Print out list of dropped students.
1.30      raeburn  3792:                 &show_drop_list($r,$classlist,'nosort',$permission);
1.1       raeburn  3793:             }
                   3794:         }
                   3795:     } # end of unless
1.29      raeburn  3796:     if ($env{'form.fullup'} ne 'yes') {
                   3797:         $r->print('</form>');
                   3798:     }
1.1       raeburn  3799: }
                   3800: 
1.13      raeburn  3801: sub print_namespacing_alerts {
                   3802:     my ($domain,$alerts,$curr_rules) = @_;
                   3803:     my $output;
                   3804:     if (ref($alerts) eq 'HASH') {
                   3805:         if (keys(%{$alerts}) > 0) {
                   3806:             if (ref($alerts->{'username'}) eq 'HASH') {
                   3807:                 foreach my $dom (sort(keys(%{$alerts->{'username'}}))) {
                   3808:                     my $count;
                   3809:                     if (ref($alerts->{'username'}{$dom}) eq 'HASH') {
                   3810:                         $count = keys(%{$alerts->{'username'}{$dom}});
                   3811:                     }
                   3812:                     my $domdesc = &Apache::lonnet::domain($domain,'description');
                   3813:                     if (ref($curr_rules->{$dom}) eq 'HASH') {
                   3814:                         $output .= &Apache::loncommon::instrule_disallow_msg(
                   3815:                                         'username',$domdesc,$count,'upload');
                   3816:                     }
                   3817:                     $output .= &Apache::loncommon::user_rule_formats($dom,
                   3818:                                    $domdesc,$curr_rules->{$dom}{'username'},
                   3819:                                    'username');
                   3820:                 }
                   3821:             }
                   3822:             if (ref($alerts->{'id'}) eq 'HASH') {
                   3823:                 foreach my $dom (sort(keys(%{$alerts->{'id'}}))) {
                   3824:                     my $count;
                   3825:                     if (ref($alerts->{'id'}{$dom}) eq 'HASH') {
                   3826:                         $count = keys(%{$alerts->{'id'}{$dom}});
                   3827:                     }
                   3828:                     my $domdesc = &Apache::lonnet::domain($domain,'description');
                   3829:                     if (ref($curr_rules->{$dom}) eq 'HASH') {
                   3830:                         $output .= &Apache::loncommon::instrule_disallow_msg(
                   3831:                                               'id',$domdesc,$count,'upload');
                   3832:                     }
                   3833:                     $output .= &Apache::loncommon::user_rule_formats($dom,
                   3834:                                     $domdesc,$curr_rules->{$dom}{'id'},'id');
                   3835:                 }
                   3836:             }
                   3837:         }
                   3838:     }
                   3839: }
                   3840: 
1.1       raeburn  3841: sub user_change_result {
1.29      raeburn  3842:     my ($r,$userresult,$authresult,$roleresult,$idresult,$counts,$flushc,
                   3843:         $username,$userchg) = @_;
1.1       raeburn  3844:     my $okresult = 0;
                   3845:     if ($userresult ne 'ok') {
                   3846:         if ($userresult =~ /^error:(.+)$/) {
                   3847:             my $error = $1;
                   3848:             $r->print('<br />'.
                   3849:                   &mt('<b>[_1]</b>:  Unable to add/modify: [_2]',$username,$error));
                   3850:         }
                   3851:     } else {
                   3852:         $counts->{'user'} ++;
                   3853:         $okresult = 1;
                   3854:     }
                   3855:     if ($authresult ne 'ok') {
                   3856:         if ($authresult =~ /^error:(.+)$/) {
                   3857:             my $error = $1;
                   3858:             $r->print('<br />'.
                   3859:                   &mt('<b>[_1]</b>:  Unable to modify authentication: [_2]',$username,$error));
                   3860:         } 
                   3861:     } else {
                   3862:         $counts->{'auth'} ++;
                   3863:         $okresult = 1;
                   3864:     }
                   3865:     if ($roleresult ne 'ok') {
                   3866:         if ($roleresult =~ /^error:(.+)$/) {
                   3867:             my $error = $1;
                   3868:             $r->print('<br />'.
                   3869:                   &mt('<b>[_1]</b>:  Unable to add role: [_2]',$username,$error));
                   3870:         }
                   3871:     } else {
                   3872:         $counts->{'role'} ++;
                   3873:         $okresult = 1;
                   3874:     }
                   3875:     if ($okresult) {
                   3876:         $flushc++;
                   3877:         $userchg->{$username}=1;
                   3878:         $r->print('. ');
                   3879:         if ($flushc>15) {
                   3880:             $r->rflush;
                   3881:             $flushc=0;
                   3882:         }
                   3883:     }
1.29      raeburn  3884:     if ($idresult) {
                   3885:         $r->print($idresult);
                   3886:     }
1.1       raeburn  3887:     return $flushc;
                   3888: }
                   3889: 
                   3890: # ========================================================= Menu Phase Two Drop
1.17      raeburn  3891: sub print_drop_menu {
                   3892:     my ($r,$context,$permission) = @_;
                   3893:     $r->print('<h3>'.&mt("Drop Students").'</h3>'."\n".
                   3894:               '<form name="studentform" method="post">'."\n");
1.30      raeburn  3895:     my $classlist = &Apache::loncoursedata::get_classlist();
1.1       raeburn  3896:     if (! defined($classlist)) {
                   3897:         $r->print(&mt('There are no students currently enrolled.')."\n");
1.30      raeburn  3898:     } else {
                   3899:         &show_drop_list($r,$classlist,'nosort',$permission);
1.1       raeburn  3900:     }
1.17      raeburn  3901:     $r->print('</form>'. &Apache::loncommon::end_page());
1.1       raeburn  3902:     return;
                   3903: }
                   3904: 
                   3905: # ================================================================== Phase four
                   3906: 
1.11      raeburn  3907: sub update_user_list {
                   3908:     my ($r,$context,$setting,$choice) = @_;
                   3909:     my $now = time;
1.1       raeburn  3910:     my $count=0;
1.11      raeburn  3911:     my @changelist;
1.29      raeburn  3912:     if ($choice eq 'drop') {
                   3913:         @changelist = &Apache::loncommon::get_env_multiple('form.droplist');
                   3914:     } else {
1.11      raeburn  3915:         @changelist = &Apache::loncommon::get_env_multiple('form.actionlist');
                   3916:     }
                   3917:     my %result_text = ( ok    => { 'revoke'   => 'Revoked',
                   3918:                                    'delete'   => 'Deleted',
                   3919:                                    'reenable' => 'Re-enabled',
1.17      raeburn  3920:                                    'activate' => 'Activated',
                   3921:                                    'chgdates' => 'Changed Access Dates for',
                   3922:                                    'chgsec'   => 'Changed section for',
                   3923:                                    'drop'     => 'Dropped',
1.11      raeburn  3924:                                  },
                   3925:                         error => {'revoke'    => 'revoking',
                   3926:                                   'delete'    => 'deleting',
                   3927:                                   'reenable'  => 're-enabling',
                   3928:                                   'activate'  => 'activating',
1.17      raeburn  3929:                                   'chgdates'  => 'changing access dates for',
                   3930:                                   'chgsec'    => 'changing section for',
                   3931:                                   'drop'      => 'dropping',
1.11      raeburn  3932:                                  },
                   3933:                       );
                   3934:     my ($startdate,$enddate);
                   3935:     if ($choice eq 'chgdates' || $choice eq 'reenable' || $choice eq 'activate') {
                   3936:         ($startdate,$enddate) = &get_dates_from_form();
                   3937:     }
                   3938:     foreach my $item (@changelist) {
                   3939:         my ($role,$uname,$udom,$cid,$sec,$scope,$result,$type,$locktype,@sections,
                   3940:             $scopestem);
1.17      raeburn  3941:         if ($choice eq 'drop') {
                   3942:             ($uname,$udom,$sec) = split(/:/,$item,-1);
                   3943:             $role = 'st';
                   3944:             $cid = $env{'request.course.id'};
                   3945:             $scopestem = '/'.$cid;
                   3946:             $scopestem =~s/\_/\//g;
                   3947:             if ($sec eq '') {
                   3948:                 $scope = $scopestem;
                   3949:             } else {
                   3950:                 $scope = $scopestem.'/'.$sec;
                   3951:             }
                   3952:         } elsif ($context eq 'course') {
1.11      raeburn  3953:             ($uname,$udom,$role,$sec,$type,$locktype) = split(/\:/,$item,-1);
                   3954:             $cid = $env{'request.course.id'};
                   3955:             $scopestem = '/'.$cid;
                   3956:             $scopestem =~s/\_/\//g;
                   3957:             if ($sec eq '') {
                   3958:                 $scope = $scopestem;
                   3959:             } else {
                   3960:                 $scope = $scopestem.'/'.$sec;
                   3961:             }
1.13      raeburn  3962:         } elsif ($context eq 'author') {
1.11      raeburn  3963:             ($uname,$udom,$role) = split(/\:/,$item,-1);
                   3964:             $scope = '/'.$env{'user.domain'}.'/'.$env{'user.name'};
                   3965:         } elsif ($context eq 'domain') {
                   3966:             if ($setting eq 'domain') {
                   3967:                 ($role,$uname,$udom) = split(/\:/,$item,-1);
                   3968:                 $scope = '/'.$env{'request.role.domain'}.'/';
1.13      raeburn  3969:             } elsif ($setting eq 'author') { 
1.11      raeburn  3970:                 ($uname,$udom,$role,$scope) = split(/\:/,$item);
                   3971:             } elsif ($setting eq 'course') {
                   3972:                 ($uname,$udom,$role,$cid,$sec,$type,$locktype) = 
                   3973:                     split(/\:/,$item);
                   3974:                 $scope = '/'.$cid;
                   3975:                 $scope =~s/\_/\//g;
                   3976:                 if ($sec ne '') {
                   3977:                     $scope .= '/'.$sec;
                   3978:                 }
                   3979:             }
                   3980:         }
                   3981:         my $plrole = &Apache::lonnet::plaintext($role);
                   3982:         my $start = $env{'form.'.$item.'_start'};
                   3983:         my $end = $env{'form.'.$item.'_end'};
1.17      raeburn  3984:         if ($choice eq 'drop') {
                   3985:             # drop students
                   3986:             $end = $now;
                   3987:             $type = 'manual';
                   3988:             $result =
1.52      raeburn  3989:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
1.17      raeburn  3990:         } elsif ($choice eq 'revoke') {
                   3991:             # revoke or delete user role
1.11      raeburn  3992:             $end = $now; 
                   3993:             if ($role eq 'st') {
                   3994:                 $result = 
1.52      raeburn  3995:                     &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
1.11      raeburn  3996:             } else {
                   3997:                 $result = 
1.52      raeburn  3998:                     &Apache::lonnet::revokerole($udom,$uname,$scope,$role,
                   3999:                                                 '','',$context);
1.11      raeburn  4000:             }
                   4001:         } elsif ($choice eq 'delete') {
                   4002:             if ($role eq 'st') {
1.52      raeburn  4003:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$now,$start,$type,$locktype,$cid,'',$context);
1.29      raeburn  4004:             }
                   4005:             $result =
                   4006:                 &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$now,
1.52      raeburn  4007:                                             $start,1,'',$context);
1.11      raeburn  4008:         } else {
                   4009:             #reenable, activate, change access dates or change section
                   4010:             if ($choice ne 'chgsec') {
                   4011:                 $start = $startdate; 
                   4012:                 $end = $enddate;
                   4013:             }
                   4014:             if ($choice eq 'reenable') {
                   4015:                 if ($role eq 'st') {
1.52      raeburn  4016:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
1.11      raeburn  4017:                 } else {
                   4018:                     $result = 
                   4019:                         &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
1.52      raeburn  4020:                                                     $now,'','',$context);
1.11      raeburn  4021:                 }
                   4022:             } elsif ($choice eq 'activate') {
                   4023:                 if ($role eq 'st') {
1.52      raeburn  4024:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
1.11      raeburn  4025:                 } else {
                   4026:                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
1.52      raeburn  4027:                                             $now,'','',$context);
1.11      raeburn  4028:                 }
                   4029:             } elsif ($choice eq 'chgdates') {
                   4030:                 if ($role eq 'st') {
1.52      raeburn  4031:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
1.11      raeburn  4032:                 } else {
                   4033:                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
1.52      raeburn  4034:                                                 $start,'','',$context);
1.11      raeburn  4035:                 }
                   4036:             } elsif ($choice eq 'chgsec') {
                   4037:                 my (@newsecs,$revresult,$nochg,@retained);
                   4038:                 if ($role ne 'cc') {
                   4039:                     @newsecs = split(/,/,$env{'form.newsecs'});
                   4040:                 }
                   4041:                 # remove existing section if not to be retained.   
                   4042:                 if (!$env{'form.retainsec'}) {
                   4043:                     if ($sec eq '') {
                   4044:                         if (@newsecs == 0) {
                   4045:                             $result = &mt('No change in section assignment (none)');
                   4046:                             $nochg = 1;
1.40      raeburn  4047:                         } else {
                   4048:                             $revresult =
                   4049:                                 &Apache::lonnet::revokerole($udom,$uname,
1.52      raeburn  4050:                                                             $scope,$role,
                   4051:                                                             '','',$context);
1.40      raeburn  4052:                         } 
1.11      raeburn  4053:                     } else {
1.28      raeburn  4054:                         if (@newsecs > 0) {
                   4055:                             if (grep(/^\Q$sec\E$/,@newsecs)) {
                   4056:                                 push(@retained,$sec);
                   4057:                             } else {
                   4058:                                 $revresult =
                   4059:                                     &Apache::lonnet::revokerole($udom,$uname,
1.52      raeburn  4060:                                                                 $scope,$role,
                   4061:                                                                 '','',$context);
1.28      raeburn  4062:                             }
                   4063:                         } else {
1.11      raeburn  4064:                             $revresult =
1.28      raeburn  4065:                                 &Apache::lonnet::revokerole($udom,$uname,
1.52      raeburn  4066:                                                             $scope,$role,
                   4067:                                                             '','',$context);
1.11      raeburn  4068:                         }
                   4069:                     }
                   4070:                 } else {
1.28      raeburn  4071:                     if ($sec eq '') {
                   4072:                         $nochg = 1;
                   4073:                     } else { 
                   4074:                         push(@retained,$sec);
                   4075:                     }
1.11      raeburn  4076:                 }
                   4077:                 # add new sections
                   4078:                 if (@newsecs == 0) {
                   4079:                     if (!$nochg) {
1.28      raeburn  4080:                         if ($role eq 'st') {
                   4081:                             $result = 
1.52      raeburn  4082:                                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,undef,$end,$start,$type,$locktype,$cid,'',$context);
1.28      raeburn  4083:                         } else {
                   4084:                             my $newscope = $scopestem;
1.52      raeburn  4085:                             $result = &Apache::lonnet::assignrole($udom,$uname,$newscope,$role,$end,$start,'','',$context);
1.11      raeburn  4086:                         }
                   4087:                     }
                   4088:                 } else {
                   4089:                     foreach my $newsec (@newsecs) { 
                   4090:                         if (!grep(/^\Q$newsec\E$/,@retained)) {
                   4091:                             if ($role eq 'st') {
1.52      raeburn  4092:                                 $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$newsec,$end,$start,$type,$locktype,$cid,'',$context);
1.11      raeburn  4093:                             } else {
                   4094:                                 my $newscope = $scopestem;
                   4095:                                 if ($newsec ne '') {
                   4096:                                    $newscope .= '/'.$newsec;
                   4097:                                 }
                   4098:                                 $result = &Apache::lonnet::assignrole($udom,$uname,
                   4099:                                                         $newscope,$role,$end,$start);
                   4100:                             }
                   4101:                         }
                   4102:                     }
                   4103:                 }
                   4104:             }
                   4105:         }
1.17      raeburn  4106:         my $extent = $scope;
                   4107:         if ($choice eq 'drop' || $context eq 'course') {
                   4108:             my ($cnum,$cdom,$cdesc) = &get_course_identity($cid);
                   4109:             if ($cdesc) {
                   4110:                 $extent = $cdesc;
                   4111:             }
                   4112:         }
1.1       raeburn  4113:         if ($result eq 'ok' || $result eq 'ok:') {
1.11      raeburn  4114:             $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for [_3]",
1.17      raeburn  4115:                           $plrole,$extent,$uname.':'.$udom).'<br />');
1.1       raeburn  4116:             $count++;
                   4117:         } else {
                   4118:             $r->print(
1.29      raeburn  4119:                 &mt("Error $result_text{'error'}{$choice} [_1] in [_2] for [_3]: [_4].",
1.17      raeburn  4120:                     $plrole,$extent,$uname.':'.$udom,$result).'<br />');
1.11      raeburn  4121:         }
                   4122:     }
1.32      raeburn  4123:     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n");
1.33      raeburn  4124:     if ($choice eq 'drop') {
                   4125:         $r->print('<input type="hidden" name="action" value="listusers" />'."\n".
                   4126:                   '<input type="hidden" name="Status" value="Active" />'."\n".
                   4127:                   '<input type="hidden" name="showrole" value="st" />'."\n");
                   4128:     } else {
                   4129:         foreach my $item ('action','sortby','roletype','showrole','Status','secfilter','grpfilter') {
                   4130:             if ($env{'form.'.$item} ne '') {
                   4131:                 $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.
                   4132:                           '" />'."\n");
                   4133:             }
1.32      raeburn  4134:         }
                   4135:     }
1.29      raeburn  4136:     $r->print('<p><b>'.&mt("$result_text{'ok'}{$choice} role(s) for [quant,_1,user,users,no users].",$count).'</b></p>');
1.11      raeburn  4137:     if ($count > 0) {
1.17      raeburn  4138:         if ($choice eq 'revoke' || $choice eq 'drop') {
1.11      raeburn  4139:             $r->print('<p>'.&mt('Re-enabling will re-activate data for the role.</p>'));
                   4140:         }
                   4141:         # Flush the course logs so reverse user roles immediately updated
                   4142:         &Apache::lonnet::flushcourselogs();
                   4143:     }
                   4144:     if ($env{'form.makedatesdefault'}) {
                   4145:         if ($choice eq 'chgdates' || $choice eq 'reenable' || $choice eq 'activate') {
1.29      raeburn  4146:             $r->print(&make_dates_default($startdate,$enddate,$context));
1.1       raeburn  4147:         }
                   4148:     }
1.33      raeburn  4149:     my $linktext = &mt('Display User Lists');
                   4150:     if ($choice eq 'drop') {
                   4151:         $linktext = &mt('Display current class roster');
                   4152:     }
                   4153:     $r->print('<a href="javascript:document.studentform.submit()">'.$linktext.'</a></form>'."\n");
1.1       raeburn  4154: }
                   4155: 
1.8       raeburn  4156: sub classlist_drop {
1.29      raeburn  4157:     my ($scope,$uname,$udom,$now) = @_;
1.8       raeburn  4158:     my ($cdom,$cnum) = ($scope=~m{^/($match_domain)/($match_courseid)});
1.29      raeburn  4159:     if (&Apache::lonnet::is_course($cdom,$cnum)) {
                   4160:         my $user = $uname.':'.$udom;
1.8       raeburn  4161:         if (!&active_student_roles($cnum,$cdom,$uname,$udom)) {
                   4162:             my $result =
                   4163:                 &Apache::lonnet::cput('classlist',
1.29      raeburn  4164:                                       { $user => $now },$cdom,$cnum);
1.8       raeburn  4165:             return &mt('Drop from classlist: [_1]',
                   4166:                        '<b>'.$result.'</b>').'<br />';
                   4167:         }
                   4168:     }
                   4169: }
                   4170: 
                   4171: sub active_student_roles {
                   4172:     my ($cnum,$cdom,$uname,$udom) = @_;
                   4173:     my %roles =
                   4174:         &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   4175:                                       ['future','active'],['st']);
                   4176:     return exists($roles{"$cnum:$cdom:st"});
                   4177: }
                   4178: 
1.1       raeburn  4179: sub section_check_js {
1.8       raeburn  4180:     my $groupslist= &get_groupslist();
1.1       raeburn  4181:     return <<"END";
                   4182: function validate(caller) {
1.9       raeburn  4183:     var groups = new Array($groupslist);
1.1       raeburn  4184:     var secname = caller.value;
                   4185:     if ((secname == 'all') || (secname == 'none')) {
                   4186:         alert("'"+secname+"' may not be used as the name for a section, as it is a reserved word.\\nPlease choose a different section name.");
                   4187:         return 'error';
                   4188:     }
                   4189:     if (secname != '') {
                   4190:         for (var k=0; k<groups.length; k++) {
                   4191:             if (secname == groups[k]) {
                   4192:                 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.");
                   4193:                 return 'error';
                   4194:             }
                   4195:         }
                   4196:     }
                   4197:     return 'ok';
                   4198: }
                   4199: END
                   4200: }
                   4201: 
                   4202: sub set_login {
                   4203:     my ($dom,$authformkrb,$authformint,$authformloc) = @_;
                   4204:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   4205:     my $response;
                   4206:     my ($authnum,%can_assign) =
                   4207:         &Apache::loncommon::get_assignable_auth($dom);
                   4208:     if ($authnum) {
                   4209:         $response = &Apache::loncommon::start_data_table();
                   4210:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
                   4211:             $response .= &Apache::loncommon::start_data_table_row().
                   4212:                          '<td>'.$authformkrb.'</td>'.
                   4213:                          &Apache::loncommon::end_data_table_row()."\n";
                   4214:         }
                   4215:         if ($can_assign{'int'}) {
                   4216:             $response .= &Apache::loncommon::start_data_table_row().
                   4217:                          '<td>'.$authformint.'</td>'.
                   4218:                          &Apache::loncommon::end_data_table_row()."\n"
                   4219:         }
                   4220:         if ($can_assign{'loc'}) {
                   4221:             $response .= &Apache::loncommon::start_data_table_row().
                   4222:                          '<td>'.$authformloc.'</td>'.
                   4223:                          &Apache::loncommon::end_data_table_row()."\n";
                   4224:         }
                   4225:         $response .= &Apache::loncommon::end_data_table();
                   4226:     }
                   4227:     return $response;
                   4228: }
                   4229: 
1.8       raeburn  4230: sub course_sections {
1.51      raeburn  4231:     my ($sections_count,$role,$current_sec) = @_;
1.8       raeburn  4232:     my $output = '';
                   4233:     my @sections = (sort {$a <=> $b} keys %{$sections_count});
1.29      raeburn  4234:     my $numsec = scalar(@sections);
1.51      raeburn  4235:     my $is_selected = ' selected="selected" ';
1.29      raeburn  4236:     if ($numsec <= 1) {
1.8       raeburn  4237:         $output = '<select name="currsec_'.$role.'" >'."\n".
1.51      raeburn  4238:                   '  <option value="">'.&mt('Select').'</option>'."\n";
                   4239:         if ($current_sec eq 'none') {
                   4240:             $output .=       
                   4241:                   '  <option value=""'.$is_selected.'>'.&mt('No section').'</option>'."\n";
                   4242:         } else {
                   4243:             $output .=
1.29      raeburn  4244:                   '  <option value="">'.&mt('No section').'</option>'."\n";
1.51      raeburn  4245:         }
1.29      raeburn  4246:         if ($numsec == 1) {
1.51      raeburn  4247:             if ($current_sec eq $sections[0]) {
                   4248:                 $output .=
                   4249:                   '  <option value="'.$sections[0].'"'.$is_selected.'>'.$sections[0].'</option>'."\n";
                   4250:             } else {
                   4251:                 $output .=  
1.8       raeburn  4252:                   '  <option value="'.$sections[0].'" >'.$sections[0].'</option>'."\n";
1.51      raeburn  4253:             }
1.29      raeburn  4254:         }
1.8       raeburn  4255:     } else {
                   4256:         $output = '<select name="currsec_'.$role.'" ';
                   4257:         my $multiple = 4;
                   4258:         if (scalar(@sections) < 4) { $multiple = scalar(@sections); }
1.29      raeburn  4259:         if ($role eq 'st') {
                   4260:             $output .= '>'."\n".
1.51      raeburn  4261:                        '  <option value="">'.&mt('Select').'</option>'."\n";
                   4262:             if ($current_sec eq 'none') {
                   4263:                 $output .= 
                   4264:                        '  <option value=""'.$is_selected.'>'.&mt('No section')."</option>\n";
                   4265:             } else {
                   4266:                 $output .=
1.29      raeburn  4267:                        '  <option value="">'.&mt('No section')."</option>\n";
1.51      raeburn  4268:             }
1.29      raeburn  4269:         } else {
                   4270:             $output .= 'multiple="multiple" size="'.$multiple.'">'."\n";
                   4271:         }
1.8       raeburn  4272:         foreach my $sec (@sections) {
1.51      raeburn  4273:             if ($current_sec eq $sec) {
                   4274:                 $output .= '<option value="'.$sec.'"'.$is_selected.'>'.$sec."</option>\n";
                   4275:             } else {
                   4276:                 $output .= '<option value="'.$sec.'">'.$sec."</option>\n";
                   4277:             }
1.8       raeburn  4278:         }
                   4279:     }
                   4280:     $output .= '</select>';
                   4281:     return $output;
                   4282: }
                   4283: 
                   4284: sub get_groupslist {
                   4285:     my $groupslist;
                   4286:     my %curr_groups = &Apache::longroup::coursegroups();
                   4287:     if (%curr_groups) {
                   4288:         $groupslist = join('","',sort(keys(%curr_groups)));
                   4289:         $groupslist = '"'.$groupslist.'"';
                   4290:     }
1.11      raeburn  4291:     return $groupslist; 
1.8       raeburn  4292: }
                   4293: 
                   4294: sub setsections_javascript {
1.37      raeburn  4295:     my ($formname,$groupslist,$mode,$checkauth) = @_;
1.28      raeburn  4296:     my ($checkincluded,$finish,$rolecode,$setsection_js);
                   4297:     if ($mode eq 'upload') {
                   4298:         $checkincluded = 'formname.name == "'.$formname.'"';
                   4299:         $finish = "return 'ok';";
                   4300:         $rolecode = "var role = formname.defaultrole.options[formname.defaultrole.selectedIndex].value;\n";
                   4301:     } elsif ($formname eq 'cu') {
1.8       raeburn  4302:         $checkincluded = 'formname.elements[i-1].checked == true';
1.37      raeburn  4303:         if ($checkauth) {
                   4304:             $finish = "var authcheck = auth_check();\n".
                   4305:                       "   if (authcheck == 'ok') {\n".
                   4306:                       "       formname.submit();\n".
                   4307:                       "   }\n";
                   4308:         } else {
                   4309:             $finish = 'formname.submit()';
                   4310:         }
1.28      raeburn  4311:         $rolecode = "var match = str.split('_');
                   4312:                 var role = match[3];\n";
                   4313:     } elsif ($formname eq 'enrollstudent') {
                   4314:         $checkincluded = 'formname.name == "'.$formname.'"';
1.37      raeburn  4315:         if ($checkauth) {
                   4316:             $finish = "var authcheck = auth_check();\n".
                   4317:                       "   if (authcheck == 'ok') {\n".
                   4318:                       "       formname.submit();\n".
                   4319:                       "   }\n";
                   4320:         } else {
                   4321:             $finish = 'formname.submit()';
                   4322:         }
1.28      raeburn  4323:         $rolecode = "var match = str.split('_');
                   4324:                 var role = match[1];\n";
1.8       raeburn  4325:     } else {
1.28      raeburn  4326:         $checkincluded = 'formname.name == "'.$formname.'"'; 
1.8       raeburn  4327:         $finish = "seccheck = 'ok';";
1.28      raeburn  4328:         $rolecode = "var match = str.split('_');
                   4329:                 var role = match[1];\n";
1.11      raeburn  4330:         $setsection_js = "var seccheck = 'alert';"; 
1.8       raeburn  4331:     }
                   4332:     my %alerts = &Apache::lonlocal::texthash(
                   4333:                     secd => 'Section designations do not apply to Course Coordinator roles.',
                   4334:                     accr => 'A course coordinator role will be added with access to all sections.',
                   4335:                     inea => 'In each course, each user may only have one student role at a time.',
                   4336:                     youh => 'You had selected ',
                   4337:                     secs => 'sections.',
                   4338:                     plmo => 'Please modify your selections so they include no more than one section.',
                   4339:                     mayn => 'may not be used as the name for a section, as it is a reserved word.',
                   4340:                     plch => 'Please choose a different section name.',
                   4341:                     mnot => 'may not be used as a section name, as it is the name of a course group.',
                   4342:                     secn => 'Section names and group names must be distinct. Please choose a different section name.',
1.11      raeburn  4343:                  );                
1.8       raeburn  4344:     $setsection_js .= <<"ENDSECCODE";
                   4345: 
                   4346: function setSections(formname) {
                   4347:     var re1 = /^currsec_/;
                   4348:     var groups = new Array($groupslist);
                   4349:     for (var i=0;i<formname.elements.length;i++) {
                   4350:         var str = formname.elements[i].name;
                   4351:         var checkcurr = str.match(re1);
                   4352:         if (checkcurr != null) {
                   4353:             if ($checkincluded) {
1.28      raeburn  4354:                 $rolecode
1.8       raeburn  4355:                 if (role == 'cc') {
                   4356:                     alert("$alerts{'secd'}\\n$alerts{'accr'}");
                   4357:                 }
                   4358:                 else {
                   4359:                     var sections = '';
                   4360:                     var numsec = 0;
                   4361:                     var sections;
                   4362:                     for (var j=0; j<formname.elements[i].length; j++) {
                   4363:                         if (formname.elements[i].options[j].selected == true ) {
                   4364:                             if (formname.elements[i].options[j].value != "") {
                   4365:                                 if (numsec == 0) {
                   4366:                                     if (formname.elements[i].options[j].value != "") {
                   4367:                                         sections = formname.elements[i].options[j].value;
                   4368:                                         numsec ++;
                   4369:                                     }
                   4370:                                 }
                   4371:                                 else {
                   4372:                                     sections = sections + "," +  formname.elements[i].options[j].value
                   4373:                                     numsec ++;
                   4374:                                 }
                   4375:                             }
                   4376:                         }
                   4377:                     }
                   4378:                     if (numsec > 0) {
                   4379:                         if (formname.elements[i+1].value != "" && formname.elements[i+1].value != null) {
                   4380:                             sections = sections + "," +  formname.elements[i+1].value;
                   4381:                         }
                   4382:                     }
                   4383:                     else {
                   4384:                         sections = formname.elements[i+1].value;
                   4385:                     }
                   4386:                     var newsecs = formname.elements[i+1].value;
                   4387:                     var numsplit;
                   4388:                     if (newsecs != null && newsecs != "") {
                   4389:                         numsplit = newsecs.split(/,/g);
                   4390:                         numsec = numsec + numsplit.length;
                   4391:                     }
                   4392: 
                   4393:                     if ((role == 'st') && (numsec > 1)) {
                   4394:                         alert("$alerts{'inea'} $alerts{'youh'} "+numsec+" $alerts{'secs'}\\n$alerts{'plmo'}")
                   4395:                         return;
                   4396:                     }
                   4397:                     else {
                   4398:                         if (numsplit != null) {
                   4399:                             for (var j=0; j<numsplit.length; j++) {
                   4400:                                 if ((numsplit[j] == 'all') ||
                   4401:                                     (numsplit[j] == 'none')) {
                   4402:                                     alert("'"+numsplit[j]+"' $alerts{'mayn'}\\n$alerts{'plch'}");
                   4403:                                     return;
                   4404:                                 }
                   4405:                                 for (var k=0; k<groups.length; k++) {
                   4406:                                     if (numsplit[j] == groups[k]) {
                   4407:                                         alert("'"+numsplit[j]+"' $alerts{'mnot'}\\n$alerts{'secn'}");
                   4408:                                         return;
                   4409:                                     }
                   4410:                                 }
                   4411:                             }
                   4412:                         }
                   4413:                         formname.elements[i+2].value = sections;
                   4414:                     }
                   4415:                 }
                   4416:             }
                   4417:         }
                   4418:     }
                   4419:     $finish
                   4420: }
                   4421: ENDSECCODE
1.11      raeburn  4422:     return $setsection_js; 
1.8       raeburn  4423: }
                   4424: 
1.15      raeburn  4425: sub can_create_user {
                   4426:     my ($dom,$context,$usertype) = @_;
                   4427:     my %domconf = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   4428:     my $cancreate = 1;
1.28      raeburn  4429:     if (&Apache::lonnet::allowed('mau',$dom)) {
                   4430:         return $cancreate;
                   4431:     }
1.15      raeburn  4432:     if (ref($domconf{'usercreation'}) eq 'HASH') {
                   4433:         if (ref($domconf{'usercreation'}{'cancreate'}) eq 'HASH') {
                   4434:             if ($context eq 'course' || $context eq 'author') {
                   4435:                 my $creation = $domconf{'usercreation'}{'cancreate'}{$context};
                   4436:                 if ($creation eq 'none') {
                   4437:                     $cancreate = 0;
                   4438:                 } elsif ($creation ne 'any') {
                   4439:                     if (defined($usertype)) {
                   4440:                         if ($creation ne $usertype) {
                   4441:                             $cancreate = 0;
                   4442:                         }
                   4443:                     }
                   4444:                 }
                   4445:             }
                   4446:         }
                   4447:     }
                   4448:     return $cancreate;
                   4449: }
                   4450: 
1.20      raeburn  4451: sub can_modify_userinfo {
                   4452:     my ($context,$dom,$fields,$userroles) = @_;
                   4453:     my %domconfig =
                   4454:        &Apache::lonnet::get_dom('configuration',['usermodification'],
                   4455:                                 $dom);
                   4456:     my %canmodify;
                   4457:     if (ref($fields) eq 'ARRAY') {
                   4458:         foreach my $field (@{$fields}) {
                   4459:             $canmodify{$field}  = 0;
                   4460:             if (&Apache::lonnet::allowed('mau',$dom)) {
                   4461:                 $canmodify{$field} = 1;
                   4462:             } else {
                   4463:                 if (ref($domconfig{'usermodification'}) eq 'HASH') {
                   4464:                     if (ref($domconfig{'usermodification'}{$context}) eq 'HASH') {
                   4465:                         if (ref($userroles) eq 'ARRAY') {
                   4466:                             foreach my $role (@{$userroles}) {
                   4467:                                 my $testrole;
                   4468:                                 if ($role =~ /^cr\//) {
                   4469:                                     $testrole = 'cr';
                   4470:                                 } else {
                   4471:                                     $testrole = $role;
                   4472:                                 }
                   4473:                                 if (ref($domconfig{'usermodification'}{$context}{$testrole}) eq 'HASH') {
                   4474:                                     if ($domconfig{'usermodification'}{$context}{$testrole}{$field}) {
                   4475:                                         $canmodify{$field} = 1;
                   4476:                                         last;
                   4477:                                     }
                   4478:                                 }
                   4479:                             }
                   4480:                         } else {
                   4481:                             foreach my $key (keys(%{$domconfig{'usermodification'}{$context}})) {
                   4482:                                 if (ref($domconfig{'usermodification'}{$context}{$key}) eq 'HASH') {
                   4483:                                     if ($domconfig{'usermodification'}{$context}{$key}{$field}) {
                   4484:                                         $canmodify{$field} = 1;
                   4485:                                         last;
                   4486:                                     }
                   4487:                                 }
                   4488:                             }
                   4489:                         }
                   4490:                     }
                   4491:                 } elsif ($context eq 'course') {
                   4492:                     if (ref($userroles) eq 'ARRAY') {
                   4493:                         if (grep(/^st$/,@{$userroles})) {
                   4494:                             $canmodify{$field} = 1;
                   4495:                         }
                   4496:                     } else {
                   4497:                         $canmodify{$field} = 1;
                   4498:                     }
                   4499:                 }
                   4500:             }
                   4501:         }
                   4502:     }
                   4503:     return %canmodify;
                   4504: }
                   4505: 
1.18      raeburn  4506: sub check_usertype {
                   4507:     my ($dom,$uname,$rules) = @_;
                   4508:     my $usertype;
                   4509:     if (ref($rules) eq 'HASH') {
                   4510:         my @user_rules = keys(%{$rules});
                   4511:         if (@user_rules > 0) {
                   4512:             my %rule_check = &Apache::lonnet::inst_rulecheck($dom,$uname,undef,'username',\@user_rules);
                   4513:             if (keys(%rule_check) > 0) {
                   4514:                 $usertype = 'unofficial';
                   4515:                 foreach my $item (keys(%rule_check)) {
                   4516:                     if ($rule_check{$item}) {
                   4517:                         $usertype = 'official';
                   4518:                         last;
                   4519:                     }
                   4520:                 }
                   4521:             }
                   4522:         }
                   4523:     }
                   4524:     return $usertype;
                   4525: }
                   4526: 
1.17      raeburn  4527: sub roles_by_context {
                   4528:     my ($context,$custom) = @_;
                   4529:     my @allroles;
                   4530:     if ($context eq 'course') {
                   4531:         @allroles = ('st','ad','ta','ep','in','cc');
                   4532:         if ($custom) {
                   4533:             push(@allroles,'cr');
                   4534:         }
                   4535:     } elsif ($context eq 'author') {
                   4536:         @allroles = ('ca','aa');
                   4537:     } elsif ($context eq 'domain') {
                   4538:         @allroles = ('li','dg','sc','au','dc');
                   4539:     }
                   4540:     return @allroles;
                   4541: }
                   4542: 
1.16      raeburn  4543: sub get_permission {
1.17      raeburn  4544:     my ($context,$roles) = @_;
1.16      raeburn  4545:     my %permission;
                   4546:     if ($context eq 'course') {
1.17      raeburn  4547:         my $custom = 1;
                   4548:         my @allroles = &roles_by_context($context,$custom);
                   4549:         foreach my $role (@allroles) {
                   4550:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
                   4551:                 $permission{'cusr'} = 1;
                   4552:                 last;
                   4553:             }
1.16      raeburn  4554:         }
                   4555:         if (&Apache::lonnet::allowed('ccr',$env{'request.course.id'})) {
                   4556:             $permission{'custom'} = 1;
                   4557:         }
                   4558:         if (&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) {
                   4559:             $permission{'view'} = 1;
                   4560:         }
                   4561:         if (!$permission{'view'}) {
                   4562:             my $scope = $env{'request.course.id'}.'/'.$env{'request.course.sec'};
                   4563:             $permission{'view'} =  &Apache::lonnet::allowed('vcl',$scope);
                   4564:             if ($permission{'view'}) {
                   4565:                 $permission{'view_section'} = $env{'request.course.sec'};
                   4566:             }
                   4567:         }
1.17      raeburn  4568:         if (!$permission{'cusr'}) {
                   4569:             if ($env{'request.course.sec'} ne '') {
                   4570:                 my $scope = $env{'request.course.id'}.'/'.$env{'request.course.sec'};
                   4571:                 $permission{'cusr'} = (&Apache::lonnet::allowed('cst',$scope));
                   4572:                 if ($permission{'cusr'}) {
                   4573:                     $permission{'cusr_section'} = $env{'request.course.sec'};
                   4574:                 }
                   4575:             }
                   4576:         }
1.16      raeburn  4577:         if (&Apache::lonnet::allowed('mdg',$env{'request.course.id'})) {
                   4578:             $permission{'grp_manage'} = 1;
                   4579:         }
                   4580:     } elsif ($context eq 'author') {
                   4581:         $permission{'cusr'} = &authorpriv($env{'user.name'},$env{'request.role.domain'});
                   4582:         $permission{'view'} = $permission{'cusr'};
                   4583:     } else {
1.17      raeburn  4584:         my @allroles = &roles_by_context($context);
                   4585:         foreach my $role (@allroles) {
1.28      raeburn  4586:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
                   4587:                 $permission{'cusr'} = 1;
1.17      raeburn  4588:                 last;
                   4589:             }
                   4590:         }
                   4591:         if (!$permission{'cusr'}) {
                   4592:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
                   4593:                 $permission{'cusr'} = 1;
                   4594:             }
1.16      raeburn  4595:         }
                   4596:         if (&Apache::lonnet::allowed('ccr',$env{'request.role.domain'})) {
                   4597:             $permission{'custom'} = 1;
                   4598:         }
                   4599:         $permission{'view'} = $permission{'cusr'};
                   4600:     }
                   4601:     my $allowed = 0;
                   4602:     foreach my $perm (values(%permission)) {
                   4603:         if ($perm) { $allowed=1; last; }
                   4604:     }
                   4605:     return (\%permission,$allowed);
                   4606: }
                   4607: 
                   4608: # ==================================================== Figure out author access
                   4609: 
                   4610: sub authorpriv {
                   4611:     my ($auname,$audom)=@_;
                   4612:     unless ((&Apache::lonnet::allowed('cca',$audom.'/'.$auname))
                   4613:          || (&Apache::lonnet::allowed('caa',$audom.'/'.$auname))) { return ''; }    return 1;
                   4614: }
                   4615: 
1.27      raeburn  4616: sub roles_on_upload {
1.42      raeburn  4617:     my ($context,$setting,%customroles) = @_;
1.27      raeburn  4618:     my (@possible_roles,@permitted_roles);
1.42      raeburn  4619:     @possible_roles = &curr_role_permissions($context,$setting,1);
1.27      raeburn  4620:     foreach my $role (@possible_roles) {
                   4621:         if ($role eq 'cr') {
                   4622:             push(@permitted_roles,keys(%customroles));
                   4623:         } else {
                   4624:             push(@permitted_roles,$role);
                   4625:         }
                   4626:     }
1.42      raeburn  4627:     return @permitted_roles;
1.27      raeburn  4628: }
                   4629: 
1.17      raeburn  4630: sub get_course_identity {
                   4631:     my ($cid) = @_;
                   4632:     my ($cnum,$cdom,$cdesc);
                   4633:     if ($cid eq '') {
                   4634:         $cid = $env{'request.course.id'}
                   4635:     }
                   4636:     if ($cid ne '') {
                   4637:         $cnum = $env{'course.'.$cid.'.num'};
                   4638:         $cdom = $env{'course.'.$cid.'.domain'};
                   4639:         $cdesc = $env{'course.'.$cid.'.description'};
                   4640:         if ($cnum eq '' || $cdom eq '') {
                   4641:             my %coursehash =
                   4642:                 &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
                   4643:             $cdom = $coursehash{'domain'};
                   4644:             $cnum = $coursehash{'num'};
                   4645:             $cdesc = $coursehash{'description'};
                   4646:         }
                   4647:     }
                   4648:     return ($cnum,$cdom,$cdesc);
                   4649: }
                   4650: 
1.19      raeburn  4651: sub dc_setcourse_js {
1.37      raeburn  4652:     my ($formname,$mode,$context) = @_;
                   4653:     my ($dc_setcourse_code,$authen_check);
1.19      raeburn  4654:     my $cctext = &Apache::lonnet::plaintext('cc');
                   4655:     my %alerts = &sectioncheck_alerts();
                   4656:     my $role = 'role';
                   4657:     if ($mode eq 'upload') {
                   4658:         $role = 'courserole';
1.37      raeburn  4659:     } else {
                   4660:         $authen_check = &verify_authen($formname,$context);
1.19      raeburn  4661:     }
                   4662:     $dc_setcourse_code = (<<"SCRIPTTOP");
1.37      raeburn  4663: $authen_check
                   4664: 
1.19      raeburn  4665: function setCourse() {
                   4666:     var course = document.$formname.dccourse.value;
                   4667:     if (course != "") {
                   4668:         if (document.$formname.dcdomain.value != document.$formname.origdom.value) {
                   4669:             alert("$alerts{'curd'}");
                   4670:             return;
                   4671:         }
                   4672:         var userrole = document.$formname.$role.options[document.$formname.$role.selectedIndex].value
                   4673:         var section="";
                   4674:         var numsections = 0;
                   4675:         var newsecs = new Array();
                   4676:         for (var i=0; i<document.$formname.currsec.length; i++) {
                   4677:             if (document.$formname.currsec.options[i].selected == true ) {
                   4678:                 if (document.$formname.currsec.options[i].value != "" && document.$formname.currsec.options[i].value != null) {
                   4679:                     if (numsections == 0) {
                   4680:                         section = document.$formname.currsec.options[i].value
                   4681:                         numsections = 1;
                   4682:                     }
                   4683:                     else {
                   4684:                         section = section + "," +  document.$formname.currsec.options[i].value
                   4685:                         numsections ++;
                   4686:                     }
                   4687:                 }
                   4688:             }
                   4689:         }
                   4690:         if (document.$formname.newsec.value != "" && document.$formname.newsec.value != null) {
                   4691:             if (numsections == 0) {
                   4692:                 section = document.$formname.newsec.value
                   4693:             }
                   4694:             else {
                   4695:                 section = section + "," +  document.$formname.newsec.value
                   4696:             }
                   4697:             newsecs = document.$formname.newsec.value.split(/,/g);
                   4698:             numsections = numsections + newsecs.length;
                   4699:         }
                   4700:         if ((userrole == 'st') && (numsections > 1)) {
                   4701:             alert("$alerts{'inea'}. $alerts{'youh'} "+numsections+" $alerts{'sect'}.\\n$alerts{'plsm'}.")
                   4702:             return;
                   4703:         }
                   4704:         for (var j=0; j<newsecs.length; j++) {
                   4705:             if ((newsecs[j] == 'all') || (newsecs[j] == 'none')) {
                   4706:                 alert("'"+newsecs[j]+"' $alerts{'mayn'}.\\n$alerts{'plsc'}.");
                   4707:                 return;
                   4708:             }
                   4709:             if (document.$formname.groups.value != '') {
                   4710:                 var groups = document.$formname.groups.value.split(/,/g);
                   4711:                 for (var k=0; k<groups.length; k++) {
                   4712:                     if (newsecs[j] == groups[k]) {
                   4713:                         alert("'"+newsecs[j]+"' $alerts{'mayt'}.\\n$alerts{'secn'}. $alerts{'plsc'}.");
                   4714:                         return;
                   4715:                     }
                   4716:                 }
                   4717:             }
                   4718:         }
                   4719:         if ((userrole == 'cc') && (numsections > 0)) {
                   4720:             alert("$alerts{'secd'} $cctext $alerts{'role'}.\\n$alerts{'accr'}.");
                   4721:             section = "";
                   4722:         }
                   4723: SCRIPTTOP
                   4724:     if ($mode ne 'upload') {
                   4725:         $dc_setcourse_code .= (<<"ENDSCRIPT");
                   4726:         var coursename = "_$env{'request.role.domain'}"+"_"+course+"_"+userrole
                   4727:         var numcourse = getIndex(document.$formname.dccourse);
                   4728:         if (numcourse == "-1") {
                   4729:             alert("$alerts{'thwa'}");
                   4730:             return;
                   4731:         }
                   4732:         else {
                   4733:             document.$formname.elements[numcourse].name = "act"+coursename;
                   4734:             var numnewsec = getIndex(document.$formname.newsec);
                   4735:             if (numnewsec != "-1") {
                   4736:                 document.$formname.elements[numnewsec].name = "sec"+coursename;
                   4737:                 document.$formname.elements[numnewsec].value = section;
                   4738:             }
                   4739:             var numstart = getIndex(document.$formname.start);
                   4740:             if (numstart != "-1") {
                   4741:                 document.$formname.elements[numstart].name = "start"+coursename;
                   4742:             }
                   4743:             var numend = getIndex(document.$formname.end);
                   4744:             if (numend != "-1") {
                   4745:                 document.$formname.elements[numend].name = "end"+coursename
                   4746:             }
                   4747:         }
                   4748:     }
1.37      raeburn  4749:     var authcheck = auth_check();
                   4750:     if (authcheck == 'ok') {
                   4751:         document.$formname.submit();
                   4752:     }
1.19      raeburn  4753: }
                   4754: ENDSCRIPT
                   4755:     } else {
                   4756:         $dc_setcourse_code .=  "
                   4757:         document.$formname.sections.value = section;
                   4758:     }
                   4759:     return 'ok';
                   4760: }
                   4761: ";
                   4762:     }
                   4763:     $dc_setcourse_code .= (<<"ENDSCRIPT");
                   4764: 
                   4765:     function getIndex(caller) {
                   4766:         for (var i=0;i<document.$formname.elements.length;i++) {
                   4767:             if (document.$formname.elements[i] == caller) {
                   4768:                 return i;
                   4769:             }
                   4770:         }
                   4771:         return -1;
                   4772:     }
                   4773: ENDSCRIPT
1.37      raeburn  4774:     return $dc_setcourse_code;
                   4775: }
                   4776: 
                   4777: sub verify_authen {
                   4778:     my ($formname,$context) = @_;
                   4779:     my %alerts = &authcheck_alerts();
                   4780:     my $finish = "return 'ok';";
                   4781:     if ($context eq 'author') {
                   4782:         $finish = "document.$formname.submit();";
                   4783:     }
                   4784:     my $outcome = <<"ENDSCRIPT";
                   4785: 
                   4786: function auth_check() {
                   4787:     var logintype;
                   4788:     if (document.$formname.login.length) {
                   4789:         if (document.$formname.login.length > 0) {
                   4790:             var loginpicked = 0;
                   4791:             for (var i=0; i<document.$formname.login.length; i++) {
                   4792:                 if (document.$formname.login[i].checked == true) {
                   4793:                     loginpicked = 1;
                   4794:                     logintype = document.$formname.login[i].value;
                   4795:                 }
                   4796:             }
                   4797:             if (loginpicked == 0) {
                   4798:                 alert("$alerts{'authen'}");
                   4799:                 return;
                   4800:             }
                   4801:         }
                   4802:     } else {
                   4803:         logintype = document.$formname.login.value;
                   4804:     }
                   4805:     if (logintype == 'nochange') {
                   4806:         return 'ok';
                   4807:     }
                   4808:     var argpicked = document.$formname.elements[logintype+'arg'].value;
                   4809:     if ((argpicked == null) || (argpicked == '') || (typeof argpicked == 'undefined')) {
                   4810:         var alertmsg = '';
                   4811:         switch (logintype) {
                   4812:             case 'krb':
                   4813:                 alertmsg = '$alerts{'krb'}';
                   4814:                 break;
                   4815:             case 'int':
                   4816:                 alertmsg = '$alerts{'ipass'}';
                   4817:             case 'fsys':
                   4818:                 alertmsg = '$alerts{'ipass'}';
                   4819:                 break;
                   4820:             case 'loc':
                   4821:                 alertmsg = '';
                   4822:                 break;
                   4823:             default:
                   4824:                 alertmsg = '';
                   4825:         }
                   4826:         if (alertmsg != '') {
                   4827:             alert(alertmsg);
                   4828:             return;
                   4829:         }
                   4830:     }
                   4831:     $finish
                   4832: }
                   4833: ENDSCRIPT
1.19      raeburn  4834: }
                   4835: 
                   4836: sub sectioncheck_alerts {
                   4837:     my %alerts = &Apache::lonlocal::texthash(
                   4838:                     curd => 'You must select a course in the current domain',
                   4839:                     inea => 'In each course, each user may only have one student role at a time',
                   4840:                     youh => 'You had selected',
                   4841:                     sect => 'sections',
                   4842:                     plsm => 'Please modify your selections so they include no more than one section',
                   4843:                     mayn => 'may not be used as the name for a section, as it is a reserved word',
                   4844:                     plsc => 'Please choose a different section name',
                   4845:                     mayt => 'may not be used as the name for a section, as it is the name of a course group',
                   4846:                     secn => 'Section names and group names must be distinct',
                   4847:                     secd => 'Section designations do not apply to ',
                   4848:                     role => 'roles',
                   4849:                     accr => 'role will be added with access to all sections',
                   4850:                     thwa => 'There was a problem with your course selection'
                   4851:                  );
                   4852:     return %alerts;
                   4853: }
1.17      raeburn  4854: 
1.37      raeburn  4855: sub authcheck_alerts {
                   4856:     my %alerts = 
                   4857:         &Apache::lonlocal::texthash(
                   4858:                     authen => 'You must choose an authentication type.',
                   4859:                     krb    => 'You need to specify the Kerberos domain.',
                   4860:                     ipass  => 'You need to specify the initial password.',
                   4861:         );
                   4862:     return %alerts;
                   4863: }
                   4864: 
1.1       raeburn  4865: 1;
                   4866: 

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