File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.212: download - view: text, annotated - select for diffs
Wed Nov 23 02:55:37 2022 UTC (19 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Take into account domain configuration in user's domain for whether approval
  (from user's DC or user) is needed to complete assignment of a role in a
  domain, authoring space, or course that does not belog to the user's domain.
  Work in progress.

    1: # The LearningOnline Network with CAPA
    2: # Utility functions for managing LON-CAPA user accounts
    3: #
    4: # $Id: lonuserutils.pm,v 1.212 2022/11/23 02:55:37 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA#
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: #
   28: ###############################################################
   29: ###############################################################
   30: 
   31: package Apache::lonuserutils;
   32: 
   33: =pod
   34: 
   35: =head1 NAME
   36: 
   37: Apache::lonuserutils.pm
   38: 
   39: =head1 SYNOPSIS
   40: 
   41:     Utilities for management of users and custom roles
   42: 
   43:     Provides subroutines called by loncreateuser.pm
   44: 
   45: =head1 OVERVIEW
   46: 
   47: =cut
   48: 
   49: use strict;
   50: use Apache::lonnet;
   51: use Apache::loncommon();
   52: use Apache::lonhtmlcommon;
   53: use Apache::loncoursequeueadmin;
   54: use Apache::lonlocal;
   55: use Apache::longroup;
   56: use HTML::Entities;
   57: use LONCAPA qw(:DEFAULT :match);
   58: 
   59: ###############################################################
   60: ###############################################################
   61: # Drop student from all sections of a course, except optional $csec
   62: sub modifystudent {
   63:     my ($udom,$unam,$courseid,$csec,$desiredhost,$context)=@_;
   64:     # if $csec is undefined, drop the student from all the courses matching
   65:     # this one.  If $csec is defined, drop them from all other sections of
   66:     # this course and add them to section $csec
   67:     my ($cnum,$cdom) = &get_course_identity($courseid);
   68:     my %roles = &Apache::lonnet::dump('roles',$udom,$unam);
   69:     my ($tmp) = keys(%roles);
   70:     # Bail out if we were unable to get the students roles
   71:     return "$1" if ($tmp =~ /^(con_lost|error|no_such_host)/i);
   72:     # Go through the roles looking for enrollment in this course
   73:     my $result = '';
   74:     foreach my $course (keys(%roles)) {
   75:         if ($course=~m{^/\Q$cdom\E/\Q$cnum\E(?:\/)*(?:\s+)*(\w+)*\_st$}) {
   76:             # We are in this course
   77:             my $section=$1;
   78:             $section='' if ($course eq "/$cdom/$cnum".'_st');
   79:             if (defined($csec) && $section eq $csec) {
   80:                 $result .= 'ok:';
   81:             } elsif ( ((!$section) && (!$csec)) || ($section ne $csec) ) {
   82:                 my (undef,$end,$start)=split(/\_/,$roles{$course});
   83:                 my $now=time;
   84:                 # if this is an active role
   85:                 if (!($start && ($now<$start)) || !($end && ($now>$end))) {
   86:                     my $reply=&Apache::lonnet::modifystudent
   87:                         # dom  name  id mode pass     f     m     l     g
   88:                         ($udom,$unam,'',  '',  '',undef,undef,undef,undef,
   89:                          $section,time,undef,undef,$desiredhost,'','manual',
   90:                          '',$courseid,'',$context);
   91:                     $result .= $reply.':';
   92:                 }
   93:             }
   94:         }
   95:     }
   96:     if ($result eq '') {
   97:         $result = &mt('Unable to find section for this student');
   98:     } else {
   99:         $result =~ s/(ok:)+/ok/g;
  100:     }
  101:     return $result;
  102: }
  103: 
  104: sub modifyuserrole {
  105:     my ($context,$setting,$changeauth,$cid,$udom,$uname,$uid,$umode,$upass,
  106:         $first,$middle,$last,$gene,$sec,$forceid,$desiredhome,$email,$role,
  107:         $end,$start,$checkid,$inststatus) = @_;
  108:     my ($scope,$userresult,$authresult,$roleresult,$idresult);
  109:     if ($setting eq 'course' || $context eq 'course') {
  110:         $scope = '/'.$cid;
  111:         $scope =~ s/\_/\//g;
  112:         if (($role ne 'cc') && ($role ne 'co') && ($sec ne '')) {
  113:             $scope .='/'.$sec;
  114:         }
  115:     } elsif ($context eq 'domain') {
  116:         $scope = '/'.$env{'request.role.domain'}.'/';
  117:     } elsif ($context eq 'author') {
  118:         $scope =  '/'.$env{'user.domain'}.'/'.$env{'user.name'};
  119:     }
  120:     if ($context eq 'domain') {
  121:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
  122:         if ($uhome ne 'no_host') {
  123:             if (($changeauth eq 'Yes') && (&Apache::lonnet::allowed('mau',$udom))) {
  124:                 if ((($umode =~ /^krb4|krb5|internal$/) && $upass ne '') ||
  125:                     ($umode eq 'localauth')) {
  126:                     $authresult = &Apache::lonnet::modifyuserauth($udom,$uname,$umode,$upass);
  127:                 }
  128:             }
  129:             if (($forceid) && (&Apache::lonnet::allowed('mau',$udom)) &&
  130:                 ($env{'form.recurseid'}) && ($checkid)) {
  131:                 my %userupdate = (
  132:                                   lastname   => $last,
  133:                                   middlename => $middle,
  134:                                   firstname  => $first,
  135:                                   generation => $gene,
  136:                                   id         => $uid,
  137:                                  );
  138:                 $idresult = &propagate_id_change($uname,$udom,\%userupdate);
  139:             }
  140:         }
  141:     }
  142:     $userresult =
  143:         &Apache::lonnet::modifyuser($udom,$uname,$uid,$umode,$upass,$first,
  144:                                     $middle,$last,$gene,$forceid,$desiredhome,
  145:                                     $email,$inststatus);
  146:     if ($userresult eq 'ok') {
  147:         if ($role ne '') {
  148:             $role =~ s/_/\//g;
  149:             $roleresult = &Apache::lonnet::assignrole($udom,$uname,$scope,
  150:                                                       $role,$end,$start,'',
  151:                                                       '',$context);
  152:         }
  153:     }
  154:     return ($userresult,$authresult,$roleresult,$idresult);
  155: }
  156: 
  157: sub role_approval {
  158:     my ($dom,$context,$process_by,$notifydc) = @_;
  159:     if (ref($process_by) eq 'HASH') {
  160:         my %domconfig = &Apache::lonnet::get_dom('configuration',['privacy'],$dom);
  161:         if (ref($domconfig{'privacy'}) eq 'HASH') {
  162:             if (ref($notifydc) eq 'ARRAY') {
  163:                 if ($domconfig{'privacy'}{'notify'} ne '') {
  164:                     @{$notifydc} = split(/,/,$domconfig{'privacy'}{'notify'});
  165:                 }
  166:             }
  167:             if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
  168:                 my %approvalconf = %{$domconfig{'privacy'}{'approval'}};
  169:                 foreach my $key ('instdom','extdom') {
  170:                     if (ref($approvalconf{$key}) eq 'HASH') {
  171:                         if (keys(%{$approvalconf{$key}})) {
  172:                             $process_by->{$key} = $approvalconf{$key}{$context};
  173:                         }
  174:                     }
  175:                 }
  176:             }
  177:         }
  178:     }
  179:     return;
  180: }
  181: 
  182: sub get_instdoms {
  183:     my ($udom,$instdoms) = @_;
  184:     return unless (ref($instdoms) eq 'ARRAY');
  185:     my @intdoms;
  186:     my %iphost = &Apache::lonnet::get_iphost();
  187:     my $primary_id = &Apache::lonnet::domain($udom,'primary');
  188:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
  189:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
  190:         foreach my $id (@{$iphost{$primary_ip}}) {
  191:             my $intdom = &Apache::lonnet::internet_dom($id);
  192:             unless(grep(/^\Q$intdom\E$/,@intdoms)) {
  193:                 push(@intdoms,$intdom);
  194:             }
  195:         }
  196:     }
  197:     foreach my $ip (keys(%iphost)) {
  198:         if (ref($iphost{$ip}) eq 'ARRAY') {
  199:             foreach my $id (@{$iphost{$ip}}) {
  200:                 my $location = &Apache::lonnet::internet_dom($id);
  201:                 if ($location) {
  202:                     if (grep(/^\Q$location\E$/,@intdoms)) {
  203:                         my $dom = &Apache::lonnet::host_domain($id);
  204:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
  205:                             push(@{$instdoms},$dom);
  206:                         }
  207:                     }
  208:                 }
  209:             }
  210:         }
  211:     }
  212:     return;
  213: }
  214: 
  215: sub restricted_dom {
  216:     my ($context,$key,$udom,$uname,$role,$start,$end,$cdom,$cnum,$csec,$credits,
  217:         $process_by,$instdoms,$got_role_approvals,$got_instdoms,$reject,$pending,
  218:         $notifydc) = @_;
  219:     return if ($udom eq $cdom);
  220:     return unless ((ref($process_by) eq 'HASH') && (ref($instdoms) eq 'HASH') &&
  221:                    (ref($got_role_approvals) eq 'HASH') && (ref($got_instdoms) eq 'HASH') &&
  222:                    (ref($reject) eq 'HASH') && (ref($pending) eq 'HASH') &&
  223:                    (ref($notifydc) eq 'HASH'));
  224:     my (%approval,@notify,$gotdata,$skip);
  225:     if (ref($got_role_approvals->{$context}) eq 'HASH') {
  226:         if ($got_role_approvals->{$context}{$udom}) {
  227:             $gotdata = 1;
  228:             if (ref($process_by->{$context}{$udom}) eq 'HASH') {
  229:                 %approval = %{$process_by->{$context}{$udom}};
  230:             }
  231:         }
  232:     }
  233:     unless ($gotdata) {
  234:         &role_approval($udom,$context,\%approval,\@notify);
  235:         $process_by->{$context} = {
  236:                                     $udom => \%approval,
  237:                                   };
  238:         $got_role_approvals->{$context} = {
  239:                                             $udom => 1,
  240:                                           };
  241:         $notifydc->{$udom} = \@notify;
  242:     }
  243:     if (ref($process_by->{$context}) eq 'HASH') {
  244:         if (ref($process_by->{$context}{$udom}) eq 'HASH') {
  245:             my @inst;
  246:             if ($got_instdoms->{$udom}) {
  247:                 if (ref($instdoms->{$udom}) eq 'ARRAY') {
  248:                     @inst = @{$instdoms->{$udom}};
  249:                 }
  250:             } else {
  251:                 &get_instdoms(\@inst);
  252:                 $instdoms->{$udom} = \@inst;
  253:                 $got_instdoms->{$udom} = 1;
  254:             }
  255:             if (grep(/^\Q$cdom\E$/,@inst)) {
  256:                 if (exists($approval{'instdom'})) {
  257:                     my $rule = $approval{'instdom'};
  258:                     if ($rule eq 'none') {
  259:                         $reject->{$key} = {
  260:                                             cdom  => $cdom,
  261:                                             cnum  => $cnum,
  262:                                             csec  => $csec,
  263:                                             udom  => $udom,
  264:                                             uname => $uname,
  265:                                             role  => $role,
  266:                                           };
  267:                         $skip = 1;
  268:                     } elsif (($rule eq 'user') || ($rule eq 'domain')) {
  269:                         $pending->{$key} = {
  270:                                              cdom  => $cdom,
  271:                                              cnum  => $cnum,
  272:                                              csec  => $csec,
  273:                                              udom  => $udom,
  274:                                              uname => $uname,
  275:                                              role  => $role,
  276:                                              start => $start,
  277:                                              end   => $end,
  278:                                              adj   => $rule,
  279:                                            };
  280:                         if (($role eq 'st') && ($credits ne '')) {
  281:                             $pending->{$key}->{'credits'} = $credits;
  282:                         }
  283:                         $skip = 1;
  284:                     }
  285:                 }
  286:             } elsif (exists($approval{'extdom'})) {
  287:                 my $rule = $approval{'extdom'};
  288:                 if ($rule eq 'none') {
  289:                     $reject->{$key} = {
  290:                                         cdom  => $cdom,
  291:                                         cnum  => $cnum,
  292:                                         csec  => $csec,
  293:                                         udom  => $udom,
  294:                                         uname => $uname,
  295:                                         role  => $role,
  296:                                       };
  297:                     $skip = 1;
  298:                 } elsif (($rule eq 'user') || ($rule eq 'domain')) {
  299:                     $pending->{$key} = {
  300:                                          cdom  => $cdom,
  301:                                          cnum  => $cnum,
  302:                                          csec  => $csec,
  303:                                          udom  => $udom,
  304:                                          uname => $uname,
  305:                                          role  => $role,
  306:                                          start => $start,
  307:                                          end   => $end,
  308:                                          adj   => $rule,
  309:                                        };
  310:                     if (($role eq 'st') && ($credits ne '')) {
  311:                         $pending->{$key}->{'credits'} = $credits;
  312:                     }
  313:                     $skip = 1;
  314:                 }
  315:             }
  316:         }
  317:     }
  318:     return $skip;
  319: }
  320: 
  321: sub print_roles_rejected {
  322:     my ($context,$reject) = @_;
  323:     return unless (ref($reject) eq 'HASH');
  324:     my $output;
  325:     if (keys(%{$reject}) > 0) {
  326:         $output = '<p class="LC_warning">'.
  327:                   &mt("The following roles could not be assigned because the user is from another domain, and that domain's policies disallow it").'<ul>';
  328:         foreach my $key (sort(keys(%{$reject}))) {
  329:             if (ref($reject->{$key}) eq 'HASH') {
  330:                 my ($crstype,$role,$cdom,$cnum,$title);
  331:                 $role = $reject->{$key}{'role'};
  332:                 $cdom = $reject->{$key}{'cdom'};
  333:                 $cnum = $reject->{$key}{'cnum'};
  334:                 if ($context eq 'domain') {
  335:                     if (&Apache::lonnet::is_course($cdom,$cnum)) {
  336:                         my %coursedata = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
  337:                         $crstype = $coursedata{'type'};
  338:                         $title = $coursedata{'description'};
  339:                     } elsif (($role eq 'ca') || ($role eq 'aa')) {
  340:                         $title = &Apache::loncommon::plainname($cnum,$cdom);
  341:                     }
  342:                 } elsif ($context eq 'course') {
  343:                     $crstype = &Apache::loncommon::course_type();
  344:                 }
  345:                 my $plainrole = &Apache::lonnet::plaintext($reject->{$key}{'role'},$crstype);
  346:                 $output .= '<li>'.&mt('User: [_1]',$reject->{$key}{'uname'}).' | '.
  347:                                   &mt('Domain: [_1]',$reject->{$key}{'udom'}).' | '.
  348:                                   &mt('Role: [_1]',$plainrole);
  349:                 if ($crstype) {
  350:                     $output .= ' | '.&mt('Section: [_1]',$reject->{$key}{'csec'});
  351:                 } elsif (($context eq 'domain') && (($role eq 'ca') || ($role eq 'aa'))) {
  352:                     $output .= ' | '.&mt('Authoring Space belonging to: [_1]',$title);
  353:                 }
  354:                 if (($context eq 'domain') && ($crstype)) {
  355:                     $output .= ' | '.&mt("$crstype: [_1]",$title);
  356:                 }
  357:                 $output .= '</li>';
  358:             }
  359:         }
  360:         $output .= '</ul></p>';
  361:     }
  362:     return $output;
  363: }
  364: 
  365: sub print_roles_queued {
  366:     my ($context,$pending,$notifydc) = @_;
  367:     return unless ((ref($pending) eq 'HASH') && (ref($notifydc) eq 'HASH'));
  368:     my $output;
  369:     if (keys(%{$pending}) > 0) {
  370:         my $now = time;
  371:         $output = '<p class="LC_warning">'.
  372:                   &mt("The following role assignments have been queued because the user is from another domain, and that domain's policies require approval by the user themselves or by a domain coordinator in that domain").'<ul>';
  373:         my (%todom,%touser,%crsqueue,%caqueue,%domqueue);
  374:         my $requester = $env{'user.name'}.':'.$env{'user.domain'};
  375:         foreach my $key (sort(keys(%{$pending}))) {
  376:             if (ref($pending->{$key}) eq 'HASH') {
  377:                 my $role = $pending->{$key}{'role'};
  378:                 my $uname = $pending->{$key}{'uname'};
  379:                 my $udom = $pending->{$key}{'udom'};
  380:                 my $csec = $pending->{$key}{'csec'};
  381:                 my $cdom = $pending->{$key}{'cdom'};
  382:                 my $cnum = $pending->{$key}{'cnum'};
  383:                 my $adj = $pending->{$key}{'adj'};
  384:                 my $start = $pending->{$key}{'start'};
  385:                 my $end = $pending->{$key}{'end'};
  386:                 my $credits = $pending->{$key}{'credits'};
  387:                 my $now = time;
  388:                 my ($crstype,$title);
  389:                 if ($context eq 'course') {
  390:                     $crstype = &Apache::loncommon::course_type();
  391:                 } elsif ($context eq 'domain') {
  392:                     if (&Apache::lonnet::is_course($cdom,$cnum)) {
  393:                         my %coursedata = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
  394:                         $crstype = $coursedata{'type'};
  395:                         $title = $coursedata{'description'};
  396:                     } elsif (($role eq 'ca') || ($role eq 'aa')) {
  397:                         $title = &Apache::loncommon::plainname($cnum,$cdom);
  398:                     }
  399:                 }
  400:                 my $plainrole = &Apache::lonnet::plaintext($role,$crstype);
  401:                 my $extent = "/$cdom/$cnum";
  402:                 $output .= '<li>'.&mt('User: [_1]',$uname).' | '.
  403:                                   &mt('Domain: [_1]',$udom).' | '.
  404:                                   &mt('Role: [_1]',$plainrole).' | ';
  405:                 if ($crstype) {
  406:                     if ($csec ne '') {
  407:                         $output .= &mt('Section: [_1]',$csec).' | ';
  408:                         $extent .= "/$csec";
  409:                     }
  410:                 }
  411:                 if ($adj eq 'user') {
  412:                     $output .= '<br />'.&mt('Message sent to user for approval');
  413:                     $touser{$uname.':'.$udom}{$extent.':'.$role} = {
  414:                                                                      timestamp => $now,
  415:                                                                      requester => $requester,
  416:                                                                      start     => $start,
  417:                                                                      end       => $end,
  418:                                                                      credits   => $credits,
  419:                                                                      context   => $context,
  420:                                                                    };
  421:                 } elsif ($adj eq 'domain') {
  422:                     $output .= '<br />'.&mt("Message sent to user's domain coordinator for approval");
  423:                     $todom{$udom}{$uname.':'.$extent.':'.$role} = {
  424:                                                                     timestamp => $now,
  425:                                                                     requester => $requester,
  426:                                                                     start     => $start,
  427:                                                                     end       => $end,
  428:                                                                     credits   => $credits,
  429:                                                                     context   => $context,
  430:                                                                   };
  431:                 }
  432:                 $output .= '</li>';
  433:                 my $id = $uname.':'.$udom.':'.$role;
  434:                 if (($context eq 'course') || ($crstype)) {
  435:                     $id .= ':'.$csec;
  436:                     $crsqueue{$cdom.'_'.$cnum}{$id} = {
  437:                                                         timestamp => $now,
  438:                                                         requester => $requester,
  439:                                                         adj       => $adj,
  440:                                                       };
  441:                 } elsif (($context eq 'author') ||
  442:                          (($context eq 'domain') && (($role eq 'ca') || ($role eq 'aa')))) {
  443:                     $caqueue{$cnum.':'.$cdom}{$id} = {
  444:                                                         timestamp => $now,
  445:                                                         requester => $requester,
  446:                                                         adj       => $adj,
  447:                                                       };
  448:                 } elsif ($context eq 'domain') {
  449:                     $domqueue{$id} = {
  450:                                         timestamp => $now,
  451:                                         requester => $requester,
  452:                                         adj       => $adj,
  453:                                      };
  454:                 }
  455:             }
  456:         }
  457:         $output .= '</ul></p>';
  458:         if (keys(%touser)) {
  459:             foreach my $key (keys(%touser)) {
  460:                 my ($uname,$udom) = split(/:/,$touser{$key});
  461:                 if (&Apache::lonnet::put('queuedrolereqs',$touser{$key},$udom,$uname) eq 'ok') {
  462:                     my $owndomdesc = &Apache::lonnet::domain($udom);
  463:                     &Apache::loncoursequeueadmin::send_selfserve_notification($uname.':'.$udom,
  464:                         '','',$owndomdesc,$now,'othdomroleuser',$requester);
  465:                 }
  466:             }
  467:         }
  468:         if (keys(%todom)) {
  469:             foreach my $dom (keys(%todom)) {
  470:                 if (ref($todom{$dom}) eq 'HASH') {
  471:                     my $confname = &Apache::lonnet::get_domainconfiguser($dom);
  472:                     if (&Apache::lonnet::put('queuedrolereqs',$todom{$dom},$dom,$confname) eq 'ok') {
  473:                         if (ref($notifydc->{$dom}) eq 'ARRAY') {
  474:                             if (@{$notifydc->{$dom}} > 0) {
  475:                                 my $notifylist = join(',',@{$notifydc->{$dom}});
  476:                                 &Apache::loncoursequeueadmin::send_selfserve_notification($notifylist,
  477:                                     '','','',$now,'othdomroledc',$requester);
  478:                             }
  479:                         }
  480:                     }
  481:                 }
  482:             }
  483:         }
  484:         if (keys(%crsqueue)) {
  485:             foreach my $key (keys(%crsqueue)) {
  486:                 my ($cdom,$cnum) = split(/_/,$key);
  487:                 if (ref($crsqueue{$key}) eq 'HASH') {
  488:                     &Apache::lonnet::put('othdomqueued',$crsqueue{$key},$cdom,$cnum);
  489:                 }
  490:             }
  491:         }
  492:         if (keys(%caqueue)) {
  493:             foreach my $key (keys(%caqueue)) {
  494:                 my ($auname,$audom) = split(/:/,$key);
  495:                 if (ref($caqueue{$key}) eq 'HASH') {
  496:                     &Apache::lonnet::put('othdomqueued',$caqueue{$key},$audom,$auname);
  497:                 }
  498:             }
  499:         }
  500:         if (keys(%domqueue)) {
  501:             my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'});
  502:             &Apache::lonnet::put('othdomqueued',\%domqueue,$env{'request.role.domain'},$confname);
  503:         }
  504:     }
  505:     return $output;
  506: }
  507: 
  508: sub propagate_id_change {
  509:     my ($uname,$udom,$user) = @_;
  510:     my (@types,@roles);
  511:     @types = ('active','future');
  512:     @roles = ('st');
  513:     my $idresult;
  514:     my %roleshash = &Apache::lonnet::get_my_roles($uname,
  515:                         $udom,'userroles',\@types,\@roles);
  516:     my %args = (
  517:                 one_time => 1,
  518:                );
  519:     foreach my $item (keys(%roleshash)) {
  520:         my ($cnum,$cdom,$role) = split(/:/,$item,-1);
  521:         my ($start,$end) = split(/:/,$roleshash{$item});
  522:         if (&Apache::lonnet::is_course($cdom,$cnum)) {
  523:             my $result = &update_classlist($cdom,$cnum,$udom,$uname,$user);
  524:             my %coursehash = 
  525:                 &Apache::lonnet::coursedescription($cdom.'_'.$cnum,\%args);
  526:             my $cdesc = $coursehash{'description'};
  527:             if ($cdesc eq '') { 
  528:                 $cdesc = $cdom.'_'.$cnum;
  529:             }
  530:             if ($result eq 'ok') {
  531:                 $idresult .= &mt('Classlist update for "[_1]" in "[_2]".',$uname.':'.$udom,$cdesc).'<br />'."\n";
  532:             } else {
  533:                 $idresult .= &mt('Error: "[_1]" during classlist update for "[_2]" in "[_3]".',$result,$uname.':'.$udom,$cdesc).'<br />'."\n";
  534:             }
  535:         }
  536:     }
  537:     return $idresult;
  538: }
  539: 
  540: sub update_classlist {
  541:     my ($cdom,$cnum,$udom,$uname,$user,$newend) = @_;
  542:     my ($uid,$classlistentry);
  543:     my $fullname =
  544:         &Apache::lonnet::format_name($user->{'firstname'},$user->{'middlename'},
  545:                                      $user->{'lastname'},$user->{'generation'},
  546:                                      'lastname');
  547:     my %classhash = &Apache::lonnet::get('classlist',[$uname.':'.$udom],
  548:                                          $cdom,$cnum);
  549:     my @classinfo = split(/:/,$classhash{$uname.':'.$udom});
  550:     my $ididx=&Apache::loncoursedata::CL_ID() - 2;
  551:     my $nameidx=&Apache::loncoursedata::CL_FULLNAME() - 2;
  552:     my $endidx = &Apache::loncoursedata::CL_END() - 2;
  553:     my $startidx = &Apache::loncoursedata::CL_START() - 2;
  554:     for (my $i=0; $i<@classinfo; $i++) {
  555:         if ($i == $endidx) {
  556:             if ($newend ne '') {
  557:                 $classlistentry .= $newend.':';
  558:             } else {
  559:                 $classlistentry .= $classinfo[$i].':';
  560:             }
  561:         } elsif ($i == $startidx) {
  562:             if ($newend ne '') {
  563:                 if ($classinfo[$i] > $newend) {
  564:                     $classlistentry .= $newend.':';
  565:                 } else {
  566:                     $classlistentry .= $classinfo[$i].':';
  567:                 }
  568:             } else {
  569:                 $classlistentry .= $classinfo[$i].':';
  570:             }
  571:         } elsif ($i == $ididx) {
  572:             if (defined($user->{'id'})) {
  573:                 $classlistentry .= $user->{'id'}.':';
  574:             } else {
  575:                 $classlistentry .= $classinfo[$i].':';
  576:             }
  577:         } elsif ($i == $nameidx) {
  578:             if (defined($user->{'lastname'})) {
  579:                 $classlistentry .= $fullname.':';
  580:             } else {
  581:                 $classlistentry .= $classinfo[$i].':';
  582:             }
  583:         } else {
  584:             $classlistentry .= $classinfo[$i].':';
  585:         }
  586:     }
  587:     $classlistentry =~ s/:$//;
  588:     my $reply=&Apache::lonnet::cput('classlist',
  589:                                     {"$uname:$udom" => $classlistentry},
  590:                                     $cdom,$cnum);
  591:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
  592:         return 'ok';
  593:     } else {
  594:         return 'error: '.$reply;
  595:     }
  596: }
  597: 
  598: 
  599: ###############################################################
  600: ###############################################################
  601: # build a role type and role selection form
  602: sub domain_roles_select {
  603:     # Set up the role type and role selection boxes when in 
  604:     # domain context   
  605:     #
  606:     # Role types
  607:     my @roletypes = ('domain','author','course','community');
  608:     my %lt = &role_type_names();
  609:     my $onchangefirst = "updateCols('showrole')";
  610:     my $onchangesecond = "updateCols('showrole')";
  611:     #
  612:     # build up the menu information to be passed to
  613:     # &Apache::loncommon::linked_select_forms
  614:     my %select_menus;
  615:     if ($env{'form.roletype'} eq '') {
  616:         $env{'form.roletype'} = 'domain';
  617:     }
  618:     foreach my $roletype (@roletypes) {
  619:         # set up the text for this domain
  620:         $select_menus{$roletype}->{'text'}= $lt{$roletype};
  621:         my $crstype;
  622:         if ($roletype eq 'community') {
  623:             $crstype = 'Community';
  624:         }
  625:         # we want a choice of 'default' as the default in the second menu
  626:         if ($env{'form.roletype'} ne '') {
  627:             $select_menus{$roletype}->{'default'} = $env{'form.showrole'};
  628:         } else { 
  629:             $select_menus{$roletype}->{'default'} = 'Any';
  630:         }
  631:         # Now build up the other items in the second menu
  632:         my @roles;
  633:         if ($roletype eq 'domain') {
  634:             @roles = &domain_roles();
  635:         } elsif ($roletype eq 'author') {
  636:             @roles = &construction_space_roles();
  637:         } else {
  638:             my $custom = 1;
  639:             @roles = &course_roles('domain',undef,$custom,$roletype);
  640:         }
  641:         my $order = ['Any',@roles];
  642:         $select_menus{$roletype}->{'order'} = $order; 
  643:         foreach my $role (@roles) {
  644:             if ($role eq 'cr') {
  645:                 $select_menus{$roletype}->{'select2'}->{$role} =
  646:                               &mt('Custom role');
  647:             } else {
  648:                 $select_menus{$roletype}->{'select2'}->{$role} = 
  649:                               &Apache::lonnet::plaintext($role,$crstype);
  650:             }
  651:         }
  652:         $select_menus{$roletype}->{'select2'}->{'Any'} = &mt('Any');
  653:     }
  654:     my $result = &Apache::loncommon::linked_select_forms
  655:         ('studentform',('&nbsp;'x3).&mt('Role: '),$env{'form.roletype'},
  656:          'roletype','showrole',\%select_menus,
  657:          ['domain','author','course','community'],$onchangefirst,
  658:          $onchangesecond);
  659:     return $result;
  660: }
  661: 
  662: ###############################################################
  663: ###############################################################
  664: sub hidden_input {
  665:     my ($name,$value) = @_;
  666:     return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
  667: }
  668: 
  669: sub print_upload_manager_header {
  670:     my ($r,$datatoken,$distotal,$krbdefdom,$context,$permission,$crstype,
  671:         $can_assign)=@_;
  672:     my $javascript;
  673:     #
  674:     if (! exists($env{'form.upfile_associate'})) {
  675:         $env{'form.upfile_associate'} = 'forward';
  676:     }
  677:     if ($env{'form.associate'} eq 'Reverse Association') {
  678:         if ( $env{'form.upfile_associate'} ne 'reverse' ) {
  679:             $env{'form.upfile_associate'} = 'reverse';
  680:         } else {
  681:             $env{'form.upfile_associate'} = 'forward';
  682:         }
  683:     }
  684:     if ($env{'form.upfile_associate'} eq 'reverse') {
  685:         $javascript=&upload_manager_javascript_reverse_associate($can_assign);
  686:     } else {
  687:         $javascript=&upload_manager_javascript_forward_associate($can_assign);
  688:     }
  689:     #
  690:     # Deal with restored settings
  691:     my $password_choice = '';
  692:     if (exists($env{'form.ipwd_choice'}) &&
  693:         $env{'form.ipwd_choice'} ne '') {
  694:         # If a column was specified for password, assume it is for an
  695:         # internal password.  This is a bug waiting to be filed (could be
  696:         # local or krb auth instead of internal) but I do not have the
  697:         # time to mess around with this now.
  698:         $password_choice = 'int';
  699:     }
  700:     #
  701:     my $groupslist;
  702:     if ($context eq 'course') {
  703:         $groupslist = &get_groupslist();
  704:     }
  705:     my $javascript_validations =
  706:         &javascript_validations('upload',$krbdefdom,$password_choice,undef,
  707:                                 $env{'request.role.domain'},$context,
  708:                                 $groupslist,$crstype);
  709:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
  710:     $r->print(
  711:         '<h3>'.&mt('Identify fields in uploaded list')."</h3>\n".
  712:         '<p class="LC_info">'.
  713:         &mt('Total number of records found in file: [_1]'
  714:            ,'<b>'.$distotal.'</b>').
  715:         "</p>\n"
  716:     );
  717:     if ($distotal == 0) {
  718:         $r->print('<p class="LC_warning">'.&mt('None found').'</p>');
  719:     }
  720:     $r->print(
  721:         '<p>'.
  722:         &mt('Enter as many fields as you can.').'<br />'.
  723:         &mt('The system will inform you and bring you back to this page,[_1]if the data selected are insufficient to add users.','<br />').
  724:         "</p>\n"
  725:     );
  726:     $r->print(&hidden_input('action','upload').
  727:               &hidden_input('state','got_file').
  728:               &hidden_input('associate','').
  729:               &hidden_input('datatoken',$datatoken).
  730:               &hidden_input('fileupload',$env{'form.fileupload'}).
  731:               &hidden_input('upfiletype',$env{'form.upfiletype'}).
  732:               &hidden_input('upfile_associate',$env{'form.upfile_associate'}));
  733:     $r->print(
  734:         '<div class="LC_left_float">'.
  735:         '<fieldset><legend>'.&mt('Functions').'</legend>'.
  736:         '<label><input type="checkbox" name="noFirstLine"'.$checked.' />'.
  737:               &mt('Ignore First Line').'</label>'.
  738:         ' <input type="button" value="'.&mt('Reverse Association').'" '.
  739:               'name="Reverse Association" '.
  740:               'onclick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />'.
  741:         '</fieldset></div><br clear="all" />'
  742:     );
  743:     $r->print(
  744:         '<script type="text/javascript" language="Javascript">'."\n".
  745:         '// <![CDATA['."\n".
  746:         $javascript."\n".$javascript_validations."\n".
  747:         '// ]]>'."\n".
  748:         '</script>'
  749:     );
  750: }
  751: 
  752: ###############################################################
  753: ###############################################################
  754: sub javascript_validations {
  755:     my ($mode,$krbdefdom,$curr_authtype,$curr_authfield,$domain,
  756:         $context,$groupslist,$crstype)=@_;
  757:     my %param = (
  758:                   kerb_def_dom => $krbdefdom,
  759:                   curr_authtype => $curr_authtype,
  760:                 );
  761:     if ($mode eq 'upload') {
  762:         $param{'formname'} = 'studentform';
  763:     } elsif ($mode eq 'createcourse') {
  764:         $param{'formname'} = 'ccrs';
  765:     } elsif ($mode eq 'modifycourse') {
  766:         $param{'formname'} = 'cmod';
  767:         $param{'mode'} = 'modifycourse',
  768:         $param{'curr_autharg'} = $curr_authfield;
  769:     }
  770: 
  771:     my $showcredits;
  772:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  773:     if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'} || $domdefaults{'textbookcredits'}) {
  774:         $showcredits = 1;
  775:     }
  776: 
  777:     my ($setsection_call,$setsections_js);
  778:     my $finish = "  vf.submit();\n";
  779:     if ($mode eq 'upload') {
  780:         if (($context eq 'course') || ($context eq 'domain')) {
  781:             if ($context eq 'course') {
  782:                 if ($env{'request.course.sec'} eq '') {
  783:                     $setsection_call = 'setSections(document.'.$param{'formname'}.",'$crstype'".');';
  784:                     $setsections_js =
  785:                         &setsections_javascript($param{'formname'},$groupslist,
  786:                                                 $mode,'',$crstype,$showcredits);
  787:                 } else {
  788:                     $setsection_call = "'ok'";
  789:                 }
  790:             } elsif ($context eq 'domain') {
  791:                 $setsection_call = 'setCourse()';
  792:                 $setsections_js = &dc_setcourse_js($param{'formname'},$mode,
  793:                                                    $context,$showcredits,$domain);
  794:             }
  795:             $finish = "  var checkSec = $setsection_call\n".
  796:                       "  if (checkSec == 'ok') {\n".
  797:                       "      vf.submit();\n".
  798:                       "   }\n";
  799:         }
  800:     }
  801:     my $authheader = &Apache::loncommon::authform_header(%param);
  802: 
  803:     my %alert = &Apache::lonlocal::texthash
  804:         (username => 'You need to specify the username field.',
  805:          authen   => 'You must choose an authentication type.',
  806:          krb      => 'You need to specify the Kerberos domain.',
  807:          ipass    => 'You need to specify the initial password.',
  808:          name     => 'The optional name field was not specified.',
  809:          snum     => 'The optional student/employee ID field was not specified.',
  810:          section  => 'The optional section field was not specified.',
  811:          email    => 'The optional e-mail address field was not specified.',
  812:          role     => 'The optional role field was not specified.',
  813:          domain   => 'The optional domain field was not specified.',
  814:          continue => 'Continue adding users?',
  815:          );
  816:     if ($showcredits) {
  817:         $alert{'credits'} = &mt('The optional credits field was not specified');
  818:     }
  819:     if (($mode eq 'upload') && ($context eq 'domain')) {
  820:         $alert{'inststatus'} = &mt('The optional affiliation field was not specified'); 
  821:     }
  822:     &js_escape(\%alert);
  823:     my $function_name = <<"END";
  824: $setsections_js
  825: 
  826: function verify_message (vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits) {
  827: END
  828:     my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($domain);
  829:     my $auth_checks;
  830:     if ($mode eq 'createcourse') {
  831:         $auth_checks .= (<<END);
  832:     if (vf.autoadds[0].checked == true) {
  833:         if (current.radiovalue == null || current.radiovalue == 'nochange') {
  834:             alert('$alert{'authen'}');
  835:             return;
  836:         }
  837:     }
  838: END
  839:     } else {
  840:         $auth_checks .= (<<END);
  841:     var foundatype=0;
  842:     if (founduname==0) {
  843:         alert('$alert{'username'}');
  844:         return;
  845:     }
  846: 
  847: END
  848:         if ($authnum > 1) {
  849:             $auth_checks .= (<<END);
  850:     if (current.radiovalue == null || current.radiovalue == '' || current.radiovalue == 'nochange') {
  851:         // They did not check any of the login radiobuttons.
  852:         alert('$alert{'authen'}');
  853:         return;
  854:     }
  855: END
  856:         }
  857:     }
  858:     if ($mode eq 'createcourse') {
  859:         $auth_checks .= "
  860:     if ( (vf.autoadds[0].checked == true) &&
  861:          (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') ) {
  862: ";
  863:     } elsif ($mode eq 'modifycourse') {
  864:         $auth_checks .= "
  865:     if (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') {
  866: ";
  867:     }
  868:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
  869:         $auth_checks .= (<<END);
  870:         var alertmsg = '';
  871:         switch (current.radiovalue) {
  872:             case 'krb':
  873:                 alertmsg = '$alert{'krb'}';
  874:                 break;
  875:             default:
  876:                 alertmsg = '';
  877:         }
  878:         if (alertmsg != '') {
  879:             alert(alertmsg);
  880:             return;
  881:         }
  882:     }
  883: /* regexp here to check for non \d \. in credits */
  884: END
  885:     } else {
  886:         my ($numrules,$intargjs) =
  887:             &Apache::loncommon::passwd_validation_js('vf.elements[current.argfield].value',$domain);
  888:         $auth_checks .= (<<END);
  889:     foundatype=1;
  890:     if (current.argfield == null || current.argfield == '') {
  891:         // The login radiobutton checked does not have an associated textbox
  892:     } else if (vf.elements[current.argfield].value == '') {
  893:         var alertmsg = '';
  894:         switch (current.radiovalue) {
  895:             case 'krb':
  896:                 alertmsg = '$alert{'krb'}';
  897:                 break;
  898:             case 'int':
  899:                 alertmsg = '$alert{'ipass'}';
  900:                 break;
  901:             case 'fsys':
  902:                 alertmsg = '$alert{'ipass'}';
  903:                 break;
  904:             case 'loc':
  905:                 alertmsg = '';
  906:                 break;
  907:             case 'lti':
  908:             default:
  909:                 alertmsg = '';
  910:         }
  911:         if (alertmsg != '') {
  912:             alert(alertmsg);
  913:             return;
  914:         }
  915:     } else if (current.radiovalue == 'int') {
  916:         if ($numrules > 0) {
  917: $intargjs
  918:         }
  919:     }
  920: END
  921:     }
  922:     my $section_checks;
  923:     my $optional_checks = '';
  924:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
  925:         $optional_checks = (<<END);
  926:     vf.submit();
  927: }
  928: END
  929:     } else {
  930:         $section_checks = &section_check_js();
  931:         $optional_checks = (<<END);
  932:     var message='';
  933:     if (foundname==0) {
  934:         message='$alert{'name'}';
  935:     }
  936:     if (foundid==0) {
  937:         if (message!='') {
  938:             message+='\\n';
  939:         }
  940:         message+='$alert{'snum'}';
  941:     }
  942:     if (foundsec==0) {
  943:         if (message!='') {
  944:             message+='\\n';
  945:         }
  946:         message+='$alert{'section'}';
  947:     }
  948:     if (foundemail==0) {
  949:         if (message!='') {
  950:             message+='\\n';
  951:         }
  952:         message+='$alert{'email'}';
  953:     }
  954:     if (foundrole==0) {
  955:         if (message!='') {
  956:             message+='\\n';
  957:         }
  958:         message+='$alert{'role'}';
  959:     }
  960:     if (founddomain==0) {
  961:         if (message!='') {
  962:             message+='\\n';
  963:         }
  964:         message+='$alert{'domain'}';
  965:     }
  966: END
  967:         if ($showcredits) {
  968:             $optional_checks .= <<END;
  969:     if (foundcredits==0) {
  970:         if (message!='') {
  971:             message+='\\n';
  972:         }
  973:         message+='$alert{'credits'}';
  974:     }
  975: END
  976:         }
  977:         if (($mode eq 'upload') && ($context eq 'domain')) {
  978:             $optional_checks .= (<<END);
  979: 
  980:     if (foundinststatus==0) {
  981:         if (message!='') {
  982:             message+='\\n';
  983:         }
  984:         message+='$alert{'inststatus'}';
  985:     }
  986: END
  987:         }
  988:         $optional_checks .= (<<END);
  989: 
  990:     if (message!='') {
  991:         message+= '\\n$alert{'continue'}';
  992:         if (confirm(message)) {
  993:             vf.state.value='enrolling';
  994:             $finish
  995:         }
  996:     } else {
  997:         vf.state.value='enrolling';
  998:         $finish
  999:     }
 1000: }
 1001: END
 1002:     }
 1003:     my $result = $function_name.$auth_checks.$optional_checks."\n".
 1004:                  $section_checks.$authheader;
 1005:     return $result;
 1006: }
 1007: 
 1008: ###############################################################
 1009: ###############################################################
 1010: sub upload_manager_javascript_forward_associate {
 1011:     my ($can_assign) = @_;
 1012:     my ($auth_update,$numbuttons,$argreset);
 1013:     if (ref($can_assign) eq 'HASH') {
 1014:         if ($can_assign->{'krb4'} || $can_assign->{'krb5'}) {
 1015:             $argreset .= "      vf.krbarg.value='';\n";
 1016:             $numbuttons ++ ;
 1017:         }
 1018:         if ($can_assign->{'int'}) {
 1019:             $argreset .= "      vf.intarg.value='';\n";
 1020:             $numbuttons ++;
 1021:         }
 1022:         if ($can_assign->{'loc'}) {
 1023:             $argreset .= "      vf.locarg.value='';\n";
 1024:             $numbuttons ++;
 1025:         }
 1026:         if (!$can_assign->{'int'}) {
 1027:             my $warning = &mt('You may not specify an initial password for each user, as this is only available when new users use LON-CAPA internal authentication.')."\n".
 1028:                           &mt('Your current role does not have rights to create users with that authentication type.');
 1029:             &js_escape(\$warning);
 1030:             $auth_update = <<"END";
 1031:    // Currently the initial password field is only supported for internal auth
 1032:    // (see bug 6368).
 1033:    if (nw==9) {
 1034:        eval('vf.f'+tf+'.selectedIndex=0;')
 1035:        alert('$warning');
 1036:    }
 1037: END
 1038:         } elsif ($numbuttons > 1) {
 1039:             $auth_update = <<"END";
 1040:    // If we set the password, make the password form below correspond to
 1041:    // the new value.
 1042:    if (nw==9) {
 1043:       changed_radio('int',document.studentform);
 1044:       set_auth_radio_buttons('int',document.studentform);
 1045: $argreset
 1046:    }
 1047: 
 1048: END
 1049:         }
 1050:     }
 1051: 
 1052:     return(<<ENDPICK);
 1053: function verify(vf,sec_caller) {
 1054:     var founduname=0;
 1055:     var foundpwd=0;
 1056:     var foundname=0;
 1057:     var foundid=0;
 1058:     var foundsec=0;
 1059:     var foundemail=0;
 1060:     var foundrole=0;
 1061:     var founddomain=0;
 1062:     var foundinststatus=0;
 1063:     var foundcredits=0;
 1064:     var tw;
 1065:     for (i=0;i<=vf.nfields.value;i++) {
 1066:         tw=eval('vf.f'+i+'.selectedIndex');
 1067:         if (tw==1) { founduname=1; }
 1068:         if ((tw>=2) && (tw<=6)) { foundname=1; }
 1069:         if (tw==7) { foundid=1; }
 1070:         if (tw==8) { foundsec=1; }
 1071:         if (tw==9) { foundpwd=1; }
 1072:         if (tw==10) { foundemail=1; }
 1073:         if (tw==11) { foundrole=1; }
 1074:         if (tw==12) { founddomain=1; }
 1075:         if (tw==13) { foundinststatus=1; }
 1076:         if (tw==14) { foundcredits=1; }
 1077:     }
 1078:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits);
 1079: }
 1080: 
 1081: //
 1082: // vf = this.form
 1083: // tf = column number
 1084: //
 1085: // values of nw
 1086: //
 1087: // 0 = none
 1088: // 1 = username
 1089: // 2 = names (lastname, firstnames)
 1090: // 3 = fname (firstname)
 1091: // 4 = mname (middlename)
 1092: // 5 = lname (lastname)
 1093: // 6 = gen   (generation)
 1094: // 7 = id
 1095: // 8 = section
 1096: // 9 = ipwd  (password)
 1097: // 10 = email address
 1098: // 11 = role
 1099: // 12 = domain
 1100: // 13 = inststatus
 1101: // 14 = foundcredits 
 1102: 
 1103: function flip(vf,tf) {
 1104:    var nw=eval('vf.f'+tf+'.selectedIndex');
 1105:    var i;
 1106:    // make sure no other columns are labeled the same as this one
 1107:    for (i=0;i<=vf.nfields.value;i++) {
 1108:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
 1109:           eval('vf.f'+i+'.selectedIndex=0;')
 1110:       }
 1111:    }
 1112:    // If we set this to 'lastname, firstnames', clear out all the ones
 1113:    // set to 'fname','mname','lname','gen' (3,4,5,6) currently.
 1114:    if (nw==2) {
 1115:       for (i=0;i<=vf.nfields.value;i++) {
 1116:          if ((eval('vf.f'+i+'.selectedIndex')>=3) &&
 1117:              (eval('vf.f'+i+'.selectedIndex')<=6)) {
 1118:              eval('vf.f'+i+'.selectedIndex=0;')
 1119:          }
 1120:       }
 1121:    }
 1122:    // If we set this to one of 'fname','mname','lname','gen' (3,4,5,6),
 1123:    // clear out any that are set to 'lastname, firstnames' (2)
 1124:    if ((nw>=3) && (nw<=6)) {
 1125:       for (i=0;i<=vf.nfields.value;i++) {
 1126:          if (eval('vf.f'+i+'.selectedIndex')==2) {
 1127:              eval('vf.f'+i+'.selectedIndex=0;')
 1128:          }
 1129:       }
 1130:    }
 1131:    $auth_update
 1132: }
 1133: 
 1134: function clearpwd(vf) {
 1135:     var i;
 1136:     for (i=0;i<=vf.nfields.value;i++) {
 1137:         if (eval('vf.f'+i+'.selectedIndex')==9) {
 1138:             eval('vf.f'+i+'.selectedIndex=0;')
 1139:         }
 1140:     }
 1141: }
 1142: 
 1143: ENDPICK
 1144: }
 1145: 
 1146: ###############################################################
 1147: ###############################################################
 1148: sub upload_manager_javascript_reverse_associate {
 1149:     my ($can_assign) = @_;
 1150:     my ($auth_update,$numbuttons,$argreset);
 1151:     if (ref($can_assign) eq 'HASH') {
 1152:         if ($can_assign->{'krb4'} || $can_assign->{'krb5'}) {
 1153:             $argreset .= "      vf.krbarg.value='';\n";
 1154:             $numbuttons ++ ;
 1155:         }
 1156:         if ($can_assign->{'int'}) {
 1157:             $argreset .= "      vf.intarg.value='';\n";
 1158:             $numbuttons ++;
 1159:         }
 1160:         if ($can_assign->{'loc'}) {
 1161:             $argreset .= "      vf.locarg.value='';\n";
 1162:             $numbuttons ++;
 1163:         }
 1164:         if (!$can_assign->{'int'}) {
 1165:             my $warning = &mt('You may not specify an initial password, as this is only available when new users use LON-CAPA internal authentication.\n').
 1166:                           &mt('Your current role does not have rights to create users with that authentication type.');
 1167:             &js_escape(\$warning);
 1168:             $auth_update = <<"END";
 1169:    // Currently the initial password field is only supported for internal auth
 1170:    // (see bug 6368).
 1171:    if (tf==8 && nw!=0) {
 1172:        eval('vf.f'+tf+'.selectedIndex=0;')
 1173:        alert('$warning');
 1174:    }
 1175: END
 1176:         } elsif ($numbuttons > 1) {
 1177:             $auth_update = <<"END";
 1178:    // initial password specified, pick internal authentication
 1179:    if (tf==8 && nw!=0) {
 1180:       changed_radio('int',document.studentform);
 1181:       set_auth_radio_buttons('int',document.studentform);
 1182: $argreset
 1183:    }
 1184: 
 1185: END
 1186:         }
 1187:     }
 1188: 
 1189:     return(<<ENDPICK);
 1190: function verify(vf,sec_caller) {
 1191:     var founduname=0;
 1192:     var foundpwd=0;
 1193:     var foundname=0;
 1194:     var foundid=0;
 1195:     var foundsec=0;
 1196:     var foundemail=0;
 1197:     var foundrole=0;
 1198:     var founddomain=0;
 1199:     var foundinststatus=0;
 1200:     var foundcredits=0;
 1201:     var tw;
 1202:     for (i=0;i<=vf.nfields.value;i++) {
 1203:         tw=eval('vf.f'+i+'.selectedIndex');
 1204:         if (i==0 && tw!=0) { founduname=1; }
 1205:         if (((i>=1) && (i<=5)) && tw!=0 ) { foundname=1; }
 1206:         if (i==6 && tw!=0) { foundid=1; }
 1207:         if (i==7 && tw!=0) { foundsec=1; }
 1208:         if (i==8 && tw!=0) { foundpwd=1; }
 1209:         if (i==9 && tw!=0) { foundemail=1; }
 1210:         if (i==10 && tw!=0) { foundrole=1; }
 1211:         if (i==11 && tw!=0) { founddomain=1; }
 1212:         if (i==12 && tw!=0) { foundinstatus=1; }
 1213:         if (i==13 && tw!=0) { foundcredits=1; }
 1214:     }
 1215:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits);
 1216: }
 1217: 
 1218: function flip(vf,tf) {
 1219:    var nw=eval('vf.f'+tf+'.selectedIndex');
 1220:    var i;
 1221:    // picked the all one name field, reset the other name ones to blank
 1222:    if (tf==1 && nw!=0) {
 1223:       for (i=2;i<=5;i++) {
 1224:          eval('vf.f'+i+'.selectedIndex=0;')
 1225:       }
 1226:    }
 1227:    //picked one of the piecewise name fields, reset the all in
 1228:    //one field to blank
 1229:    if ((tf>=2) && (tf<=5) && (nw!=0)) {
 1230:       eval('vf.f1.selectedIndex=0;')
 1231:    }
 1232:    $auth_update
 1233: }
 1234: 
 1235: function clearpwd(vf) {
 1236:     var i;
 1237:     if (eval('vf.f8.selectedIndex')!=0) {
 1238:         eval('vf.f8.selectedIndex=0;')
 1239:     }
 1240: }
 1241: ENDPICK
 1242: }
 1243: 
 1244: ###############################################################
 1245: ###############################################################
 1246: sub print_upload_manager_footer {
 1247:     my ($r,$i,$keyfields,$defdom,$today,$halfyear,$context,$permission,$crstype,
 1248:         $showcredits) = @_;
 1249:     my $form = 'document.studentform';
 1250:     my $formname = 'studentform';
 1251:     my ($krbdef,$krbdefdom) =
 1252:         &Apache::loncommon::get_kerberos_defaults($defdom);
 1253:     my %param = ( formname => $form,
 1254:                   kerb_def_dom => $krbdefdom,
 1255:                   kerb_def_auth => $krbdef
 1256:                   );
 1257:     if (exists($env{'form.ipwd_choice'}) &&
 1258:         defined($env{'form.ipwd_choice'}) &&
 1259:         $env{'form.ipwd_choice'} ne '') {
 1260:         $param{'curr_authtype'} = 'int';
 1261:     }
 1262:     my $krbform = &Apache::loncommon::authform_kerberos(%param);
 1263:     my $intform = &Apache::loncommon::authform_internal(%param);
 1264:     my $locform = &Apache::loncommon::authform_local(%param);
 1265:     my $ltiform = &Apache::loncommon::authform_lti(%param);
 1266:     my $date_table = &date_setting_table(undef,undef,$context,undef,
 1267:                                          $formname,$permission,$crstype);
 1268: 
 1269:     my $Str = "\n".'<div class="LC_left_float">';
 1270:     $Str .= &hidden_input('nfields',$i);
 1271:     $Str .= &hidden_input('keyfields',$keyfields);
 1272: 
 1273:     $Str .= '<h3>'.&mt('Options').'</h3>'
 1274:            .&Apache::lonhtmlcommon::start_pick_box();
 1275: 
 1276:     $Str .= &Apache::lonhtmlcommon::row_title(&mt('Login Type'));
 1277:     if ($context eq 'domain') {
 1278:         $Str .= '<p>'
 1279:                .&mt('Change authentication for existing users in domain "[_1]" to these settings?'
 1280:                    ,$defdom)
 1281:                .'&nbsp;<span class="LC_nobreak"><label>'
 1282:                .'<input type="radio" name="changeauth" value="No" checked="checked" />'
 1283:                .&mt('No').'</label>'
 1284:                .'&nbsp;&nbsp;<label>'
 1285:                .'<input type="radio" name="changeauth" value="Yes" />'
 1286:                .&mt('Yes').'</label>'
 1287:                .'</span></p>'; 
 1288:     } else {
 1289:         $Str .= '<p class="LC_info">'."\n".
 1290:             &mt('This will not take effect if the user already exists.').
 1291:             &Apache::loncommon::help_open_topic('Auth_Options').
 1292:             "</p>\n";
 1293:     }
 1294:     $Str .= &set_login($defdom,$krbform,$intform,$locform,$ltiform);
 1295: 
 1296:     my ($home_server_pick,$numlib) =
 1297:         &Apache::loncommon::home_server_form_item($defdom,'lcserver',
 1298:                                                   'default','hide');
 1299:     if ($numlib > 1) {
 1300:         $Str .= &Apache::lonhtmlcommon::row_closure()
 1301:                .&Apache::lonhtmlcommon::row_title(
 1302:                     &mt('LON-CAPA Home Server for New Users'))
 1303:                .&mt('LON-CAPA domain: [_1] with home server:','"'.$defdom.'"')
 1304:                .$home_server_pick
 1305:                .&Apache::lonhtmlcommon::row_closure();
 1306:     } else {
 1307:         $Str .= $home_server_pick.
 1308:                 &Apache::lonhtmlcommon::row_closure();
 1309:     }
 1310: 
 1311:     my ($trusted,$untrusted);
 1312:     if ($context eq 'course') {
 1313:         ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
 1314:     } elsif ($context eq 'author') {
 1315:         ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
 1316:     }
 1317:     $Str .= &Apache::lonhtmlcommon::row_title(&mt('Default domain'))
 1318:            .&Apache::loncommon::select_dom_form($defdom,'defaultdomain',undef,1,undef,$trusted,$untrusted)
 1319:            .&Apache::lonhtmlcommon::row_closure();
 1320: 
 1321:     $Str .= &Apache::lonhtmlcommon::row_title(&mt('Starting and Ending Dates'))
 1322:            ."<p>\n".$date_table."</p>\n"
 1323:            .&Apache::lonhtmlcommon::row_closure();
 1324: 
 1325:     if ($context eq 'domain') {
 1326:         $Str .= &Apache::lonhtmlcommon::row_title(
 1327:                     &mt('Settings for assigning roles'))
 1328:                .&mt('Pick the action to take on roles for these users:').'<br />'
 1329:                .'<span class="LC_nobreak"><label>'
 1330:                .'<input type="radio" name="roleaction" value="norole" checked="checked" />'
 1331:                .'&nbsp;'.&mt('No role changes').'</label>'
 1332:                .'&nbsp;&nbsp;&nbsp;<label>'
 1333:                .'<input type="radio" name="roleaction" value="domain" />'
 1334:                .'&nbsp;'.&mt('Add a domain role').'</label>'
 1335:                .'&nbsp;&nbsp;&nbsp;<label>'
 1336:                .'<input type="radio" name="roleaction" value="course" />'
 1337:                .'&nbsp;'.&mt('Add a course/community role').'</label>'
 1338:                .'</span>';
 1339:     } elsif ($context eq 'author') {
 1340:         $Str .= &Apache::lonhtmlcommon::row_title(
 1341:                     &mt('Default role'))
 1342:                .&mt('Choose the role to assign to users without a value specified in the uploaded file.')
 1343:     } elsif ($context eq 'course') {
 1344:         if ($showcredits) {
 1345:             $Str .= &Apache::lonhtmlcommon::row_title(
 1346:                     &mt('Default role, section and credits'))
 1347:                    .&mt('Choose the role and/or section(s) and/or credits to assign to users without values specified in the uploaded file.');
 1348:         } else { 
 1349:             $Str .= &Apache::lonhtmlcommon::row_title(
 1350:                     &mt('Default role and section'))
 1351:                    .&mt('Choose the role and/or section(s) to assign to users without values specified in the uploaded file.');
 1352:         }
 1353:     } else {
 1354:         $Str .= &Apache::lonhtmlcommon::row_title(
 1355:                     &mt('Default role and/or section(s)'))
 1356:                .&mt('Role and/or section(s) for users without values specified in the uploaded file.');
 1357:     }
 1358:     if (($context eq 'domain') || ($context eq 'author')) {
 1359:         $Str .= '<br />';
 1360:         my ($options,$cb_script,$coursepick) = 
 1361:             &default_role_selector($context,1,'',$showcredits);
 1362:         if ($context eq 'domain') {
 1363:             $Str .= '<p>'
 1364:                    .'<b>'.&mt('Domain Level').'</b><br />'
 1365:                    .$options
 1366:                    .'</p><p>'
 1367:                    .'<b>'.&mt('Course Level').'</b>'
 1368:                    .'</p>'
 1369:                    .$cb_script.$coursepick
 1370:                    .&Apache::lonhtmlcommon::row_closure();
 1371:         } elsif ($context eq 'author') {
 1372:             $Str .= $options
 1373:                    .&Apache::lonhtmlcommon::row_closure(1); # last row in pick_box
 1374:         }
 1375:     } else {
 1376:         my ($cnum,$cdom) = &get_course_identity();
 1377:         my $rowtitle = &mt('section');
 1378:         my $defaultcredits;
 1379:         if ($showcredits) {
 1380:             $defaultcredits = &get_defaultcredits();
 1381:         }
 1382:         my $secbox = &section_picker($cdom,$cnum,'Any',$rowtitle,$permission,
 1383:                                      $context,'upload',$crstype,$showcredits,
 1384:                                      $defaultcredits);
 1385:         $Str .= $secbox
 1386:                .&Apache::lonhtmlcommon::row_closure();
 1387:         my %lt;
 1388:         if ($crstype eq 'Community') {
 1389:             %lt = &Apache::lonlocal::texthash (
 1390:                     disp => 'Display members with current/future access who are not in the uploaded file',
 1391:                     stus => 'Members selected from this list can be dropped.'
 1392:             );
 1393:         } else {
 1394:             %lt = &Apache::lonlocal::texthash (
 1395:                     disp => 'Display students with current/future access who are not in the uploaded file',
 1396:                     stus => 'Students selected from this list can be dropped.'
 1397:             );
 1398:         }
 1399:         $Str .= &Apache::lonhtmlcommon::row_title(&mt('Full Update'))
 1400:                .'<label><input type="checkbox" name="fullup" value="yes" />'
 1401:                .' '.$lt{'disp'}
 1402:                .'</label><br />'
 1403:                .$lt{'stus'}
 1404:                .&Apache::lonhtmlcommon::row_closure();
 1405:     }
 1406:     if ($context eq 'course' || $context eq 'domain') {
 1407:         $Str .= &Apache::lonhtmlcommon::row_title(&mt('Student/Employee ID'))
 1408:                .&forceid_change($context)
 1409:                .&Apache::lonhtmlcommon::row_closure(1); # last row in pick_box
 1410:     }
 1411: 
 1412:     $Str .= &Apache::lonhtmlcommon::end_pick_box();
 1413:     $Str .= '</div>';
 1414: 
 1415:     # Footer
 1416:     $Str .= '<div class="LC_clear_float_footer">'
 1417:            .'<hr />';
 1418:     if ($context eq 'course') {
 1419:         $Str .= '<p class="LC_info">'
 1420:                .&mt('Note: This operation may be time consuming when adding several users.')
 1421:                .'</p>';
 1422:     }
 1423:     $Str .= '<p><input type="button"'
 1424:            .' onclick="javascript:verify(this.form,this.form.csec)"'
 1425:            .' value="'.&mt('Update Users').'" />'
 1426:            .'</p>'."\n"
 1427:            .'</div>';
 1428:     $r->print($Str);
 1429:     return;
 1430: }
 1431: 
 1432: sub get_defaultcredits {
 1433:     my ($cdom,$cnum) = @_;
 1434:      
 1435:     if ($cdom eq '' || $cnum eq '') {
 1436:         return unless ($env{'request.course.id'});
 1437:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1438:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1439:     }
 1440:     return unless(($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)); 
 1441:     my ($defaultcredits,$domdefcredits);
 1442:     my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 1443:     if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'} || $domdefaults{'textbookcredits'}) {
 1444:         my $instcode = $env{'course.'.$cdom.'_'.$cnum.'.internal.coursecode'};
 1445:         if ($instcode) {
 1446:             $domdefcredits = $domdefaults{'officialcredits'};
 1447:         } elsif ($env{'course.'.$cdom.'_'.$cnum.'.internal.textbook'}) {
 1448:             $domdefcredits = $domdefaults{'textbookcredits'};
 1449:         } else {
 1450:             $domdefcredits = $domdefaults{'unofficialcredits'};
 1451:         }
 1452:     } else {
 1453:         return;
 1454:     }
 1455: 
 1456:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
 1457:         $defaultcredits = $env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'};
 1458:     } elsif (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'})) {
 1459:         $defaultcredits = $env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'};
 1460:     } else {
 1461:         my %crsinfo =
 1462:             &Apache::lonnet::coursedescription("$cdom/$cnum",{'one_time' => 1});
 1463:         $defaultcredits = $crsinfo{'internal.defaultcredits'};
 1464:     }
 1465:     if ($defaultcredits eq '') {
 1466:         $defaultcredits = $domdefcredits;
 1467:     }
 1468:     return $defaultcredits;
 1469: }
 1470: 
 1471: sub forceid_change {
 1472:     my ($context) = @_;
 1473:     my $output = 
 1474:         '<label><input type="checkbox" name="forceid" value="yes" />'
 1475:        .&mt('Force change of existing ID')
 1476:        .'</label>'.&Apache::loncommon::help_open_topic('ForceIDChange')."\n";
 1477:     if ($context eq 'domain') {
 1478:         $output .= 
 1479:             '<br />'
 1480:            .'<label><input type="checkbox" name="recurseid" value="yes" />'
 1481:            .&mt("Update ID in user's course(s).").'</label>'."\n";
 1482:     }
 1483:     return $output;
 1484: }
 1485: 
 1486: ###############################################################
 1487: ###############################################################
 1488: sub print_upload_manager_form {
 1489:     my ($r,$context,$permission,$crstype,$showcredits) = @_;
 1490:     my $firstLine;
 1491:     my $datatoken;
 1492:     if (!$env{'form.datatoken'}) {
 1493:         $datatoken=&Apache::loncommon::upfile_store($r);
 1494:     } else {
 1495:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 1496:         if ($datatoken ne '') {
 1497:             &Apache::loncommon::load_tmp_file($r,$datatoken);
 1498:         }
 1499:     }
 1500:     if ($datatoken eq '') {
 1501:         $r->print('<p class="LC_error">'.&mt('Error').': '.
 1502:                   &mt('Invalid datatoken').'</p>');
 1503:         return 'missingdata';
 1504:     }
 1505:     my @records=&Apache::loncommon::upfile_record_sep();
 1506:     if($env{'form.noFirstLine'}){
 1507:         $firstLine=shift(@records);
 1508:     }
 1509:     my $total=$#records;
 1510:     my $distotal=$total+1;
 1511:     my $today=time;
 1512:     my $halfyear=$today+15552000;
 1513:     #
 1514:     # Restore memorized settings
 1515:     my $col_setting_names =  { 'username_choice' => 'scalar', # column settings
 1516:                                'names_choice' => 'scalar',
 1517:                                'fname_choice' => 'scalar',
 1518:                                'mname_choice' => 'scalar',
 1519:                                'lname_choice' => 'scalar',
 1520:                                'gen_choice' => 'scalar',
 1521:                                'id_choice' => 'scalar',
 1522:                                'sec_choice' => 'scalar',
 1523:                                'ipwd_choice' => 'scalar',
 1524:                                'email_choice' => 'scalar',
 1525:                                'role_choice' => 'scalar',
 1526:                                'domain_choice' => 'scalar',
 1527:                                'inststatus_choice' => 'scalar',
 1528:                              };
 1529:     if ($showcredits) {
 1530:         $col_setting_names->{'credits_choice'} = 'scalar';
 1531:     }
 1532:     if ($context eq 'course') {
 1533:         &Apache::loncommon::restore_course_settings('enrollment_upload',
 1534:                                                     $col_setting_names);
 1535:     } else {
 1536:         &Apache::loncommon::restore_settings($context,'user_upload',
 1537:                                              $col_setting_names);
 1538:     }
 1539:     my $defdom = $env{'request.role.domain'};
 1540:     #
 1541:     # Determine kerberos parameters as appropriate
 1542:     my ($krbdef,$krbdefdom) =
 1543:         &Apache::loncommon::get_kerberos_defaults($defdom);
 1544:     #
 1545:     my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($defdom);
 1546:     &print_upload_manager_header($r,$datatoken,$distotal,$krbdefdom,$context,
 1547:                                  $permission,$crstype,\%can_assign);
 1548:     my $i;
 1549:     my $keyfields;
 1550:     if ($total>=0) {
 1551:         my @field=
 1552:             (['username',&mt('Username'),     $env{'form.username_choice'}],
 1553:              ['names',&mt('Last Name, First Names'),$env{'form.names_choice'}],
 1554:              ['fname',&mt('First Name'),      $env{'form.fname_choice'}],
 1555:              ['mname',&mt('Middle Names/Initials'),$env{'form.mname_choice'}],
 1556:              ['lname',&mt('Last Name'),       $env{'form.lname_choice'}],
 1557:              ['gen',  &mt('Generation'),      $env{'form.gen_choice'}],
 1558:              ['id',   &mt('Student/Employee ID'),$env{'form.id_choice'}],
 1559:              ['sec',  &mt('Section'),          $env{'form.sec_choice'}],
 1560:              ['ipwd', &mt('Initial Password'),$env{'form.ipwd_choice'}],
 1561:              ['email',&mt('E-mail Address'),   $env{'form.email_choice'}],
 1562:              ['role',&mt('Role'),             $env{'form.role_choice'}],
 1563:              ['domain',&mt('Domain'),         $env{'form.domain_choice'}],
 1564:              ['inststatus',&mt('Affiliation'), $env{'form.inststatus_choice'}]);
 1565:         if ($showcredits) {     
 1566:             push(@field,
 1567:                  ['credits',&mt('Student Credits'), $env{'form.credits_choice'}]);
 1568:         }
 1569:         if ($env{'form.upfile_associate'} eq 'reverse') {
 1570:             &Apache::loncommon::csv_print_samples($r,\@records);
 1571:             $i=&Apache::loncommon::csv_print_select_table($r,\@records,
 1572:                                                           \@field);
 1573:             foreach (@field) {
 1574:                 $keyfields.=$_->[0].',';
 1575:             }
 1576:             chop($keyfields);
 1577:         } else {
 1578:             unshift(@field,['none','']);
 1579:             $i=&Apache::loncommon::csv_samples_select_table($r,\@records,
 1580:                                                             \@field);
 1581:             my %sone=&Apache::loncommon::record_sep($records[0]);
 1582:             $keyfields=join(',',sort(keys(%sone)));
 1583:         }
 1584:     }
 1585:     &print_upload_manager_footer($r,$i,$keyfields,$defdom,$today,$halfyear,
 1586:                                  $context,$permission,$crstype,$showcredits);
 1587:     return 'ok';
 1588: }
 1589: 
 1590: sub setup_date_selectors {
 1591:     my ($starttime,$endtime,$mode,$nolink,$formname) = @_;
 1592:     if ($formname eq '') {
 1593:         $formname = 'studentform';
 1594:     }
 1595:     if (! defined($starttime)) {
 1596:         $starttime = time;
 1597:         unless ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
 1598:             if (exists($env{'course.'.$env{'request.course.id'}.
 1599:                             '.default_enrollment_start_date'})) {
 1600:                 $starttime = $env{'course.'.$env{'request.course.id'}.
 1601:                                   '.default_enrollment_start_date'};
 1602:             }
 1603:         }
 1604:     }
 1605:     if (! defined($endtime)) {
 1606:         $endtime = time+(6*30*24*60*60); # 6 months from now, approx
 1607:         unless ($mode eq 'createcourse') {
 1608:             if (exists($env{'course.'.$env{'request.course.id'}.
 1609:                             '.default_enrollment_end_date'})) {
 1610:                 $endtime = $env{'course.'.$env{'request.course.id'}.
 1611:                                 '.default_enrollment_end_date'};
 1612:             }
 1613:         }
 1614:     }
 1615: 
 1616:     my $startdateform = 
 1617:         &Apache::lonhtmlcommon::date_setter($formname,'startdate',$starttime,
 1618:             undef,undef,undef,undef,undef,undef,undef,$nolink);
 1619: 
 1620:     my $enddateform = 
 1621:         &Apache::lonhtmlcommon::date_setter($formname,'enddate',$endtime,
 1622:             undef,undef,undef,undef,undef,undef,undef,$nolink);
 1623: 
 1624:     if ($mode eq 'create_enrolldates') {
 1625:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
 1626:                                                             'startenroll',
 1627:                                                             $starttime);
 1628:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
 1629:                                                           'endenroll',
 1630:                                                           $endtime);
 1631:     }
 1632:     if ($mode eq 'create_defaultdates') {
 1633:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
 1634:                                                             'startaccess',
 1635:                                                             $starttime);
 1636:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
 1637:                                                           'endaccess',
 1638:                                                           $endtime);
 1639:     }
 1640:     return ($startdateform,$enddateform);
 1641: }
 1642: 
 1643: 
 1644: sub get_dates_from_form {
 1645:     my ($startname,$endname) = @_;
 1646:     if ($startname eq '') {
 1647:         $startname = 'startdate';
 1648:     }
 1649:     if ($endname eq '') {
 1650:         $endname = 'enddate';
 1651:     }
 1652:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form($startname);
 1653:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form($endname);
 1654:     if ($env{'form.no_end_date'}) {
 1655:         $enddate = 0;
 1656:     }
 1657:     return ($startdate,$enddate);
 1658: }
 1659: 
 1660: sub date_setting_table {
 1661:     my ($starttime,$endtime,$mode,$bulkaction,$formname,$permission,$crstype) = @_;
 1662:     my $nolink;
 1663:     if ($bulkaction) {
 1664:         $nolink = 1;
 1665:     }
 1666:     my ($startform,$endform) = 
 1667:         &setup_date_selectors($starttime,$endtime,$mode,$nolink,$formname);
 1668:     my $dateDefault;
 1669:     if ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
 1670:         $dateDefault = '&nbsp;';
 1671:     } elsif ($mode ne 'author' && $mode ne 'domain') {
 1672:         if (($bulkaction eq 'reenable') || 
 1673:             ($bulkaction eq 'activate') || 
 1674:             ($bulkaction eq 'chgdates') ||
 1675:             ($env{'form.action'} eq 'upload')) {
 1676:             if ($env{'request.course.sec'} eq '') {
 1677:                 $dateDefault = '<span class="LC_nobreak">'.
 1678:                     '<label><input type="checkbox" name="makedatesdefault" value="1" /> ';
 1679:                 if ($crstype eq 'Community') {
 1680:                     $dateDefault .= &mt("make these dates the default access dates for future community enrollment");
 1681:                 } else {
 1682:                     $dateDefault .= &mt("make these dates the default access dates for future course enrollment");
 1683:                 }
 1684:                 $dateDefault .= '</label></span>';
 1685:             }
 1686:         }
 1687:     }
 1688:     my $perpetual = '<span class="LC_nobreak"><label><input type="checkbox" name="no_end_date"';
 1689:     if (defined($endtime) && $endtime == 0) {
 1690:         $perpetual .= ' checked="checked"';
 1691:     }
 1692:     $perpetual.= ' /> '.&mt('no ending date').'</label></span>';
 1693:     if ($mode eq 'create_enrolldates') {
 1694:         $perpetual = '&nbsp;';
 1695:     }
 1696:     my $result = &Apache::lonhtmlcommon::start_pick_box()."\n";
 1697:     $result .= &Apache::lonhtmlcommon::row_title(&mt('Starting Date'),
 1698:                                                      'LC_oddrow_value')."\n".
 1699:                $startform."\n".
 1700:                &Apache::lonhtmlcommon::row_closure(1).
 1701:                &Apache::lonhtmlcommon::row_title(&mt('Ending Date'), 
 1702:                                                      'LC_oddrow_value')."\n".
 1703:                $endform.'&nbsp;'.$perpetual.
 1704:                &Apache::lonhtmlcommon::row_closure(1).
 1705:                &Apache::lonhtmlcommon::end_pick_box();
 1706:     if ($dateDefault) {
 1707:         $result .=  $dateDefault.'<br />'."\n";
 1708:     }
 1709:     return $result;
 1710: }
 1711: 
 1712: sub make_dates_default {
 1713:     my ($startdate,$enddate,$context,$crstype) = @_;
 1714:     my $result = '';
 1715:     if ($context eq 'course') {
 1716:         my ($cnum,$cdom) = &get_course_identity();
 1717:         my $put_result = &Apache::lonnet::put('environment',
 1718:                 {'default_enrollment_start_date'=>$startdate,
 1719:                  'default_enrollment_end_date'  =>$enddate},$cdom,$cnum);
 1720:         if ($put_result eq 'ok') {
 1721:             if ($crstype eq 'Community') {
 1722:                 $result .= &mt('Set default start and end access dates for community.');
 1723:             } else {
 1724:                 $result .= &mt('Set default start and end access dates for course.');
 1725:             }
 1726:             $result .= '<br />'."\n";
 1727:             #
 1728:             # Refresh the course environment
 1729:             &Apache::lonnet::coursedescription($env{'request.course.id'},
 1730:                                                {'freshen_cache' => 1});
 1731:         } else {
 1732:             if ($crstype eq 'Community') {
 1733:                 $result .= &mt('Unable to set default access dates for community');
 1734:             } else {
 1735:                 $result .= &mt('Unable to set default access dates for course');
 1736:             }
 1737:             $result .= ':'.$put_result.'<br />';
 1738:         }
 1739:     }
 1740:     return $result;
 1741: }
 1742: 
 1743: sub default_role_selector {
 1744:     my ($context,$checkpriv,$crstype,$showcredits) = @_;
 1745:     my %customroles;
 1746:     my ($options,$coursepick,$cb_jscript);
 1747:     if ($context ne 'author') {
 1748:         %customroles = &my_custom_roles($crstype);
 1749:     }
 1750: 
 1751:     my %lt=&Apache::lonlocal::texthash(
 1752:                     'rol'  => "Role",
 1753:                     'grs'  => "Section",
 1754:                     'exs'  => "Existing sections",
 1755:                     'new'  => "New section",
 1756:                     'crd'  => "Credits",
 1757:                   );
 1758:     $options = '<select name="defaultrole">'."\n".
 1759:                ' <option value="">'.&mt('Please select').'</option>'."\n"; 
 1760:     if ($context eq 'course') {
 1761:         $options .= &default_course_roles($context,$checkpriv,$crstype,%customroles);
 1762:     } elsif ($context eq 'author') {
 1763:         my @roles = &construction_space_roles($checkpriv);
 1764:         foreach my $role (@roles) {
 1765:            my $plrole=&Apache::lonnet::plaintext($role);
 1766:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>'."\n";
 1767:         }
 1768:     } elsif ($context eq 'domain') {
 1769:         my @roles = &domain_roles($checkpriv);
 1770:         foreach my $role (@roles) {
 1771:            my $plrole=&Apache::lonnet::plaintext($role);
 1772:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>';
 1773:         }
 1774:         my $courseform = &Apache::loncommon::selectcourse_link
 1775:             ('studentform','dccourse','dcdomain','coursedesc',"$env{'request.role.domain'}",undef,'Course/Community');
 1776:         my ($credit_elem,$creditsinput);
 1777:         if ($showcredits) {
 1778:             $credit_elem = 'credits';
 1779:             $creditsinput = '<td><input type="text" name="credits" value="" /></td>';
 1780:         }
 1781:         $cb_jscript = 
 1782:             &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'},'currsec','studentform','courserole','Course/Community',$credit_elem);
 1783:         $coursepick = &Apache::loncommon::start_data_table().
 1784:                       &Apache::loncommon::start_data_table_header_row().
 1785:                       '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th>'.
 1786:                       '<th>'.$lt{'grs'}.'</th>'.
 1787:                       '<th>'.$lt{'crd'}.'</th>'.
 1788:                       &Apache::loncommon::end_data_table_header_row().
 1789:                       &Apache::loncommon::start_data_table_row()."\n".
 1790:                       '<td><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'studentform','dccourse','dcdomain','coursedesc','','','','crstype'".')" /></td>'."\n".
 1791:                       '<td><select name="courserole">'."\n".
 1792:                       &default_course_roles($context,$checkpriv,'Course',%customroles)."\n".
 1793:                       '</select></td><td>'.
 1794:                       '<table class="LC_createuser">'.
 1795:                       '<tr class="LC_section_row"><td valign="top">'.
 1796:                       $lt{'exs'}.'<br /><select name="currsec">'.
 1797:                       ' <option value="">&lt;--'.&mt('Pick course first').
 1798:                       '</select></td>'.
 1799:                       '<td>&nbsp;&nbsp;</td>'.
 1800:                       '<td valign="top">'.$lt{'new'}.'<br />'.
 1801:                       '<input type="text" name="newsec" value="" size="5" />'.
 1802:                       '<input type="hidden" name="groups" value="" />'.
 1803:                       '<input type="hidden" name="sections" value="" />'.
 1804:                       '<input type="hidden" name="origdom" value="'.
 1805:                       $env{'request.role.domain'}.'" />'.
 1806:                       '<input type="hidden" name="dccourse" value="" />'.
 1807:                       '<input type="hidden" name="dcdomain" value="" />'.
 1808:                       '<input type="hidden" name="crstype" value="" />'.
 1809:                       '</td></tr></table></td>'.$creditsinput.
 1810:                       &Apache::loncommon::end_data_table_row().
 1811:                       &Apache::loncommon::end_data_table()."\n";
 1812:     }
 1813:     $options .= '</select>';
 1814:     return ($options,$cb_jscript,$coursepick);
 1815: }
 1816: 
 1817: sub default_course_roles {
 1818:     my ($context,$checkpriv,$crstype,%customroles) = @_;
 1819:     my $output;
 1820:     my $custom = 1;
 1821:     my @roles = &course_roles($context,$checkpriv,$custom,lc($crstype));
 1822:     foreach my $role (@roles) {
 1823:         if ($role ne 'cr') {
 1824:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 1825:             $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
 1826:         }
 1827:     }
 1828:     if (keys(%customroles) > 0) {
 1829:         if (grep(/^cr$/,@roles)) {
 1830:             foreach my $cust (sort(keys(%customroles))) {
 1831:                 my $custrole='cr_'.$env{'user.domain'}.
 1832:                              '_'.$env{'user.name'}.'_'.$cust;
 1833:                 $output .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 1834:             }
 1835:         }
 1836:     }
 1837:     return $output;
 1838: }
 1839: 
 1840: sub construction_space_roles {
 1841:     my ($checkpriv) = @_;
 1842:     my @allroles = &roles_by_context('author');
 1843:     my @roles;
 1844:     if ($checkpriv) {
 1845:         foreach my $role (@allroles) {
 1846:             if (&Apache::lonnet::allowed('c'.$role,$env{'user.domain'}.'/'.$env{'user.name'})) { 
 1847:                 push(@roles,$role); 
 1848:             }
 1849:         }
 1850:         return @roles;
 1851:     } else {
 1852:         return @allroles;
 1853:     }
 1854: }
 1855: 
 1856: sub domain_roles {
 1857:     my ($checkpriv) = @_;
 1858:     my @allroles = &roles_by_context('domain');
 1859:     my @roles;
 1860:     if ($checkpriv) {
 1861:         foreach my $role (@allroles) {
 1862:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
 1863:                 push(@roles,$role);
 1864:             }
 1865:         }
 1866:         return @roles;
 1867:     } else {
 1868:         return @allroles;
 1869:     }
 1870: }
 1871: 
 1872: sub course_roles {
 1873:     my ($context,$checkpriv,$custom,$roletype) = @_;
 1874:     my $crstype;
 1875:     if ($roletype eq 'community') {
 1876:         $crstype = 'Community' ;
 1877:     } else {
 1878:         $crstype = 'Course';
 1879:     }
 1880:     my @allroles = &roles_by_context('course',$custom,$crstype);
 1881:     my @roles;
 1882:     if ($context eq 'domain') {
 1883:         @roles = @allroles;
 1884:     } elsif ($context eq 'course') {
 1885:         if ($env{'request.course.id'}) {
 1886:             if ($checkpriv) { 
 1887:                 foreach my $role (@allroles) {
 1888:                     if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
 1889:                         push(@roles,$role);
 1890:                     } else {
 1891:                         if ((($role ne 'cc') && ($role ne 'co')) && ($env{'request.course.sec'} ne '')) {
 1892:                             if (&Apache::lonnet::allowed('c'.$role,
 1893:                                              $env{'request.course.id'}.'/'.
 1894:                                              $env{'request.course.sec'})) {
 1895:                                 push(@roles,$role);
 1896:                             }
 1897:                         }
 1898:                     }
 1899:                 }
 1900:             } else {
 1901:                 @roles = @allroles;
 1902:             }
 1903:         }
 1904:     }
 1905:     return @roles;
 1906: }
 1907: 
 1908: sub curr_role_permissions {
 1909:     my ($context,$setting,$checkpriv,$type) = @_; 
 1910:     my $custom = 1;
 1911:     my @roles;
 1912:     if ($context eq 'author') {
 1913:         @roles = &construction_space_roles($checkpriv);
 1914:     } elsif ($context eq 'domain') {
 1915:         if ($setting eq 'course') {
 1916:             @roles = &course_roles($context,$checkpriv,$custom,$type); 
 1917:         } else {
 1918:             @roles = &domain_roles($checkpriv);
 1919:         }
 1920:     } elsif ($context eq 'course') {
 1921:         @roles = &course_roles($context,$checkpriv,$custom,$type);
 1922:     }
 1923:     return @roles;
 1924: }
 1925: 
 1926: # ======================================================= Existing Custom Roles
 1927: 
 1928: sub my_custom_roles {
 1929:     my ($crstype,$udom,$uname) = @_;
 1930:     my %returnhash=();
 1931:     my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 1932:     my %rolehash=&Apache::lonnet::dump('roles',$udom,$uname);
 1933:     foreach my $key (keys(%rolehash)) {
 1934:         if ($key=~/^rolesdef\_(\w+)$/) {
 1935:             my $role = $1;
 1936:             if ($crstype eq 'Community') {
 1937:                 next if ($rolehash{$key} =~ /bre\&S/); 
 1938:             }
 1939:             $returnhash{$role}=$role;
 1940:         }
 1941:     }
 1942:     return %returnhash;
 1943: }
 1944: 
 1945: sub print_userlist {
 1946:     my ($r,$mode,$permission,$context,$formname,$totcodes,$codetitles,
 1947:         $idlist,$idlist_titles,$showcredits) = @_;
 1948:     my $format = $env{'form.output'};
 1949:     if (! exists($env{'form.sortby'})) {
 1950:         $env{'form.sortby'} = 'username';
 1951:     }
 1952:     if ($env{'form.Status'} !~ /^(Any|Expired|Active|Future)$/) {
 1953:         $env{'form.Status'} = 'Active';
 1954:     }
 1955:     my $onchange = "javascript:updateCols('Status');";
 1956:     my $status_select = &Apache::lonhtmlcommon::StatusOptions
 1957:         ($env{'form.Status'},undef,undef,$onchange);
 1958: 
 1959:     if ($env{'form.showrole'} eq '') {
 1960:         if ($context eq 'course') {
 1961:             $env{'form.showrole'} = 'st';
 1962:         } else {
 1963:             $env{'form.showrole'} = 'Any';            
 1964:         }
 1965:     }
 1966:     if (! defined($env{'form.output'}) ||
 1967:         $env{'form.output'} !~ /^(csv|excel|html)$/ ) {
 1968:         $env{'form.output'} = 'html';
 1969:     }
 1970: 
 1971:     my @statuses;
 1972:     if ($env{'form.Status'} eq 'Any') {
 1973:         @statuses = ('previous','active','future');
 1974:     } elsif ($env{'form.Status'} eq 'Expired') {
 1975:         @statuses = ('previous');
 1976:     } elsif ($env{'form.Status'} eq 'Active') {
 1977:         @statuses = ('active');
 1978:     } elsif ($env{'form.Status'} eq 'Future') {
 1979:         @statuses = ('future');
 1980:     }
 1981: 
 1982:     # Interface output
 1983:     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n".
 1984:               '<input type="hidden" name="action" value="'.
 1985:               $env{'form.action'}.'" />');
 1986:     $r->print('<div>'."\n");
 1987:     if ($env{'form.action'} ne 'modifystudent') {
 1988:         my %lt=&Apache::lonlocal::texthash('csv' => "CSV",
 1989:                                            'excel' => "Excel",
 1990:                                            'html'  => 'HTML');
 1991:         my $output_selector = '<select size="1" name="output" onchange="javascript:updateCols('."'output'".');" >';
 1992:         foreach my $outputformat ('html','csv','excel') {
 1993:             my $option = '<option value="'.$outputformat.'"';
 1994:             if ($outputformat eq $env{'form.output'}) {
 1995:                 $option .= ' selected="selected"';
 1996:             }
 1997:             $option .='>'.$lt{$outputformat}.'</option>';
 1998:             $output_selector .= "\n".$option;
 1999:         }
 2000:         $output_selector .= '</select>';
 2001:         $r->print('<span class="LC_nobreak">'
 2002:                  .&mt('Output Format: [_1]',$output_selector)
 2003:                  .'</span>'.('&nbsp;'x3));
 2004:     }
 2005:     $r->print('<span class="LC_nobreak">'
 2006:              .&mt('User Status: [_1]',$status_select)
 2007:              .'</span>'.('&nbsp;'x3)."\n");
 2008:     my $roleselected = '';
 2009:     if ($env{'form.showrole'} eq 'Any') {
 2010:        $roleselected = ' selected="selected"'; 
 2011:     }
 2012:     my ($cnum,$cdom);
 2013:     $r->print(&role_filter($context));
 2014:     if ($context eq 'course') {
 2015:         ($cnum,$cdom) = &get_course_identity();
 2016:         $r->print(&section_group_filter($cnum,$cdom));
 2017:     }
 2018:     $r->print('</div><div class="LC_left_float">'.
 2019:               &column_checkboxes($context,$mode,$formname,$showcredits).
 2020:               '</div>');
 2021:     if ($env{'form.phase'} eq '') {
 2022:         $r->print('<br clear="all" />'.
 2023:                   &list_submit_button(&mt('Display List of Users'))."\n".
 2024:                   '<input type="hidden" name="phase" value="" /></form>');
 2025:         return;
 2026:     }
 2027:     if (!(($context eq 'domain') && 
 2028:           (($env{'form.roletype'} eq 'course') || ($env{'form.roletype'} eq 'community')))) {
 2029:         $r->print('<br clear="all" />'.
 2030:                   &list_submit_button(&mt('Update Display'))."\n");
 2031:     }
 2032: 
 2033:     my @cols = &infocolumns($context,$mode,$showcredits);  
 2034:     if (!@cols) {
 2035:          $r->print('<hr style="clear:both;" /><span class="LC_warning">'.
 2036:                    &mt('No user information selected for display.').'</span>'.
 2037:                    '<input type="hidden" name="phase" value="display" /></form>'."\n");
 2038:          return;
 2039:     }
 2040:     my ($indexhash,$keylist) = &make_keylist_array();
 2041:     my (%userlist,%userinfo,$clearcoursepick,$needauthorquota,$needauthorusage);
 2042:     if (($context eq 'domain') && 
 2043:         ($env{'form.roletype'} eq 'course') || 
 2044:         ($env{'form.roletype'} eq 'community')) {
 2045:         my ($crstype,$numcodes,$title,$warning);
 2046:         if ($env{'form.roletype'} eq 'course') {
 2047:             $crstype = 'Course';
 2048:             $numcodes = $totcodes;
 2049:             $title = &mt('Select Courses');
 2050:             $warning = &mt('Warning: data retrieval for multiple courses can take considerable time, as this operation is not currently optimized.');
 2051:         } elsif ($env{'form.roletype'} eq 'community') {
 2052:             $crstype = 'Community';
 2053:             $numcodes = 0;
 2054:             $title = &mt('Select Communities');
 2055:             $warning = &mt('Warning: data retrieval for multiple communities can take considerable time, as this operation is not currently optimized.');
 2056:         }
 2057:         my @standardnames = &Apache::loncommon::get_standard_codeitems();
 2058:         my $courseform =
 2059:             &Apache::lonhtmlcommon::course_selection($formname,$numcodes,
 2060:                             $codetitles,$idlist,$idlist_titles,$crstype,
 2061:                             \@standardnames);
 2062:         $r->print('<div class="LC_left_float">'.
 2063:                   '<fieldset><legend>'.$title.'</legend>'."\n".
 2064:                   $courseform."\n".
 2065:                   '</fieldset></div><br clear="all" />'.
 2066:                   '<p><input type="hidden" name="origroletype" value="'.$env{'form.roletype'}.'" />'.
 2067:                   &list_submit_button(&mt('Update Display')).
 2068:                   "\n".'</p><span class="LC_warning">'.$warning.'</span>'."\n");
 2069:         $clearcoursepick = 0;
 2070:         if (($env{'form.origroletype'} ne '') &&
 2071:             ($env{'form.origroletype'} ne $env{'form.roletype'})) {
 2072:             $clearcoursepick = 1;
 2073:         }
 2074:         if (($env{'form.coursepick'}) && (!$clearcoursepick)) {
 2075:             $r->print('<hr />'.&mt('Searching ...').'<br />&nbsp;<br />');
 2076:         }
 2077:     } else {
 2078:         $r->print('<hr style="clear:both;" /><div id="searching">'.&mt('Searching ...').'</div>');
 2079:     }
 2080:     $r->rflush();
 2081:     if ($context eq 'course') {
 2082:         if (($env{'form.showrole'} eq 'st') || ($env{'form.showrole'} eq 'Any')) { 
 2083:             my $classlist = &Apache::loncoursedata::get_classlist();
 2084:             if (ref($classlist) eq 'HASH') {
 2085:                 %userlist = %{$classlist};
 2086:             }
 2087:         }
 2088:         if ($env{'form.showrole'} ne 'st') {
 2089:             my $showroles;
 2090:             if ($env{'form.showrole'} ne 'Any') {
 2091:                 $showroles = [$env{'form.showrole'}];
 2092:             } else {
 2093:                 $showroles = undef;
 2094:             }
 2095:             my $withsec = 1;
 2096:             my $hidepriv = 1;
 2097:             my %advrolehash = &Apache::lonnet::get_my_roles($cnum,$cdom,undef,
 2098:                               \@statuses,$showroles,undef,$withsec,$hidepriv);
 2099:             &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
 2100:                              \%advrolehash,$permission);
 2101:         }
 2102:     } else {
 2103:         my (%cstr_roles,%dom_roles);
 2104:         if ($context eq 'author') {
 2105:             # List co-authors and assistant co-authors
 2106:             my @possroles = &roles_by_context($context);
 2107:             %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 2108:                                               \@statuses,\@possroles);
 2109:             &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
 2110:                              \%cstr_roles,$permission);
 2111:         } elsif ($context eq 'domain') {
 2112:             if ($env{'form.roletype'} eq 'domain') {
 2113:                 if (grep(/^authorusage$/,@cols)) {
 2114:                     $needauthorusage = 1;
 2115:                 }
 2116:                 if (grep(/^authorquota$/,@cols)) {
 2117:                     $needauthorquota = 1;
 2118:                 }
 2119:                 %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'});
 2120:                 foreach my $key (keys(%dom_roles)) {
 2121:                     if (ref($dom_roles{$key}) eq 'HASH') {
 2122:                         &gather_userinfo($context,$format,\%userlist,$indexhash,
 2123:                                          \%userinfo,$dom_roles{$key},$permission);
 2124:                     }
 2125:                 }
 2126:             } elsif ($env{'form.roletype'} eq 'author') {
 2127:                 my %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'},['au']);
 2128:                 my %coauthors;
 2129:                 foreach my $key (keys(%dom_roles)) {
 2130:                     if (ref($dom_roles{$key}) eq 'HASH') {
 2131:                         if ($env{'form.showrole'} eq 'au') {
 2132:                             &gather_userinfo($context,$format,\%userlist,$indexhash,
 2133:                                              \%userinfo,$dom_roles{$key},$permission);
 2134:                         } else {
 2135:                             my @possroles;
 2136:                             if ($env{'form.showrole'} eq 'Any') {
 2137:                                 @possroles = &roles_by_context('author');
 2138:                             } else {
 2139:                                 @possroles = ($env{'form.showrole'}); 
 2140:                             }
 2141:                             foreach my $author (sort(keys(%{$dom_roles{$key}}))) {
 2142:                                 my ($role,$authorname,$authordom) = split(/:/,$author,-1);
 2143:                                 my $extent = '/'.$authordom.'/'.$authorname;
 2144:                                 %{$coauthors{$extent}} =
 2145:                                     &Apache::lonnet::get_my_roles($authorname,
 2146:                                        $authordom,undef,\@statuses,\@possroles);
 2147:                             }
 2148:                             &gather_userinfo($context,$format,\%userlist,
 2149:                                      $indexhash,\%userinfo,\%coauthors,$permission);
 2150:                         }
 2151:                     }
 2152:                 }
 2153:             } elsif (($env{'form.roletype'} eq 'course') ||
 2154:                      ($env{'form.roletype'} eq 'community')) {
 2155:                 if (($env{'form.coursepick'}) && (!$clearcoursepick)) {
 2156:                     my %courses = &process_coursepick();
 2157:                     my %allusers;
 2158:                     my $hidepriv = 1;
 2159:                     foreach my $cid (keys(%courses)) {
 2160:                         my ($cnum,$cdom,$cdesc) = &get_course_identity($cid);
 2161:                         next if ($cnum eq '' || $cdom eq '');
 2162:                         my $custom = 1;
 2163:                         my (@roles,@sections,%access,%users,%userdata,
 2164:                             %statushash);
 2165:                         if ($env{'form.showrole'} eq 'Any') {
 2166:                             @roles = &course_roles($context,undef,$custom,
 2167:                                                    $env{'form.roletype'});
 2168:                         } else {
 2169:                             @roles = ($env{'form.showrole'});
 2170:                         }
 2171:                         foreach my $role (@roles) {
 2172:                             %{$users{$role}} = ();
 2173:                         }
 2174:                         foreach my $type (@statuses) {
 2175:                             $access{$type} = $type;
 2176:                         }
 2177:                         &Apache::loncommon::get_course_users($cdom,$cnum,\%access,\@roles,\@sections,\%users,\%userdata,\%statushash,$hidepriv);
 2178:                         foreach my $user (keys(%userdata)) {
 2179:                             next if (ref($userinfo{$user}) eq 'HASH');
 2180:                             foreach my $item ('fullname','id') {
 2181:                                 $userinfo{$user}{$item} = $userdata{$user}[$indexhash->{$item}];
 2182:                             }
 2183:                         }
 2184:                         foreach my $role (keys(%users)) {
 2185:                             foreach my $user (keys(%{$users{$role}})) {
 2186:                                 my $uniqid = $user.':'.$role;
 2187:                                 $allusers{$uniqid}{$cid} = { desc => $cdesc,
 2188:                                                              secs  => $statushash{$user}{$role},
 2189:                                                            };
 2190:                             }
 2191:                         }
 2192:                     }
 2193:                     &gather_userinfo($context,$format,\%userlist,$indexhash,
 2194:                                      \%userinfo,\%allusers,$permission);
 2195:                 } else {
 2196:                     $r->print('<input type="hidden" name="phase" value="'.
 2197:                               $env{'form.phase'}.'" /></form>');
 2198:                     return;
 2199:                 }
 2200:             }
 2201:         }
 2202:     }
 2203:     if (keys(%userlist) == 0) {
 2204:         my $msg = '';
 2205:         if ($context eq 'author') {
 2206:             $msg = &mt('There are no co-authors to display.');
 2207:         } elsif ($context eq 'domain') {
 2208:             if ($env{'form.roletype'} eq 'domain') {
 2209:                 $msg = &mt('There are no users with domain roles to display.');
 2210:             } elsif ($env{'form.roletype'} eq 'author') {
 2211:                 $msg = &mt('There are no authors or co-authors to display.');
 2212:             } elsif ($env{'form.roletype'} eq 'course') {
 2213:                 $msg = &mt('There are no course users to display');
 2214:             } elsif ($env{'form.roletype'} eq 'community') {
 2215:                 $msg = &mt('There are no community users to display');
 2216:             }
 2217:         } elsif ($context eq 'course') {
 2218:             $r->print(&mt('There are no course users to display.')."\n");
 2219:         }
 2220:         $r->print('<p class="LC_info">'.$msg.'</p>'."\n") if $msg;
 2221:     } else {
 2222:         # Print out the available choices
 2223:         my $usercount;
 2224:         if ($env{'form.action'} eq 'modifystudent') {
 2225:             ($usercount) = &show_users_list($r,$context,'view',$permission,
 2226:                                  $env{'form.Status'},\%userlist,$keylist,'',
 2227:                                  $showcredits);
 2228:         } else {
 2229:             ($usercount) = &show_users_list($r,$context,$env{'form.output'},
 2230:                                $permission,$env{'form.Status'},\%userlist,
 2231:                                $keylist,'',$showcredits,$needauthorquota,$needauthorusage);
 2232:         }
 2233:         if (!$usercount) {
 2234:             $r->print('<br /><span class="LC_info">'
 2235:                      .&mt('There are no users matching the search criteria.')
 2236:                      .'</span>'
 2237:             ); 
 2238:         }
 2239:     }
 2240:     $r->print('<input type="hidden" name="phase" value="'.
 2241:               $env{'form.phase'}.'" /></form>');
 2242:     return;
 2243: }
 2244: 
 2245: sub role_filter {
 2246:     my ($context) = @_;
 2247:     my $output;
 2248:     my $roleselected = '';
 2249:     if ($env{'form.showrole'} eq 'Any') {
 2250:        $roleselected = ' selected="selected"';
 2251:     }
 2252:     my ($role_select);
 2253:     if ($context eq 'domain') {
 2254:         $role_select = &domain_roles_select();
 2255:         $output = '<span class="LC_nobreak">'
 2256:                  .&mt('Role Type: [_1]',$role_select)
 2257:                  .'</span>';
 2258:     } else {
 2259:         $role_select = '<select name="showrole" onchange="javascript:updateCols('."'showrole'".');">'."\n".
 2260:                        '<option value="Any" '.$roleselected.'>'.
 2261:                        &mt('Any role').'</option>';
 2262:         my ($roletype,$crstype);
 2263:         if ($context eq 'course') {
 2264:             $crstype = &Apache::loncommon::course_type();
 2265:             if ($crstype eq 'Community') {
 2266:                 $roletype = 'community';
 2267:             } else {
 2268:                 $roletype = 'course';
 2269:             } 
 2270:         }
 2271:         my @poss_roles = &curr_role_permissions($context,'','',$roletype);
 2272:         foreach my $role (@poss_roles) {
 2273:             $roleselected = '';
 2274:             if ($role eq $env{'form.showrole'}) {
 2275:                 $roleselected = ' selected="selected"';
 2276:             }
 2277:             my $plrole;
 2278:             if ($role eq 'cr') {
 2279:                 $plrole = &mt('Custom role');
 2280:             } else {
 2281:                 $plrole=&Apache::lonnet::plaintext($role,$crstype);
 2282:             }
 2283:             $role_select .= '<option value="'.$role.'"'.$roleselected.'>'.$plrole.'</option>';
 2284:         }
 2285:         $role_select .= '</select>';
 2286:         $output = '<span class="LC_nobreak">'
 2287:                  .&mt('Role: [_1]',$role_select)
 2288:                  .'</span>';
 2289:     }
 2290:     return $output;
 2291: }
 2292: 
 2293: sub section_group_filter {
 2294:     my ($cnum,$cdom) = @_;
 2295:     my @filters;
 2296:     if ($env{'request.course.sec'} eq '') {
 2297:         @filters = ('sec');
 2298:     }
 2299:     push(@filters,'grp');
 2300:     my %name = (
 2301:                  sec => 'secfilter',
 2302:                  grp => 'grpfilter',
 2303:                );
 2304:     my %title = &Apache::lonlocal::texthash (
 2305:                                               sec  => 'Section(s)',
 2306:                                               grp  => 'Group(s)',
 2307:                                               all  => 'all',
 2308:                                               none => 'none',
 2309:                                             );
 2310:     my $output;
 2311:     foreach my $item (@filters) {
 2312:         my ($markup,@options); 
 2313:         if ($env{'form.'.$name{$item}} eq '') {
 2314:             $env{'form.'.$name{$item}} = 'all';
 2315:         }
 2316:         if ($item eq 'sec') {
 2317:             if (($env{'form.showrole'} eq 'cc') || ($env{'form.showrole'} eq 'co')) {
 2318:                 $env{'form.'.$name{$item}} = 'none';
 2319:             }
 2320:             my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 2321:             @options = sort(keys(%sections_count));
 2322:         } elsif ($item eq 'grp') {
 2323:             my %curr_groups = &Apache::longroup::coursegroups();
 2324:             @options = sort(keys(%curr_groups));
 2325:         }
 2326:         if (@options > 0) {
 2327:             my $currsel;
 2328:             $markup = '<select name="'.$name{$item}.'">'."\n";
 2329:             foreach my $option ('all','none',@options) { 
 2330:                 $currsel = '';
 2331:                 if ($env{'form.'.$name{$item}} eq $option) {
 2332:                     $currsel = ' selected="selected"';
 2333:                 }
 2334:                 $markup .= ' <option value="'.$option.'"'.$currsel.'>';
 2335:                 if (($option eq 'all') || ($option eq 'none')) {
 2336:                     $markup .= $title{$option};
 2337:                 } else {
 2338:                     $markup .= $option;
 2339:                 }   
 2340:                 $markup .= '</option>'."\n";
 2341:             }
 2342:             $markup .= '</select>'."\n";
 2343:             $output .= ('&nbsp;'x3).'<span class="LC_nobreak">'
 2344:                       .'<label>'.$title{$item}.': '.$markup.'</label>'
 2345:                       .'</span> ';
 2346:         }
 2347:     }
 2348:     return $output;
 2349: }
 2350: 
 2351: sub infocolumns {
 2352:     my ($context,$mode,$showcredits) = @_;
 2353:     my @cols;
 2354:     if (($mode eq 'pickauthor') || ($mode eq 'autoenroll')) {
 2355:         @cols = &get_cols_array($context,$mode,$showcredits);
 2356:     } else {
 2357:         my @posscols = &get_cols_array($context,$mode,$showcredits);
 2358:         if ($env{'form.phase'} ne '') {
 2359:             my @checkedcols = &Apache::loncommon::get_env_multiple('form.showcol');
 2360:             foreach my $col (@checkedcols) {
 2361:                 if (grep(/^$col$/,@posscols)) {
 2362:                     push(@cols,$col);
 2363:                 }
 2364:             }
 2365:         } else {
 2366:             @cols = @posscols;
 2367:         }
 2368:     }
 2369:     return @cols;
 2370: }
 2371: 
 2372: sub get_cols_array {
 2373:     my ($context,$mode,$showcredits) = @_;
 2374:     my @cols;
 2375:     if ($mode eq 'pickauthor') {
 2376:         @cols = ('username','fullname','status','email');
 2377:     } else {
 2378:         @cols = ('username','domain','id','fullname');
 2379:         if ($context eq 'course') {
 2380:             push(@cols,'section');
 2381:         }
 2382:         push(@cols,('start','end','role'));
 2383:         unless (($mode eq 'autoenroll') && ($env{'form.Status'} ne 'Any')) {
 2384:             push(@cols,'status');
 2385:         }
 2386:         if ($context eq 'course') {
 2387:             push(@cols,'groups');
 2388:         }
 2389:         push(@cols,'email');
 2390:         if (($context eq 'course') && ($mode ne 'autoenroll')) {
 2391:             if ($showcredits) {
 2392:                 push(@cols,'credits');
 2393:             }
 2394:             push(@cols,'lastlogin','clicker');
 2395:         }
 2396:         if (($context eq 'course') && ($mode ne 'autoenroll') &&
 2397:             ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'})) {
 2398:             push(@cols,'photo');
 2399:         }
 2400:         if ($context eq 'domain') {
 2401:             push (@cols,('authorusage','authorquota','extent'));
 2402:         }
 2403:     }
 2404:     return @cols;
 2405: }
 2406: 
 2407: sub column_checkboxes {
 2408:     my ($context,$mode,$formname,$showcredits) = @_;
 2409:     my @cols = &get_cols_array($context,$mode,$showcredits);
 2410:     my @showncols = &Apache::loncommon::get_env_multiple('form.showcol');
 2411:     my (%disabledchk,%unchecked);
 2412:     if ($env{'form.phase'} eq '') {
 2413:         $disabledchk{'status'} = 1;
 2414:         if ($context eq 'course') {
 2415:             $disabledchk{'role'} = 1;
 2416:             $unchecked{'photo'} = 1;
 2417:             $unchecked{'clicker'} = 1;
 2418:             if ($showcredits) {
 2419:                 $unchecked{'credits'} = 1;
 2420:             }
 2421:         } elsif ($context eq 'domain') { 
 2422:             $unchecked{'extent'} = 1; 
 2423:         }
 2424:         $unchecked{'start'} = 1;
 2425:         $unchecked{'end'} = 1;
 2426:     } else {
 2427:         if ($env{'form.Status'} ne 'Any') {
 2428:             $disabledchk{'status'} = 1;
 2429:         }
 2430:         if (($env{'form.showrole'} ne 'Any') && ($env{'form.showrole'} ne 'cr')) {
 2431:             $disabledchk{'role'} = 1;
 2432:         }
 2433:         if ($context eq 'domain') {
 2434:             if (($env{'form.roletype'} eq 'course') || 
 2435:                 ($env{'form.roletype'} eq 'community')) {
 2436:                 $disabledchk{'status'} = 1;
 2437:                 $disabledchk{'authorusage'} = 1;
 2438:                 $disabledchk{'authorquota'} = 1;
 2439:             } elsif ($env{'form.roletype'} eq 'domain') {
 2440:                 $disabledchk{'extent'} = 1; 
 2441:             }
 2442:         }
 2443:     }
 2444:     my $numposs = scalar(@cols);
 2445:     my $numinrow = 7;
 2446:     my %lt = &get_column_names($context);
 2447:     my $output = '<fieldset><legend>'.&mt('Information to show').'</legend>'."\n".'<span class="LC_nobreak">'.
 2448:                  '<input type="button" onclick="javascript:checkAll(document.'.$formname.'.showcol);" value="'.&mt('check all').'" />'.
 2449:                  ('&nbsp;'x3).
 2450:                  '<input type="button" onclick="javascript:uncheckAll(document.'.$formname.'.showcol);" value="'.&mt('uncheck all').'" />'.
 2451:                  '</span><table>';
 2452:     
 2453:     for (my $i=0; $i<$numposs; $i++) {
 2454:         my $rem = $i%($numinrow);
 2455:         if ($rem == 0) {
 2456:             if ($i > 0) {
 2457:                 $output .= '</tr>';
 2458:             }
 2459:             $output .= '<tr>';
 2460:         }
 2461:         my $checked;
 2462:         if ($env{'form.phase'} eq '') {
 2463:             $checked = ' checked="checked"';
 2464:             if ($unchecked{$cols[$i]}) { 
 2465:                $checked = '';
 2466:             }
 2467:             if ($disabledchk{$cols[$i]}) {
 2468:                 $checked = ' disabled="disabled"';
 2469:             }
 2470:         } elsif (grep(/^\Q$cols[$i]\E$/,@showncols)) {
 2471:             $checked = ' checked="checked"';
 2472:         } elsif ($disabledchk{$cols[$i]}) {
 2473:             $checked = ' disabled="disabled"';
 2474:         }
 2475:         if ($i == $numposs-1) {
 2476:             my $colsleft = $numinrow-$rem;
 2477:             if ($colsleft > 1) {
 2478:                 $output .= '<td colspan="'.$colsleft.'">';
 2479:             } else {
 2480:                 $output .= '<td>';
 2481:             }
 2482:         } else {
 2483:             $output .= '<td>';
 2484:         }
 2485:         my $style;
 2486:         if ($cols[$i] eq 'extent') {
 2487:             if (($env{'form.roletype'} eq 'domain') || ($env{'form.roletype'} eq '')) {
 2488:                 $style = ' style="display: none;"';
 2489:             } 
 2490:         } elsif (($cols[$i] eq 'authorusage') || ($cols[$i] eq 'authorquota')) {
 2491:             if ($env{'form.roletype'} ne 'domain') {
 2492:                 $style = ' style="display: none;"';
 2493:             }
 2494:         }
 2495:         $output .= '<span id="show'.$cols[$i].'"'.$style.'><label>'.
 2496:                    '<input id="showcol'.$cols[$i].'" type="checkbox" name="showcol" value="'.$cols[$i].'"'.$checked.' /><span id="showcoltext'.$cols[$i].'">'.
 2497:                    $lt{$cols[$i]}.'</span>'.
 2498:                    '</label></span></td>';
 2499:     }
 2500:     $output .= '</tr></table></fieldset>';
 2501:     return $output;
 2502: }
 2503: 
 2504: sub list_submit_button {
 2505:     my ($text) = @_;
 2506:     return '<input type="button" name="updatedisplay" value="'.$text.'" onclick="javascript:display_update()" />';
 2507: }
 2508: 
 2509: sub get_column_names {
 2510:     my ($context) = @_;
 2511:     my %lt = &Apache::lonlocal::texthash(
 2512:         'username'   => "username",
 2513:         'domain'     => "domain",
 2514:         'id'         => 'ID',
 2515:         'fullname'   => "name",
 2516:         'section'    => "section",
 2517:         'groups'     => "active groups",
 2518:         'start'      => "start date",
 2519:         'end'        => "end date",
 2520:         'status'     => "status",
 2521:         'role'       => "role",
 2522:         'credits'    => "credits",
 2523:         'type'       => "enroll type/action",
 2524:         'email'      => "e-mail address",
 2525:         'photo'      => "photo",
 2526:         'lastlogin'  => "last login",
 2527:         'extent'     => "extent",
 2528:         'authorusage' => "disk usage (%)",
 2529:         'authorquota' => "disk quota (MB)",
 2530:         'ca'         => "check all",
 2531:         'ua'         => "uncheck all",
 2532:         'clicker'    => "clicker-ID",
 2533:     );
 2534:     if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
 2535:         $lt{'extent'} = &mt('course(s): description, section(s), status');
 2536:     } elsif ($context eq 'domain' && $env{'form.roletype'} eq 'community') {
 2537:         $lt{'extent'} = &mt('community(s): description, section(s), status');
 2538:     } elsif (($context eq 'author') || 
 2539:              ($context eq 'domain' && $env{'form.roletype'} eq 'author')) {
 2540:         $lt{'extent'} = &mt('author');
 2541:     }
 2542:     return %lt;
 2543: }
 2544: 
 2545: sub gather_userinfo {
 2546:     my ($context,$format,$userlist,$indexhash,$userinfo,$rolehash,$permission) = @_;
 2547:     my $viewablesec;
 2548:     if ($context eq 'course') {
 2549:         $viewablesec = &viewable_section($permission);
 2550:     }
 2551:     foreach my $item (keys(%{$rolehash})) {
 2552:         my %userdata;
 2553:         if ($context eq 'author') { 
 2554:             ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
 2555:                 split(/:/,$item);
 2556:             ($userdata{'start'},$userdata{'end'})=split(/:/,$rolehash->{$item});
 2557:             &build_user_record($context,\%userdata,$userinfo,$indexhash,
 2558:                                $item,$userlist);
 2559:         } elsif ($context eq 'course') {
 2560:             ($userdata{'username'},$userdata{'domain'},$userdata{'role'},
 2561:              $userdata{'section'}) = split(/:/,$item,-1);
 2562:             ($userdata{'start'},$userdata{'end'})=split(/:/,$rolehash->{$item});
 2563:             if (($viewablesec ne '') && ($userdata{'section'} ne '')) {
 2564:                 next if ($viewablesec ne $userdata{'section'});
 2565:             }
 2566:             &build_user_record($context,\%userdata,$userinfo,$indexhash,
 2567:                                $item,$userlist);
 2568:         } elsif ($context eq 'domain') {
 2569:             if ($env{'form.roletype'} eq 'domain') {
 2570:                 ($userdata{'role'},$userdata{'username'},$userdata{'domain'}) =
 2571:                     split(/:/,$item);
 2572:                 ($userdata{'end'},$userdata{'start'})=split(/:/,$rolehash->{$item});
 2573:                 &build_user_record($context,\%userdata,$userinfo,$indexhash,
 2574:                                    $item,$userlist);
 2575:             } elsif ($env{'form.roletype'} eq 'author') {
 2576:                 if (ref($rolehash->{$item}) eq 'HASH') {
 2577:                     $userdata{'extent'} = $item;
 2578:                     foreach my $key (keys(%{$rolehash->{$item}})) {
 2579:                         ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =  split(/:/,$key);
 2580:                         ($userdata{'start'},$userdata{'end'}) = 
 2581:                             split(/:/,$rolehash->{$item}{$key});
 2582:                         my $uniqid = $key.':'.$item;
 2583:                         &build_user_record($context,\%userdata,$userinfo,
 2584:                                            $indexhash,$uniqid,$userlist);
 2585:                     }
 2586:                 }
 2587:             } elsif (($env{'form.roletype'} eq 'course') || 
 2588:                      ($env{'form.roletype'} eq 'community')) {
 2589:                 ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
 2590:                     split(/:/,$item);
 2591:                 if (ref($rolehash->{$item}) eq 'HASH') {
 2592:                     my $numcids = keys(%{$rolehash->{$item}});
 2593:                     foreach my $cid (sort(keys(%{$rolehash->{$item}}))) {
 2594:                         if (ref($rolehash->{$item}{$cid}) eq 'HASH') {
 2595:                             my $spanstart = '';
 2596:                             my $spanend = '; ';
 2597:                             my $space = ', ';
 2598:                             if ($format eq 'html' || $format eq 'view') {
 2599:                                 $spanstart = '<span class="LC_nobreak">';
 2600:                                 # FIXME: actions on courses disabled for now
 2601: #                                if ($permission->{'cusr'}) {
 2602: #                                    if ($numcids > 1) {
 2603: #                                        $spanstart .= '<input type="radio" name="'.$item.'" value="'.$cid.'" />&nbsp;';
 2604: #                                    } else {
 2605: #                                        $spanstart .= '<input type="hidden" name="'.$item.'" value="'.$cid.'" />&nbsp;';
 2606: #                                    }
 2607: #                                }
 2608:                                 $spanend = '</span><br />';
 2609:                                 $space = ',&nbsp;';
 2610:                             }
 2611:                             $userdata{'extent'} .= $spanstart.
 2612:                                     $rolehash->{$item}{$cid}{'desc'}.$space;
 2613:                             if (ref($rolehash->{$item}{$cid}{'secs'}) eq 'HASH') { 
 2614:                                 foreach my $sec (sort(keys(%{$rolehash->{$item}{$cid}{'secs'}}))) {
 2615:                                     if (($env{'form.Status'} eq 'Any') ||
 2616:                                         ($env{'form.Status'} eq $rolehash->{$item}{$cid}{'secs'}{$sec})) {
 2617:                                         $userdata{'extent'} .= $sec.$space.$rolehash->{$item}{$cid}{'secs'}{$sec}.$spanend;
 2618:                                         $userdata{'status'} = $rolehash->{$item}{$cid}{'secs'}{$sec};
 2619:                                     }
 2620:                                 }
 2621:                             }
 2622:                         }
 2623:                     }
 2624:                 }
 2625:                 if ($userdata{'status'} ne '') {
 2626:                     &build_user_record($context,\%userdata,$userinfo,
 2627:                                        $indexhash,$item,$userlist);
 2628:                 }
 2629:             }
 2630:         }
 2631:     }
 2632:     return;
 2633: }
 2634: 
 2635: sub build_user_record {
 2636:     my ($context,$userdata,$userinfo,$indexhash,$record_key,$userlist) = @_;
 2637:     next if ($userdata->{'start'} eq '-1' && $userdata->{'end'} eq '-1');
 2638:     if (!(($context eq 'domain') && (($env{'form.roletype'} eq 'course')
 2639:                              && ($env{'form.roletype'} eq 'community')))) {
 2640:         &process_date_info($userdata);
 2641:     }
 2642:     my $username = $userdata->{'username'};
 2643:     my $domain = $userdata->{'domain'};
 2644:     if (ref($userinfo->{$username.':'.$domain}) eq 'HASH') {
 2645:         $userdata->{'fullname'} = $userinfo->{$username.':'.$domain}{'fullname'};
 2646:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
 2647:     } else {
 2648:         &aggregate_user_info($domain,$username,$userinfo);
 2649:         $userdata->{'fullname'} = $userinfo->{$username.':'.$domain}{'fullname'};
 2650:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
 2651:     }
 2652:     foreach my $key (keys(%{$indexhash})) {
 2653:         if (defined($userdata->{$key})) {
 2654:             $userlist->{$record_key}[$indexhash->{$key}] = $userdata->{$key};
 2655:         }
 2656:     }
 2657:     return;
 2658: }
 2659: 
 2660: sub courses_selector {
 2661:     my ($cdom,$formname) = @_;
 2662:     my %codes = ();
 2663:     my @codetitles = ();
 2664:     my %cat_titles = ();
 2665:     my %cat_order = ();
 2666:     my %idlist = ();
 2667:     my %idnums = ();
 2668:     my %idlist_titles = ();
 2669:     my $caller = 'global';
 2670:     my $format_reply;
 2671:     my $jscript = '';
 2672: 
 2673:     my $totcodes = 0;
 2674:     my $instcats = &Apache::lonnet::get_dom_instcats($cdom);
 2675:     if (ref($instcats) eq 'HASH') {
 2676:         if ((ref($instcats->{'codetitles'}) eq 'ARRAY') && (ref($instcats->{'codes'}) eq 'HASH') &&
 2677:             (ref($instcats->{'cat_titles'}) eq 'HASH') && (ref($instcats->{'cat_order'}) eq 'HASH')) {
 2678:             %codes = %{$instcats->{'codes'}};
 2679:             @codetitles = @{$instcats->{'codetitles'}};
 2680:             %cat_titles = %{$instcats->{'cat_titles'}};
 2681:             %cat_order = %{$instcats->{'cat_order'}};
 2682:             $totcodes = scalar(keys(%codes));
 2683:             my $numtypes = @codetitles;
 2684:             &Apache::courseclassifier::build_code_selections(\%codes,\@codetitles,\%cat_titles,\%cat_order,\%idlist,\%idnums,\%idlist_titles);
 2685:             my ($scripttext,$longtitles) = &Apache::courseclassifier::javascript_definitions(\@codetitles,\%idlist,\%idlist_titles,\%idnums,\%cat_titles);
 2686:             my $longtitles_str = join('","',@{$longtitles});
 2687:             my $allidlist = $idlist{$codetitles[0]};
 2688:             $jscript .= &Apache::courseclassifier::courseset_js_start($formname,$longtitles_str,$allidlist);
 2689:             $jscript .= $scripttext;
 2690:             $jscript .= &Apache::courseclassifier::javascript_code_selections($formname,\@codetitles);
 2691:         }
 2692:     }
 2693:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($cdom);
 2694: 
 2695:     my %elements = (
 2696:                      Year => 'selectbox',
 2697:                      coursepick => 'radio',
 2698:                      coursetotal => 'text',
 2699:                      courselist => 'text',
 2700:                    );
 2701:     $jscript .= &Apache::lonhtmlcommon::set_form_elements(\%elements);
 2702:     if ($env{'form.coursepick'} eq 'category') {
 2703:         $jscript .= qq|
 2704: function setCourseCat(formname) {
 2705:     if (formname.Year.options[formname.Year.selectedIndex].value == -1) {
 2706:         return;
 2707:     }
 2708:     courseSet('$codetitles[0]');
 2709:     for (var j=0; j<formname.Semester.length; j++) {
 2710:         if (formname.Semester.options[j].value == "$env{'form.Semester'}") {
 2711:             formname.Semester.options[j].selected = true;
 2712:         }
 2713:     }
 2714:     if (formname.Semester.options[formname.Semester.selectedIndex].value == -1) {
 2715:         return;
 2716:     }
 2717:     courseSet('$codetitles[1]');
 2718:     for (var j=0; j<formname.Department.length; j++) {
 2719:         if (formname.Department.options[j].value == "$env{'form.Department'}") {
 2720:             formname.Department.options[j].selected = true;
 2721:         }
 2722:     }
 2723:     if (formname.Department.options[formname.Department.selectedIndex].value == -1) {
 2724:         return;
 2725:     }
 2726:     courseSet('$codetitles[2]');
 2727:     for (var j=0; j<formname.Number.length; j++) {
 2728:         if (formname.Number.options[j].value == "$env{'form.Number'}") {
 2729:             formname.Number.options[j].selected = true;
 2730:         }
 2731:     }
 2732: }
 2733: |;
 2734:     }
 2735:     return ($cb_jscript,$jscript,$totcodes,\@codetitles,\%idlist,
 2736:             \%idlist_titles);
 2737: }
 2738: 
 2739: sub course_selector_loadcode {
 2740:     my ($formname) = @_;
 2741:     my $loadcode;
 2742:     if ($env{'form.coursepick'} ne '') {
 2743:         $loadcode = 'javascript:setFormElements(document.'.$formname.')';
 2744:         if ($env{'form.coursepick'} eq 'category') {
 2745:             $loadcode .= ';javascript:setCourseCat(document.'.$formname.')';
 2746:         }
 2747:     }
 2748:     return $loadcode;
 2749: }
 2750: 
 2751: sub process_coursepick {
 2752:     my $coursefilter = $env{'form.coursepick'};
 2753:     my $cdom = $env{'request.role.domain'};
 2754:     my %courses;
 2755:     my $crssrch = 'Course';
 2756:     if ($env{'form.roletype'} eq 'community') {
 2757:         $crssrch = 'Community';
 2758:     }
 2759:     if ($coursefilter eq 'all') {
 2760:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.','.','.','.',
 2761:                                                  undef,undef,$crssrch);
 2762:     } elsif ($coursefilter eq 'category') {
 2763:         my $instcode = &instcode_from_coursefilter();
 2764:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.',$instcode,'.','.',
 2765:                                                  undef,undef,$crssrch);
 2766:     } elsif ($coursefilter eq 'specific') {
 2767:         if ($env{'form.coursetotal'} > 1) {
 2768:             my @course_ids = split(/&&/,$env{'form.courselist'});
 2769:             foreach my $cid (@course_ids) {
 2770:                 $courses{$cid} = '';
 2771:             }
 2772:         } else {
 2773:             $courses{$env{'form.courselist'}} = '';
 2774:         }
 2775:     }
 2776:     return %courses;
 2777: }
 2778: 
 2779: sub instcode_from_coursefilter {
 2780:     my $instcode = '';
 2781:     my @cats = ('Semester','Year','Department','Number');
 2782:     foreach my $category (@cats) {
 2783:         if (defined($env{'form.'.$category})) {
 2784:             unless ($env{'form.'.$category} eq '-1') {
 2785:                 $instcode .= $env{'form.'.$category};
 2786:            }
 2787:         }
 2788:     }
 2789:     if ($instcode eq '') {
 2790:         $instcode = '.';
 2791:     }
 2792:     return $instcode;
 2793: }
 2794: 
 2795: sub make_keylist_array {
 2796:     my ($index,$keylist);
 2797:     $index->{'domain'} = &Apache::loncoursedata::CL_SDOM();
 2798:     $index->{'username'} = &Apache::loncoursedata::CL_SNAME();
 2799:     $index->{'end'} = &Apache::loncoursedata::CL_END();
 2800:     $index->{'start'} = &Apache::loncoursedata::CL_START();
 2801:     $index->{'id'} = &Apache::loncoursedata::CL_ID();
 2802:     $index->{'section'} = &Apache::loncoursedata::CL_SECTION();
 2803:     $index->{'fullname'} = &Apache::loncoursedata::CL_FULLNAME();
 2804:     $index->{'status'} = &Apache::loncoursedata::CL_STATUS();
 2805:     $index->{'type'} = &Apache::loncoursedata::CL_TYPE();
 2806:     $index->{'lockedtype'} = &Apache::loncoursedata::CL_LOCKEDTYPE();
 2807:     $index->{'groups'} = &Apache::loncoursedata::CL_GROUP();
 2808:     $index->{'email'} = &Apache::loncoursedata::CL_PERMANENTEMAIL();
 2809:     $index->{'role'} = &Apache::loncoursedata::CL_ROLE();
 2810:     $index->{'extent'} = &Apache::loncoursedata::CL_EXTENT();
 2811:     $index->{'photo'} = &Apache::loncoursedata::CL_PHOTO();
 2812:     $index->{'thumbnail'} = &Apache::loncoursedata::CL_THUMBNAIL();
 2813:     $index->{'credits'} = &Apache::loncoursedata::CL_CREDITS();
 2814:     $index->{'instsec'} = &Apache::loncoursedata::CL_INSTSEC();
 2815:     $index->{'authorquota'} = &Apache::loncoursedata::CL_AUTHORQUOTA();
 2816:     $index->{'authorusage'} = &Apache::loncoursedata::CL_AUTHORUSAGE();
 2817:     foreach my $key (keys(%{$index})) {
 2818:         $keylist->[$index->{$key}] = $key;
 2819:     }
 2820:     return ($index,$keylist);
 2821: }
 2822: 
 2823: sub aggregate_user_info {
 2824:     my ($udom,$uname,$userinfo) = @_;
 2825:     my %info=&Apache::lonnet::get('environment',
 2826:                                   ['firstname','middlename',
 2827:                                    'lastname','generation','id'],
 2828:                                    $udom,$uname);
 2829:     my ($tmp) = keys(%info);
 2830:     my ($fullname,$id);
 2831:     if ($tmp =~/^(con_lost|error|no_such_host)/i) {
 2832:         $fullname = 'not available';
 2833:         $id = 'not available';
 2834:         &Apache::lonnet::logthis('unable to retrieve environment '.
 2835:                                  'for '.$uname.':'.$udom);
 2836:     } else {
 2837:         $fullname = &Apache::lonnet::format_name(@info{qw/firstname middlename lastname generation/},'lastname');
 2838:         $id = $info{'id'};
 2839:     }
 2840:     $userinfo->{$uname.':'.$udom} = { 
 2841:                                       fullname => $fullname,
 2842:                                       id       => $id,
 2843:                                     };
 2844:     return;
 2845: }
 2846: 
 2847: sub process_date_info {
 2848:     my ($userdata) = @_;
 2849:     my $now = time;
 2850:     $userdata->{'status'} = 'Active';
 2851:     if ($userdata->{'start'} > 0) {
 2852:         if ($now < $userdata->{'start'}) {
 2853:             $userdata->{'status'} = 'Future';
 2854:         }
 2855:     }
 2856:     if ($userdata->{'end'} > 0) {
 2857:         if ($now > $userdata->{'end'}) {
 2858:             $userdata->{'status'} = 'Expired';
 2859:         }
 2860:     }
 2861:     return;
 2862: }
 2863: 
 2864: sub show_users_list {
 2865:     my ($r,$context,$mode,$permission,$statusmode,$userlist,$keylist,$formname,
 2866:         $showcredits,$needauthorquota,$needauthorusage)=@_;
 2867:     if ($formname eq '') {
 2868:         $formname = 'studentform';
 2869:     }
 2870:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2871:     #
 2872:     # Variables for excel output
 2873:     my ($excel_workbook, $excel_sheet, $excel_filename,$row,$format);
 2874:     #
 2875:     # Variables for csv output
 2876:     my ($CSVfile,$CSVfilename);
 2877:     #
 2878:     my $sortby = $env{'form.sortby'};
 2879:     my @sortable = ('username','domain','id','fullname','start','end','email','role');
 2880:     if ($context eq 'course') {
 2881:         push(@sortable,('section','groups','type'));
 2882:         if ($showcredits) {
 2883:             push(@sortable,'credits');
 2884:         }
 2885:     } else {
 2886:         push(@sortable,'extent');
 2887:         if (($context eq 'domain') && ($env{'form.roletype'} eq 'domain') &&
 2888:             (($env{'form.showrole'} eq 'Any') || ($env{'form.showrole'} eq 'au'))) {
 2889:             push(@sortable,('authorusage','authorquota'));
 2890:         }
 2891:     }
 2892:     if ($mode eq 'pickauthor') {
 2893:         @sortable = ('username','fullname','email','status');
 2894:     }
 2895:     my %is_sortable;
 2896:     map { $is_sortable{$_} = 1; } @sortable;
 2897:     unless ($is_sortable{$sortby}) {
 2898:         $sortby = 'username';
 2899:     }
 2900:     my $setting = $env{'form.roletype'};
 2901:     my ($cid,$cdom,$cnum,$classgroups,$crstype,$defaultcredits);
 2902:     if ($context eq 'course') {
 2903:         $cid = $env{'request.course.id'};
 2904:         $crstype = &Apache::loncommon::course_type();
 2905:         ($cnum,$cdom) = &get_course_identity($cid);
 2906:         $defaultcredits = $env{'course.'.$cid.'.internal.defaultcredits'};
 2907:         ($classgroups) = &Apache::loncoursedata::get_group_memberships(
 2908:                                      $userlist,$keylist,$cdom,$cnum);
 2909:         if ($mode eq 'autoenroll') {
 2910:             $env{'form.showrole'} = 'st';
 2911:         } else {
 2912:             if ($env{'course.'.$cid.'.internal.showphoto'}) {
 2913:                 $r->print('
 2914: <script type="text/javascript">
 2915: // <![CDATA[
 2916: function photowindow(photolink) {
 2917:     var title = "Photo_Viewer";
 2918:     var options = "scrollbars=1,resizable=1,menubar=0";
 2919:     options += ",width=240,height=240";
 2920:     stdeditbrowser = open(photolink,title,options,"1");
 2921:     stdeditbrowser.focus();
 2922: }
 2923: // ]]>
 2924: </script>
 2925:                ');
 2926:             }
 2927:         }
 2928:     } elsif ($context eq 'domain') {
 2929:         if ($setting eq 'community') {
 2930:             $crstype = 'Community';
 2931:         } elsif ($setting eq 'course') {
 2932:             $crstype = 'Course';
 2933:         }
 2934:     }
 2935:     if ($mode ne 'autoenroll' && $mode ne 'pickauthor') {
 2936:         my $date_sec_selector = &date_section_javascript($context,$setting,$statusmode);
 2937:         my $verify_action_js = &bulkaction_javascript($formname);
 2938:         $r->print(<<END);
 2939: 
 2940: <script type="text/javascript" language="Javascript">
 2941: // <![CDATA[
 2942: 
 2943: $verify_action_js
 2944: 
 2945: function username_display_launch(username,domain) {
 2946:     var target;
 2947:     if (!document.$formname.usernamelink.length) {
 2948:         target = document.$formname.usernamelink.value;
 2949:     } else {
 2950:         for (var i=0; i<document.$formname.usernamelink.length; i++) {
 2951:             if (document.$formname.usernamelink[i].checked) {
 2952:                target = document.$formname.usernamelink[i].value;
 2953:             }
 2954:         }
 2955:     }
 2956:     if ((target == 'modify') || (target == 'activity')) {
 2957:         var nextaction = 'singleuser';
 2958:         if (target == 'activity') {
 2959:             nextaction = 'accesslogs';
 2960:         }
 2961:         if (document.$formname.userwin.checked == true) {
 2962:             var url = '/adm/createuser?srchterm='+username+'&srchdomain='+domain+'&phase=get_user_info&srchin=dom&srchby=uname&srchtype=exact&popup=1&action='+nextaction;
 2963:             var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2964:             modifywin = window.open(url,'',options,1);
 2965:             modifywin.focus();
 2966:             return;
 2967:         } else {
 2968:             document.$formname.srchterm.value=username;
 2969:             document.$formname.srchdomain.value=domain;
 2970:             document.$formname.phase.value='get_user_info';
 2971:             document.$formname.action.value = nextaction;
 2972:             document.$formname.submit();
 2973:         }
 2974:     }
 2975:     if (target == 'aboutme') {
 2976:         if (document.$formname.userwin.checked == true) {
 2977:             var url = '/adm/'+domain+'/'+username+'/aboutme?popup=1';
 2978:             var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2979:             aboutmewin = window.open(url,'',options,1);
 2980:             aboutmewin.focus();
 2981:             return;
 2982:         } else {
 2983:             document.location.href = '/adm/'+domain+'/'+username+'/aboutme';
 2984:         }
 2985:     }
 2986:     if (target == 'track') {
 2987:         if (document.$formname.userwin.checked == true) {
 2988:             var url = '/adm/trackstudent?selected_student='+username+':'+domain+'&only_body=1';
 2989:             var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2990:             var trackwin = window.open(url,'',options,1);
 2991:             trackwin.focus();
 2992:             return;
 2993:         } else {
 2994:             document.location.href = '/adm/trackstudent?selected_student='+username+':'+domain;
 2995:         }
 2996:     }
 2997: }
 2998: // ]]>
 2999: </script>
 3000: $date_sec_selector
 3001: <input type="hidden" name="state" value="$env{'form.state'}" />
 3002: END
 3003:     }
 3004:     $r->print(<<END);
 3005: <input type="hidden" name="sortby" value="$sortby" />
 3006: END
 3007:     my @cols = &infocolumns($context,$mode,$showcredits);
 3008:     my %coltxt = &get_column_names($context);
 3009:     my %acttxt = &Apache::lonlocal::texthash(
 3010:                        'pr'         => "Proceed",
 3011:                        'ac'         => "Action to take for selected users",
 3012:                        'link'       => "Behavior of clickable username link for each user",
 3013:                        'aboutme'    => "Display a user's personal information page",
 3014:                        'owin'       => "Open in a new window",
 3015:                        'modify'     => "Modify a user's information",
 3016:                        'track'      => "View a user's recent activity",
 3017:                        'activity'   => "View a user's access log", 
 3018:                       );
 3019:     my %lt = (%coltxt,%acttxt);
 3020:     my $rolefilter = $env{'form.showrole'};
 3021:     if ($env{'form.showrole'} eq 'cr') {
 3022:         $rolefilter = &mt('custom');  
 3023:     } elsif ($env{'form.showrole'} ne 'Any') {
 3024:         $rolefilter = &Apache::lonnet::plaintext($env{'form.showrole'},$crstype);
 3025:     }
 3026:     my $results_description;
 3027:     if ($mode ne 'autoenroll') {
 3028:         $results_description = &results_header_row($rolefilter,$statusmode,
 3029:                                                    $context,$permission,$mode,$crstype);
 3030:         $r->print('<b>'.$results_description.'</b><br clear="all" />');
 3031:     }
 3032:     my ($output,$actionselect,%canchange,%canchangesec);
 3033:     if ($mode eq 'html' || $mode eq 'view' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
 3034:         if ($mode ne 'autoenroll' && $mode ne 'pickauthor') {
 3035:             if ($permission->{'cusr'}) {
 3036:                 unless (($context eq 'domain') && 
 3037:                         (($setting eq 'course') || ($setting eq 'community'))) {
 3038:                     $actionselect = 
 3039:                         &select_actions($context,$setting,$statusmode,$formname);
 3040:                 }
 3041:             }
 3042:             $r->print(<<END);
 3043: <input type="hidden" name="srchby"  value="uname" />
 3044: <input type="hidden" name="srchin"   value="dom" />
 3045: <input type="hidden" name="srchtype" value="exact" />
 3046: <input type="hidden" name="srchterm" value="" />
 3047: <input type="hidden" name="srchdomain" value="" /> 
 3048: END
 3049:             if ($actionselect) {
 3050:                 $output .= <<"END";
 3051: <div class="LC_left_float"><fieldset><legend>$lt{'ac'}</legend>
 3052: $actionselect
 3053: <br/><br /><input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.$formname.actionlist)" /> &nbsp;
 3054: <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.$formname.actionlist)" /><br /><input type="button" value="$lt{'pr'}" onclick="javascript:verify_action('actionlist')" /></fieldset></div>
 3055: END
 3056:                 my @allroles;
 3057:                 if ($env{'form.showrole'} eq 'Any') {
 3058:                     my $custom = 1;
 3059:                     if ($context eq 'domain') {
 3060:                         @allroles = &roles_by_context($setting,$custom,$crstype);
 3061:                     } else {
 3062:                         @allroles = &roles_by_context($context,$custom,$crstype);
 3063:                     }
 3064:                 } else {
 3065:                     @allroles = ($env{'form.showrole'});
 3066:                 }
 3067:                 foreach my $role (@allroles) {
 3068:                     if ($context eq 'domain') {
 3069:                         if ($setting eq 'domain') {
 3070:                             if (&Apache::lonnet::allowed('c'.$role,
 3071:                                     $env{'request.role.domain'})) {
 3072:                                 $canchange{$role} = 1;
 3073:                             }
 3074:                         } elsif ($setting eq 'author') {
 3075:                             if (&Apache::lonnet::allowed('c'.$role,
 3076:                                     $env{'request.role.domain'})) {
 3077:                                 $canchange{$role} = 1;
 3078:                             }
 3079:                         }
 3080:                     } elsif ($context eq 'author') {
 3081:                         if (&Apache::lonnet::allowed('c'.$role,
 3082:                             $env{'user.domain'}.'/'.$env{'user.name'})) {
 3083:                             $canchange{$role} = 1;
 3084:                         }
 3085:                     } elsif ($context eq 'course') {
 3086:                         if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
 3087:                             $canchange{$role} = 1;
 3088:                         } elsif ($env{'request.course.sec'} ne '') {
 3089:                             if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
 3090:                                 $canchangesec{$role} = $env{'request.course.sec'};
 3091:                             }
 3092:                         } elsif ((($role eq 'co') && ($crstype eq 'Community')) ||
 3093:                                  (($role eq 'cc') && ($crstype eq 'Course'))) {
 3094:                             if (&is_courseowner($env{'request.course.id'},
 3095:                                                 $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'})) {
 3096:                                 $canchange{$role} = 1;
 3097:                             }
 3098:                         }
 3099:                     }
 3100:                 }
 3101:             }
 3102:             $output .= '<div class="LC_left_float"><fieldset><legend>'.$lt{'link'}.'</legend>'.
 3103:                        '<table><tr>';
 3104:             my @linkdests = ('aboutme');
 3105:             if ($permission->{'cusr'}) {
 3106:                 unshift (@linkdests,'modify');
 3107:             }
 3108:             if ($context eq 'course') {
 3109:                 if (&Apache::lonnet::allowed('vsa', $env{'request.course.id'}) ||
 3110:                     &Apache::lonnet::allowed('vsa', $env{'request.course.id'}.'/'.
 3111:                                              $env{'request.course.sec'})) {
 3112:                     push(@linkdests,'track');
 3113:                 }
 3114:             } elsif ($context eq 'domain') {
 3115:                 if (&Apache::lonnet::allowed('vac',$env{'request.role.domain'})) {
 3116:                     push(@linkdests,'activity');
 3117:                 }
 3118:             }
 3119:             $output .= '<td>';
 3120:             my $usernamelink = $env{'form.usernamelink'};
 3121:             if ($usernamelink eq '') {
 3122:                 $usernamelink = 'aboutme';
 3123:             }
 3124:             foreach my $item (@linkdests) {
 3125:                 my $checkedstr = '';
 3126:                 if ($item eq $usernamelink) {
 3127:                     $checkedstr = ' checked="checked"';
 3128:                 }
 3129:                 $output .= '<span class="LC_nobreak"><label><input type="radio" name="usernamelink" value="'.$item.'"'.$checkedstr.' />&nbsp;'.$lt{$item}.'</label></span><br />';
 3130:             }
 3131:             my $checkwin;
 3132:             if ($env{'form.userwin'}) {
 3133:                 $checkwin = ' checked="checked"';
 3134:             }
 3135:             $output .=
 3136:                 '</td><td valign="top"  style="border-left: 1px solid;">'
 3137:                .'<span class="LC_nobreak"><label>'
 3138:                .'<input type="checkbox" name="userwin" value="1"'.$checkwin.' />'.$lt{'owin'}
 3139:                .'</label></span></td></tr></table></fieldset></div>';
 3140:         }
 3141:         $output .= "\n".'<div style="padding:0;clear:both;margin:0;border:0"></div>'."\n".
 3142:                   &Apache::loncommon::start_data_table().
 3143:                   &Apache::loncommon::start_data_table_header_row();
 3144:         if ($mode eq 'autoenroll') {
 3145:             $output .= "
 3146:  <th><a href=\"javascript:document.$formname.sortby.value='type';document.$formname.submit();\">$lt{'type'}</a></th>
 3147:             ";
 3148:         } else {
 3149:             $output .= "\n".'<th>&nbsp;</th>'."\n";
 3150:             if ($actionselect) {
 3151:                 $output .= '<th class="LC_nobreak" valign="top">'.&mt('Select').'</th>'."\n";
 3152:             }
 3153:         }
 3154:         foreach my $item (@cols) {
 3155:             $output .= '<th class="LC_nobreak" valign="top">';
 3156:             if ($is_sortable{$item}) {
 3157:                 $output .= "<a href=\"javascript:document.$formname.sortby.value='$item';document.$formname.submit();\" style=\"text-decoration:none;\">$lt{$item}<span class=\"LC_fontsize_small\"> &#9660;</span></a>";
 3158:             } else {
 3159:                 $output .= $lt{$item};
 3160:             }
 3161:             $output .= "</th>\n";
 3162:         }
 3163:         my %role_types = &role_type_names();
 3164:         $output .= &Apache::loncommon::end_data_table_header_row();
 3165: # Done with the HTML header line
 3166:     } elsif ($mode eq 'csv') {
 3167:         #
 3168:         # Open a file
 3169:         $CSVfilename = '/prtspool/'.
 3170:                        $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 3171:                        time.'_'.rand(1000000000).'.csv';
 3172:         unless ($CSVfile = Apache::File->new('>/home/httpd'.$CSVfilename)) {
 3173:             $r->log_error("Couldn't open $CSVfilename for output $!");
 3174:             $r->print(
 3175:                 '<p class="LC_error">'
 3176:                .&mt('Problems occurred in writing the CSV file.')
 3177:                .' '.&mt('This error has been logged.')
 3178:                .' '.&mt('Please alert your LON-CAPA administrator.')
 3179:                .'</p>'
 3180:             );
 3181:             $CSVfile = undef;
 3182:         }
 3183:         #
 3184:         # Write headers and data to file
 3185:         print $CSVfile '"'.$results_description.'"'."\n"; 
 3186:         print $CSVfile '"'.join('","',map {
 3187:             &Apache::loncommon::csv_translate($lt{$_})
 3188:             } (@cols))."\"\n";
 3189:     } elsif ($mode eq 'excel') {
 3190:         # Create the excel spreadsheet
 3191:         ($excel_workbook,$excel_filename,$format) =
 3192:             &Apache::loncommon::create_workbook($r);
 3193:         return if (! defined($excel_workbook));
 3194:         $excel_sheet = $excel_workbook->addworksheet('userlist');
 3195:         $excel_sheet->write($row++,0,$results_description,$format->{'h2'});
 3196:         #
 3197:         my @colnames = map {$lt{$_}} (@cols);
 3198: 
 3199:         $excel_sheet->write($row++,0,\@colnames,$format->{'bold'});
 3200:     }
 3201: 
 3202: # Done with header lines in all formats
 3203:     my %index;
 3204:     my $i;
 3205:     foreach my $idx (@$keylist) {
 3206:         $index{$idx} = $i++;
 3207:     }
 3208:     my $usercount = 0;
 3209:     my ($secfilter,$grpfilter);
 3210:     if ($context eq 'course') {
 3211:         $secfilter = $env{'form.secfilter'};
 3212:         $grpfilter = $env{'form.grpfilter'};
 3213:         if ($secfilter eq '') {
 3214:             $secfilter = 'all';
 3215:         }
 3216:         if ($grpfilter eq '') {
 3217:             $grpfilter = 'all';
 3218:         }
 3219:     }
 3220:     my %ltstatus = &Apache::lonlocal::texthash(
 3221:                                                 Active  => 'Active',
 3222:                                                 Future  => 'Future',
 3223:                                                 Expired => 'Expired',
 3224:                                                );
 3225:     # If this is for a single course get last course "log-in".
 3226:     my %crslogins;
 3227:     if ($context eq 'course') {
 3228:         %crslogins=&Apache::lonnet::dump('nohist_crslastlogin',$cdom,$cnum);
 3229:     }
 3230:     # Get groups, role, permanent e-mail so we can sort on them if
 3231:     # necessary.
 3232:     foreach my $user (keys(%{$userlist})) {
 3233:         if ($user eq '' ) {
 3234:             delete($userlist->{$user});
 3235:             next;
 3236:         }
 3237:         if ($context eq 'domain' &&  $user eq $env{'request.role.domain'}.'-domainconfig:'.$env{'request.role.domain'}) {
 3238:             delete($userlist->{$user});
 3239:             next;
 3240:         }
 3241:         my ($uname,$udom,$role,$groups,$email);
 3242:         if (($statusmode ne 'Any') && 
 3243:                  ($userlist->{$user}->[$index{'status'}] ne $statusmode)) {
 3244:             delete($userlist->{$user});
 3245:             next;
 3246:         }
 3247:         if ($context eq 'domain') {
 3248:             if ($env{'form.roletype'} eq 'domain') {
 3249:                 ($role,$uname,$udom) = split(/:/,$user);
 3250:                 if (($uname eq $env{'request.role.domain'}.'-domainconfig') &&
 3251:                     ($udom eq $env{'request.role.domain'})) {
 3252:                     delete($userlist->{$user});
 3253:                     next;
 3254:                 }
 3255:             } elsif ($env{'form.roletype'} eq 'author') {
 3256:                 ($uname,$udom,$role) = split(/:/,$user,-1);
 3257:             } elsif (($env{'form.roletype'} eq 'course') || 
 3258:                      ($env{'form.roletype'} eq 'community')) {
 3259:                 ($uname,$udom,$role) = split(/:/,$user);
 3260:             }
 3261:         } else {
 3262:             ($uname,$udom,$role) = split(/:/,$user,-1);
 3263:             if (($context eq 'course') && $role eq '') {
 3264:                 $role = 'st';
 3265:             }
 3266:         }
 3267:         $userlist->{$user}->[$index{'role'}] = $role;
 3268:         if (($env{'form.showrole'} ne 'Any') && (!($env{'form.showrole'}  eq 'cr' && $role =~ /^cr\//)) && ($role ne $env{'form.showrole'})) {
 3269:             delete($userlist->{$user});
 3270:             next;
 3271:         }
 3272:         if ($context eq 'course') {
 3273:             my @ac_groups;
 3274:             if (ref($classgroups) eq 'HASH') {
 3275:                 $groups = $classgroups->{$user};
 3276:             }
 3277:             if (ref($groups->{'active'}) eq 'HASH') {
 3278:                 @ac_groups = keys(%{$groups->{'active'}});
 3279:                 $userlist->{$user}->[$index{'groups'}] = join(', ',@ac_groups);
 3280:             }
 3281:             if ($mode ne 'autoenroll') {
 3282:                 my $section = $userlist->{$user}->[$index{'section'}];
 3283:                 if (($env{'request.course.sec'} ne '') && 
 3284:                     ($section ne $env{'request.course.sec'})) {
 3285:                     if ($role eq 'st') {
 3286:                         delete($userlist->{$user});
 3287:                         next;
 3288:                     }
 3289:                 }
 3290:                 if ($secfilter eq 'none') {
 3291:                     if ($section ne '') {
 3292:                         delete($userlist->{$user});
 3293:                         next;
 3294:                     }
 3295:                 } elsif ($secfilter ne 'all') {
 3296:                     if ($section ne $secfilter) {
 3297:                         delete($userlist->{$user});
 3298:                         next;
 3299:                     }
 3300:                 }
 3301:                 if ($grpfilter eq 'none') {
 3302:                     if (@ac_groups > 0) {
 3303:                         delete($userlist->{$user});
 3304:                         next;
 3305:                     }
 3306:                 } elsif ($grpfilter ne 'all') {
 3307:                     if (!grep(/^\Q$grpfilter\E$/,@ac_groups)) {
 3308:                         delete($userlist->{$user});
 3309:                         next;
 3310:                     }
 3311:                 }
 3312:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3313:                     if ((grep/^photo$/,@cols) && ($role eq 'st')) {
 3314:                         $userlist->{$user}->[$index{'photo'}] =
 3315:                             &Apache::lonnet::retrievestudentphoto($udom,$uname,'jpg');
 3316:                         $userlist->{$user}->[$index{'thumbnail'}] =
 3317:                             &Apache::lonnet::retrievestudentphoto($udom,$uname,
 3318:                                                                 'gif','thumbnail');
 3319:                     }
 3320:                 }
 3321:                 if (($role eq 'st') && ($defaultcredits)) {
 3322:                     if ($userlist->{$user}->[$index{'credits'}] eq '') {
 3323:                         $userlist->{$user}->[$index{'credits'}] = $defaultcredits;
 3324:                     }
 3325:                 }
 3326:             }
 3327:         }
 3328:         my %emails   = &Apache::loncommon::getemails($uname,$udom);
 3329:         if ($emails{'permanentemail'} =~ /\S/) {
 3330:             $userlist->{$user}->[$index{'email'}] = $emails{'permanentemail'};
 3331:         }
 3332:         if (($context eq 'domain') && ($env{'form.roletype'} eq 'domain') && 
 3333:             ($role eq 'au')) {
 3334:             my ($disk_quota,$current_disk_usage,$percent); 
 3335:             if (($needauthorusage) || ($needauthorquota)) {
 3336:                 $disk_quota = &Apache::loncommon::get_user_quota($uname,$udom,'author');
 3337:             }
 3338:             if ($needauthorusage) {
 3339:                 $current_disk_usage =
 3340:                     &Apache::lonnet::diskusage($udom,$uname,"$londocroot/priv/$udom/$uname");
 3341:                 if ($disk_quota == 0) {
 3342:                     $percent = 100.0;
 3343:                 } else {
 3344:                     $percent = $current_disk_usage/(10 * $disk_quota);
 3345:                 }
 3346:                 $userlist->{$user}->[$index{'authorusage'}] = sprintf("%.0f",$percent);
 3347:             }
 3348:             if ($needauthorquota) {
 3349:                 $userlist->{$user}->[$index{'authorquota'}] = sprintf("%.2f",$disk_quota);
 3350:             }
 3351:         }
 3352:         $usercount ++;
 3353:     }
 3354:     my $autocount = 0;
 3355:     my $manualcount = 0;
 3356:     my $lockcount = 0;
 3357:     my $unlockcount = 0;
 3358:     if ($usercount) {
 3359:         $r->print($output);
 3360:     } else {
 3361:         if ($mode eq 'autoenroll') {
 3362:             return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
 3363:         } else {
 3364:             return;
 3365:         }
 3366:     }
 3367:     #
 3368:     # Sort the users
 3369:     my $index  = $index{$sortby};
 3370:     my $second = $index{'username'};
 3371:     my $third  = $index{'domain'};
 3372:     my @sorted_users;
 3373:     if (($sortby eq 'authorquota') || ($sortby eq 'authorusage')) {  
 3374:         @sorted_users = sort {
 3375:             $userlist->{$b}->[$index] <=> $userlist->{$a}->[$index]           ||
 3376:             lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second]) ||
 3377:             lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
 3378:             } (keys(%$userlist));
 3379:     } else {
 3380:         @sorted_users = sort {
 3381:             lc($userlist->{$a}->[$index]) cmp lc($userlist->{$b}->[$index])   ||
 3382:             lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second]) ||
 3383:             lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
 3384:             } (keys(%$userlist));
 3385:     }
 3386:     my $rowcount = 0;
 3387:     my $disabled;
 3388:     if ($mode eq 'autoenroll') {
 3389:         unless ($permission->{'cusr'}) {
 3390:             $disabled = ' disabled="disabled"';
 3391:         }
 3392:     }
 3393:     foreach my $user (@sorted_users) {
 3394:         my %in;
 3395:         my $sdata = $userlist->{$user};
 3396:         $rowcount ++; 
 3397:         foreach my $item (@{$keylist}) {
 3398:             $in{$item} = $sdata->[$index{$item}];
 3399:         }
 3400:         my $clickers = (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
 3401:         if ($clickers!~/\w/) { $clickers='-'; }
 3402:         $in{'clicker'} = $clickers;
 3403: 	my $role = $in{'role'};
 3404:         $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}],$crstype);
 3405:         unless ($mode eq 'excel') {
 3406:             if (! defined($in{'start'}) || $in{'start'} == 0) {
 3407:                 $in{'start'} = &mt('none');
 3408:             } else {
 3409:                 $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
 3410:             }
 3411:             if (! defined($in{'end'}) || $in{'end'} == 0) {
 3412:                 $in{'end'} = &mt('none');
 3413:             } else {
 3414:                 $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
 3415:             }
 3416:         }
 3417:         if ($context eq 'course') {
 3418:             my $lastlogin = $crslogins{$in{'username'}.':'.$in{'domain'}.':'.$in{'section'}.':'.$role};
 3419:             if ($lastlogin ne '') {
 3420:                 $in{'lastlogin'} = &Apache::lonlocal::locallocaltime($lastlogin);
 3421:             }
 3422:         }
 3423:         if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
 3424:             $r->print(&Apache::loncommon::start_data_table_row());
 3425:             my $checkval;
 3426:             if ($mode eq 'autoenroll') {
 3427:                 my $cellentry;
 3428:                 if ($in{'type'} eq 'auto') {
 3429:                     $cellentry = '<b>'.&mt('auto').'</b>&nbsp;<label><input type="checkbox" name="chgauto" value="'.$in{'username'}.':'.$in{'domain'}.'"'.$disabled.' />&nbsp;'.&mt('Change').'</label>';
 3430:                     $autocount ++;
 3431:                 } else {
 3432:                     $cellentry = '<table border="0" cellspacing="0"><tr><td rowspan="2"><b>'.&mt('manual').'</b></td><td><span class="LC_nobreak"><label><input type="checkbox" name="chgmanual" value="'.$in{'username'}.':'.$in{'domain'}.'"'.$disabled.' />&nbsp;'.&mt('Change').'</label></span></td></tr><tr><td><span class="LC_nobreak">';
 3433:                     $manualcount ++;
 3434:                     if ($in{'lockedtype'}) {
 3435:                         $cellentry .= '<label><input type="checkbox" name="unlockchg" value="'.$in{'username'}.':'.$in{'domain'}.'"'.$disabled.' />&nbsp;'.&mt('Unlock').'</label>';
 3436:                         $unlockcount ++;
 3437:                     } else {
 3438:                         $cellentry .= '<label><input type="checkbox" name="lockchg" value="'.$in{'username'}.':'.$in{'domain'}.'"'.$disabled.' />&nbsp;'.&mt('Lock').'</label>';
 3439:                         $lockcount ++;
 3440:                     }
 3441:                     $cellentry .= '</span></td></tr></table>';
 3442:                 }
 3443:                 $r->print("<td>$cellentry</td>\n");
 3444:             } else {
 3445:                 if ($mode ne 'pickauthor') {  
 3446:                     $r->print("<td>$rowcount</td>\n");
 3447:                 }
 3448:                 if ($actionselect) {
 3449:                     my $showcheckbox;
 3450:                     if ($role =~ /^cr\//) {
 3451:                         $showcheckbox = $canchange{'cr'};
 3452:                     } else {
 3453:                         $showcheckbox = $canchange{$role};
 3454:                     }
 3455:                     if (!$showcheckbox) {
 3456:                         if ($context eq 'course') {
 3457:                             if ($canchangesec{$role} ne '') {
 3458:                                 if ($canchangesec{$role} eq $in{'section'}) {
 3459:                                     $showcheckbox = 1;
 3460:                                 }
 3461:                             }
 3462:                         }
 3463:                     }
 3464:                     if ($showcheckbox) {
 3465:                         $checkval = $user; 
 3466:                         if ($context eq 'course') {
 3467:                             if (($role eq 'co' || $role eq 'cc') &&
 3468:                                 ($user =~ /^\Q$env{'user.name'}:$env{'user.domain'}:$role\E/)) {
 3469:                                 $showcheckbox = 0;
 3470:                             } else {
 3471:                                 if ($role eq 'st') {
 3472:                                     $checkval .= ':st';
 3473:                                 }
 3474:                                 $checkval .= ':'.$in{'section'};
 3475:                                 if ($role eq 'st') {
 3476:                                     $checkval .= ':'.$in{'type'}.':'.
 3477:                                                  $in{'lockedtype'}.':'.
 3478:                                                  $in{'credits'}.':'.
 3479:                                                  &escape($in{'instsec'});
 3480:                                 }
 3481:                              }
 3482:                         }
 3483:                         if ($showcheckbox) {
 3484:                             $r->print('<td><input type="checkbox" name="'.
 3485:                                       'actionlist" value="'.
 3486:                                       &HTML::Entities::encode($checkval,'&<>"').'" />');
 3487:                             foreach my $item ('start','end') {
 3488:                                 $r->print('<input type="hidden" name="'.
 3489:                                           &HTML::Entities::encode($checkval.'_'.$item,'&<>"').'"'.
 3490:                                           ' value="'.$sdata->[$index{$item}].'" />');
 3491:                             }
 3492:                             $r->print('</td>');
 3493:                         } else {
 3494:                             $r->print('<td>&nbsp;</td>');
 3495:                         }
 3496:                     } else {
 3497:                         $r->print('<td>&nbsp;</td>');
 3498:                     }
 3499:                 } elsif ($mode eq 'pickauthor') {
 3500:                         $r->print('<td><input type="button" name="chooseauthor" onclick="javascript:gochoose('."'$in{'username'}'".');" value="'.&mt('Select').'" /></td>');
 3501:                 }
 3502:             }
 3503:             foreach my $item (@cols) {
 3504:                 if ($item eq 'username') {
 3505:                     $r->print('<td>'.&print_username_link($mode,\%in).'</td>');
 3506:                 } elsif ($item eq 'status') {
 3507:                     my $showitem = $in{$item};
 3508:                     if (defined($ltstatus{$in{$item}})) {
 3509:                         $showitem = $ltstatus{$in{$item}};
 3510:                     }
 3511:                     $r->print('<td>'.$showitem.'</td>'."\n");
 3512:                 } elsif ($item eq 'photo') {
 3513:                      if (($context eq 'course') && ($mode ne 'autoenroll') && 
 3514:                          ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'})) { 
 3515:                          if ($role eq 'st') {
 3516:                              $r->print('<td align="right"><a href="javascript:photowindow('."'".$in{'photo'}."'".')"><img src="'.$in{'thumbnail'}.'" border="1" alt="" /></a></td>');
 3517:                          } else {
 3518:                              $r->print('<td>&nbsp;</td>');
 3519:                          }
 3520:                      }
 3521:                 } elsif ($item eq 'clicker') {
 3522:                     if (($context eq 'course') && ($mode ne 'autoenroll')) {
 3523:                         if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
 3524:                             my $clickers =
 3525:                    (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
 3526:                             if ($clickers!~/\w/) { $clickers='-'; }
 3527:                             $r->print('<td>'.$clickers.'</td>');
 3528:                         } else {
 3529:                              $r->print('<td>&nbsp;</td>'."\n");
 3530:                         } 
 3531:                     }
 3532:                 } elsif (($item eq 'authorquota') || ($item eq 'authorusage')) {
 3533:                     $r->print('<td align="right">'.$in{$item}.'</td>'."\n");
 3534:                 } else {
 3535:                     $r->print('<td>'.$in{$item}.'</td>'."\n");
 3536:                 }
 3537:             }
 3538:             $r->print(&Apache::loncommon::end_data_table_row());
 3539:         } elsif ($mode eq 'csv') {
 3540:             next if (! defined($CSVfile));
 3541:             # no need to bother with $linkto
 3542:             my @line = ();
 3543:             foreach my $item (@cols) {
 3544:                 push @line,&Apache::loncommon::csv_translate($in{$item});
 3545:             }
 3546:             print $CSVfile '"'.join('","',@line)."\"\n";
 3547:         } elsif ($mode eq 'excel') {
 3548:             my $col = 0;
 3549:             foreach my $item (@cols) {
 3550:                 if ($item eq 'start' || $item eq 'end') {
 3551:                     if ((defined($in{$item})) && ($in{$item} != 0)) {
 3552:                         $excel_sheet->write($row,$col++,
 3553:                             &Apache::lonstathelpers::calc_serial($in{$item}),
 3554:                                     $format->{'date'});
 3555:                     } else {
 3556:                         $excel_sheet->write($row,$col++,'none');
 3557:                     }
 3558:                 } else {
 3559:                     $excel_sheet->write($row,$col++,$in{$item});
 3560:                 }
 3561:             }
 3562:             $row++;
 3563:         }
 3564:     }
 3565:     if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
 3566:             $r->print(&Apache::loncommon::end_data_table().'<br />');
 3567:     } elsif ($mode eq 'excel') {
 3568:         $excel_workbook->close();
 3569: 	$r->print('<p>'.&mt('[_1]Your Excel spreadsheet[_2] is ready for download.', '<a href="'.$excel_filename.'">','</a>')."</p>\n");
 3570:     } elsif ($mode eq 'csv') {
 3571:         close($CSVfile);
 3572: 	$r->print('<p>'.&mt('[_1]Your CSV file[_2] is ready for download.', '<a href="'.$CSVfilename.'">','</a>')."</p>\n");
 3573:         $r->rflush();
 3574:     }
 3575:     if ($mode eq 'autoenroll') {
 3576:         return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
 3577:     } else {
 3578:         return ($usercount);
 3579:     }
 3580: }
 3581: 
 3582: sub bulkaction_javascript {
 3583:     my ($formname,$caller) = @_;
 3584:     my $docstart = 'document';
 3585:     if ($caller eq 'popup') {
 3586:         $docstart = 'opener.document';
 3587:     }
 3588:     my %lt = &Apache::lonlocal::texthash(
 3589:               acwi => 'Access will be set to start immediately',
 3590:               asyo => 'as you did not select an end date in the pop-up window',
 3591:               accw => 'Access will be set to continue indefinitely',
 3592:               asyd => 'as you did not select an end date in the pop-up window',
 3593:               sewi => "Sections will be switched to 'No section'",
 3594:               ayes => "as you either selected the 'No section' option",
 3595:               oryo => 'or you did not select a section in the pop-up window',
 3596:               arol => 'A role with no section will be added',
 3597:               swbs => 'Sections will be switched to:',
 3598:               rwba => 'Roles will be added for section(s):',
 3599:             );
 3600:     my $alert = &mt("You must select at least one user by checking a user's 'Select' checkbox");
 3601:     my $noaction = &mt("You need to select an action to take for the user(s) you have selected"); 
 3602:     my $singconfirm = &mt(' for a single user?');
 3603:     my $multconfirm = &mt(' for multiple users?');
 3604:     &js_escape(\$alert);
 3605:     &js_escape(\$noaction);
 3606:     &js_escape(\$singconfirm);
 3607:     &js_escape(\$multconfirm);
 3608:     my $output = <<"ENDJS";
 3609: function verify_action (field) {
 3610:     var numchecked = 0;
 3611:     var singconf = '$singconfirm';
 3612:     var multconf = '$multconfirm';
 3613:     if ($docstart.$formname.elements[field].length > 0) {
 3614:         for (i=0; i<$docstart.$formname.elements[field].length; i++) {
 3615:             if ($docstart.$formname.elements[field][i].checked == true) {
 3616:                numchecked ++;
 3617:             }
 3618:         }
 3619:     } else {
 3620:         if ($docstart.$formname.elements[field].checked == true) {
 3621:             numchecked ++;
 3622:         }
 3623:     }
 3624:     if (numchecked == 0) {
 3625:         alert("$alert");
 3626:         return;
 3627:     } else {
 3628:         var message = $docstart.$formname.bulkaction[$docstart.$formname.bulkaction.selectedIndex].text;
 3629:         var choice = $docstart.$formname.bulkaction[$docstart.$formname.bulkaction.selectedIndex].value;
 3630:         if (choice == '') {
 3631:             alert("$noaction");
 3632:             return;
 3633:         } else {
 3634:             if (numchecked == 1) {
 3635:                 message += singconf;
 3636:             } else {
 3637:                 message += multconf;
 3638:             }
 3639: ENDJS
 3640:     if ($caller ne 'popup') {
 3641:         $output .= <<"NEWWIN";
 3642:             if (choice == 'chgdates' || choice == 'reenable' || choice == 'activate' || choice == 'chgsec') {
 3643:                 opendatebrowser(document.$formname,'$formname','go');
 3644:                 return;
 3645: 
 3646:             } else {
 3647:                 if (confirm(message)) {
 3648:                     document.$formname.phase.value = 'bulkchange';
 3649:                     document.$formname.submit();
 3650:                     return;
 3651:                 }
 3652:             }
 3653: NEWWIN
 3654:     } else {
 3655:         $output .= <<"POPUP";
 3656:             if (choice == 'chgdates' || choice == 'reenable' || choice == 'activate') {
 3657:                 var datemsg = '';
 3658:                 if (($docstart.$formname.startdate_month.value == '') &&
 3659:                     ($docstart.$formname.startdate_day.value  == '') &&
 3660:                     ($docstart.$formname.startdate_year.value == '')) {
 3661:                     datemsg = "\\n$lt{'acwi'},\\n$lt{'asyo'}.\\n";
 3662:                 }
 3663:                 if (($docstart.$formname.enddate_month.value == '') &&
 3664:                     ($docstart.$formname.enddate_day.value  == '') &&
 3665:                     ($docstart.$formname.enddate_year.value == '')) {
 3666:                     datemsg += "\\n$lt{'accw'},\\n$lt{'asyd'}.\\n";
 3667:                 }
 3668:                 if (datemsg != '') {
 3669:                     message += "\\n"+datemsg;
 3670:                 }
 3671:             }
 3672:             if (choice == 'chgsec') {
 3673:                 var rolefilter = $docstart.$formname.showrole.options[$docstart.$formname.showrole.selectedIndex].value;
 3674:                 var retained =  $docstart.$formname.retainsec.value;
 3675:                 var secshow = $docstart.$formname.newsecs.value;
 3676:                 if (secshow == '') {
 3677:                     if (rolefilter == 'st' || retained == 0 || retained == "") {
 3678:                         message += "\\n\\n$lt{'sewi'},\\n$lt{'ayes'},\\n$lt{'oryo'}.\\n";
 3679:                     } else {
 3680:                         message += "\\n\\n$lt{'arol'}\\n$lt{'ayes'},\\n$lt{'oryo'}.\\n";
 3681:                     }
 3682:                 } else {
 3683:                     if (rolefilter == 'st' || retained == 0 || retained == "") {
 3684:                         message += "\\n\\n$lt{'swbs'} "+secshow+".\\n";
 3685:                     } else {
 3686:                         message += "\\n\\n$lt{'rwba'} "+secshow+".\\n";
 3687:                     }
 3688:                 }
 3689:             }
 3690:             if (confirm(message)) {
 3691:                 $docstart.$formname.phase.value = 'bulkchange';
 3692:                 $docstart.$formname.submit();
 3693:                 window.close();
 3694:             }
 3695: POPUP
 3696:     }
 3697:     $output .= '
 3698:         }
 3699:     }
 3700: }
 3701: ';
 3702:     return $output;
 3703: }
 3704: 
 3705: sub print_username_link {
 3706:     my ($mode,$in) = @_;
 3707:     my $output;
 3708:     if ($mode eq 'autoenroll') {
 3709:         $output = $in->{'username'};
 3710:     } else {
 3711:         $output = '<a href="javascript:username_display_launch('.
 3712:                   "'$in->{'username'}','$in->{'domain'}'".')">'.
 3713:                   $in->{'username'}.'</a>';
 3714:     }
 3715:     return $output;
 3716: }
 3717: 
 3718: sub role_type_names {
 3719:     my %lt = &Apache::lonlocal::texthash (
 3720:                          'domain' => 'Domain Roles',
 3721:                          'author' => 'Co-Author Roles',
 3722:                          'course' => 'Course Roles',
 3723:                          'community' => 'Community Roles',
 3724:              );
 3725:     return %lt;
 3726: }
 3727: 
 3728: sub select_actions {
 3729:     my ($context,$setting,$statusmode,$formname) = @_;
 3730:     my %lt = &Apache::lonlocal::texthash(
 3731:                 revoke   => "Revoke user roles",
 3732:                 delete   => "Delete user roles",
 3733:                 reenable => "Re-enable expired user roles",
 3734:                 activate => "Make future user roles active now",
 3735:                 chgdates  => "Change starting/ending dates",
 3736:                 chgsec   => "Change section associated with user roles",
 3737:     );
 3738:     # FIXME Add an option to change credits for student roles.
 3739:     my ($output,$options,%choices);
 3740:     # FIXME Disable actions for now for roletype=course in domain context
 3741:     if ($context eq 'domain' && $setting eq 'course') {
 3742:         return;
 3743:     }
 3744:     if ($context eq 'course') {
 3745:         if ($env{'form.showrole'} ne 'Any') {
 3746:             my $showactions;
 3747:             if (&Apache::lonnet::allowed('c'.$env{'form.showrole'},
 3748:                                           $env{'request.course.id'})) {
 3749:                 $showactions = 1;  
 3750:             } elsif ($env{'request.course.sec'} ne '') {
 3751:                 if (&Apache::lonnet::allowed('c'.$env{'form.showrole'},$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
 3752:                     $showactions = 1;
 3753:                 }
 3754:             }
 3755:             unless ($showactions) {
 3756:                 unless (&is_courseowner($env{'request.course.id'},
 3757:                                        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'})) {
 3758:                     return; 
 3759:                 }
 3760:             }
 3761:         }
 3762:     }
 3763:     if ($statusmode eq 'Any') {
 3764:         $options .= '
 3765: <option value="chgdates">'.$lt{'chgdates'}.'</option>';
 3766:         $choices{'dates'} = 1;
 3767:     } else {
 3768:         if ($statusmode eq 'Future') {
 3769:             $options .= '
 3770: <option value="activate">'.$lt{'activate'}.'</option>';
 3771:             $choices{'dates'} = 1;
 3772:         } elsif ($statusmode eq 'Expired') {
 3773:             $options .= '
 3774: <option value="reenable">'.$lt{'reenable'}.'</option>';
 3775:             $choices{'dates'} = 1;
 3776:         }
 3777:         if ($statusmode eq 'Active' || $statusmode eq 'Future') {
 3778:             $options .= '
 3779: <option value="chgdates">'.$lt{'chgdates'}.'</option>
 3780: <option value="revoke">'.$lt{'revoke'}.'</option>';
 3781:             $choices{'dates'} = 1;
 3782:         }
 3783:     }
 3784:     if ($context eq 'domain') {
 3785:         $options .= '
 3786: <option value="delete">'.$lt{'delete'}.'</option>';
 3787:     }
 3788:     if (($context eq 'course') || ($context eq 'domain' && $setting eq 'course')) {
 3789:         if (($statusmode ne 'Expired') && ($env{'request.course.sec'} eq '')) {
 3790:             $options .= '
 3791: <option value="chgsec">'.$lt{'chgsec'}.'</option>';
 3792:             $choices{'sections'} = 1;
 3793:         }
 3794:     }
 3795:     if ($options) {
 3796:         $output = '<select name="bulkaction">'."\n".
 3797:                   '<option value="" selected="selected">'.
 3798:                   &mt('Please select').'</option>'."\n".$options."\n".'</select>';
 3799:         if ($choices{'dates'}) {
 3800:             $output .= 
 3801:                 '<input type="hidden" name="startdate_month" value="" />'."\n".
 3802:                 '<input type="hidden" name="startdate_day" value="" />'."\n".
 3803:                 '<input type="hidden" name="startdate_year" value="" />'."\n".
 3804:                 '<input type="hidden" name="startdate_hour" value="" />'."\n".
 3805:                 '<input type="hidden" name="startdate_minute" value="" />'."\n".
 3806:                 '<input type="hidden" name="startdate_second" value="" />'."\n".
 3807:                 '<input type="hidden" name="enddate_month" value="" />'."\n".
 3808:                 '<input type="hidden" name="enddate_day" value="" />'."\n".
 3809:                 '<input type="hidden" name="enddate_year" value="" />'."\n".
 3810:                 '<input type="hidden" name="enddate_hour" value="" />'."\n".
 3811:                 '<input type="hidden" name="enddate_minute" value="" />'."\n".
 3812:                 '<input type="hidden" name="enddate_second" value="" />'."\n".
 3813:                 '<input type="hidden" name="no_end_date" value="" />'."\n";
 3814:             if ($context eq 'course') {
 3815:                 $output .= '<input type="hidden" name="makedatesdefault" value="" />'."\n";
 3816:             }
 3817:         }
 3818:         if ($choices{'sections'}) {
 3819:             $output .= '<input type="hidden" name="retainsec" value="" />'."\n".
 3820:                        '<input type="hidden" name="newsecs" value="" />'."\n";
 3821:         }
 3822:     }
 3823:     return $output;
 3824: }
 3825: 
 3826: sub date_section_javascript {
 3827:     my ($context,$setting) = @_;
 3828:     my $title = 'Date_And_Section_Selector';
 3829:     my %nopopup = &Apache::lonlocal::texthash (
 3830:         revoke => "Check the boxes for any users for whom roles are to be revoked, and click 'Proceed'",
 3831:         delete => "Check the boxes for any users for whom roles are to be deleted, and click 'Proceed'",
 3832:         none   => "Choose an action to take for selected users",
 3833:     );  
 3834:     my $output = <<"ENDONE";
 3835: <script type="text/javascript">
 3836: // <![CDATA[
 3837:     function opendatebrowser(callingform,formname,calledby) {
 3838:         var bulkaction = callingform.bulkaction.options[callingform.bulkaction.selectedIndex].value;
 3839:         var url = '/adm/createuser?';
 3840:         var type = '';
 3841:         var showrole = callingform.showrole.options[callingform.showrole.selectedIndex].value;
 3842: ENDONE
 3843:     if ($context eq 'domain') {
 3844:         $output .= '
 3845:         type = callingform.roletype.options[callingform.roletype.selectedIndex].value;
 3846: ';
 3847:     }
 3848:     my $width= '700';
 3849:     my $height = '400';
 3850:     $output .= <<"ENDTWO";
 3851:         url += 'action=dateselect&callingform=' + formname + 
 3852:                '&roletype='+type+'&showrole='+showrole +'&bulkaction='+bulkaction;
 3853:         var title = '$title';
 3854:         var options = 'scrollbars=1,resizable=1,menubar=0';
 3855:         options += ',width=$width,height=$height';
 3856:         stdeditbrowser = open(url,title,options,'1');
 3857:         stdeditbrowser.focus();
 3858:     }
 3859: // ]]>
 3860: </script>
 3861: ENDTWO
 3862:     return $output;
 3863: }
 3864: 
 3865: sub date_section_selector {
 3866:     my ($context,$permission,$crstype,$showcredits) = @_;
 3867:     my $callingform = $env{'form.callingform'};
 3868:     my $formname = 'dateselect';  
 3869:     my $groupslist = &get_groupslist();
 3870:     my $sec_js =
 3871:         &setsections_javascript($formname,$groupslist,undef,undef,$crstype,
 3872:                                 $showcredits);
 3873:     my $output = <<"END";
 3874: <script type="text/javascript">
 3875: // <![CDATA[
 3876: 
 3877: $sec_js
 3878: 
 3879: function saveselections(formname) {
 3880: 
 3881: END
 3882:     if ($env{'form.bulkaction'} eq 'chgsec') {
 3883:         $output .= <<"END";
 3884:         if (formname.retainsec.length > 1) {  
 3885:             for (var i=0; i<formname.retainsec.length; i++) {
 3886:                 if (formname.retainsec[i].checked == true) {
 3887:                     opener.document.$callingform.retainsec.value = formname.retainsec[i].value;
 3888:                 }
 3889:             }
 3890:         } else {
 3891:             opener.document.$callingform.retainsec.value = formname.retainsec.value;
 3892:         }
 3893:         setSections(formname,'$crstype');
 3894:         if (seccheck == 'ok') {
 3895:             opener.document.$callingform.newsecs.value = formname.sections.value;
 3896:         } else {
 3897:             return;
 3898:         }
 3899: END
 3900:     } else {
 3901:         if ($context eq 'course') {
 3902:             if (($env{'form.bulkaction'} eq 'reenable') || 
 3903:                 ($env{'form.bulkaction'} eq 'activate') || 
 3904:                 ($env{'form.bulkaction'} eq 'chgdates')) {
 3905:                 if ($env{'request.course.sec'} eq '') {
 3906:                     $output .= <<"END";
 3907:  
 3908:         if (formname.makedatesdefault.checked == true) {
 3909:             opener.document.$callingform.makedatesdefault.value = 1;
 3910:         }
 3911:         else {
 3912:             opener.document.$callingform.makedatesdefault.value = 0;
 3913:         }
 3914: 
 3915: END
 3916:                 }
 3917:             }
 3918:         }
 3919:         $output .= <<"END";
 3920:     opener.document.$callingform.startdate_month.value =  formname.startdate_month.options[formname.startdate_month.selectedIndex].value;
 3921:     opener.document.$callingform.startdate_day.value =  formname.startdate_day.value;
 3922:     opener.document.$callingform.startdate_year.value = formname.startdate_year.value;
 3923:     opener.document.$callingform.startdate_hour.value =  formname.startdate_hour.options[formname.startdate_hour.selectedIndex].value;
 3924:     opener.document.$callingform.startdate_minute.value =  formname.startdate_minute.value;
 3925:     opener.document.$callingform.startdate_second.value = formname.startdate_second.value;
 3926:     opener.document.$callingform.enddate_month.value =  formname.enddate_month.options[formname.enddate_month.selectedIndex].value;
 3927:     opener.document.$callingform.enddate_day.value =  formname.enddate_day.value;
 3928:     opener.document.$callingform.enddate_year.value = formname.enddate_year.value;
 3929:     opener.document.$callingform.enddate_hour.value =  formname.enddate_hour.options[formname.enddate_hour.selectedIndex].value;
 3930:     opener.document.$callingform.enddate_minute.value =  formname.enddate_minute.value;
 3931:     opener.document.$callingform.enddate_second.value = formname.enddate_second.value;
 3932:     if (formname.no_end_date.checked) {
 3933:         opener.document.$callingform.no_end_date.value = '1';
 3934:     } else {
 3935:         opener.document.$callingform.no_end_date.value = '0';
 3936:     }
 3937: END
 3938:     }
 3939:     my $verify_action_js = &bulkaction_javascript($callingform,'popup');
 3940:     $output .= <<"ENDJS";
 3941:     verify_action('actionlist');
 3942: }
 3943: 
 3944: $verify_action_js
 3945: 
 3946: // ]]>
 3947: </script>
 3948: ENDJS
 3949:     my %lt = &Apache::lonlocal::texthash (
 3950:                  chac => 'Access dates to apply for selected users',
 3951:                  chse => 'Changes in section affiliation to apply to selected users',
 3952:                  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.',
 3953:                  forn => 'For a course role that is not "student", users may have roles in more than one section at a time.',
 3954:                  reta => "Retain each user's current section affiliations?",
 3955:                  dnap => '(Does not apply to student roles).',
 3956:             );
 3957:     my ($date_items,$headertext);
 3958:     if ($env{'form.bulkaction'} eq 'chgsec') {
 3959:         $headertext = $lt{'chse'};
 3960:     } else {
 3961:         $headertext = $lt{'chac'};
 3962:         my $starttime;
 3963:         if (($env{'form.bulkaction'} eq 'activate') || 
 3964:             ($env{'form.bulkaction'} eq 'reenable')) {
 3965:             $starttime = time;
 3966:         }
 3967:         $date_items = &date_setting_table($starttime,undef,$context,
 3968:                                           $env{'form.bulkaction'},$formname,
 3969:                                           $permission,$crstype);
 3970:     }
 3971:     $output .= '<h3>'.$headertext.'</h3>'.
 3972:                '<form name="'.$formname.'" method="post" action="">'."\n".
 3973:                 $date_items;
 3974:     if ($context eq 'course' && $env{'form.bulkaction'} eq 'chgsec') {
 3975:         my ($cnum,$cdom) = &get_course_identity();
 3976:         if ($crstype eq 'Community') {
 3977:             $lt{'fors'} = &mt('For member roles, changing the section will result in a section switch, as members may only be in one section of a community at a time.');
 3978:             $lt{'forn'} = &mt('For a community role that is not "member", users may have roles in more than one section at a time.');
 3979:             $lt{'dnap'} = &mt('(Does not apply to member roles).'); 
 3980:         }
 3981:         my $info;
 3982:         if ($env{'form.showrole'} eq 'st') {
 3983:             $output .= '<p>'.$lt{'fors'}.'</p>'; 
 3984:         } elsif ($env{'form.showrole'} eq 'Any') {
 3985:             $output .= '<p>'.$lt{'fors'}.'</p>'.
 3986:                        '<p>'.$lt{'forn'}.'&nbsp;';
 3987:             $info = $lt{'reta'};
 3988:         } else {
 3989:             $output .= '<p>'.$lt{'forn'}.'&nbsp;';
 3990:             $info = $lt{'reta'};
 3991:         }
 3992:         if ($info) {
 3993:             $info .= '<span class="LC_nobreak">'.
 3994:                      '<label><input type="radio" name="retainsec" value="1" '.
 3995:                      'checked="checked" />'.&mt('Yes').'</label>&nbsp;&nbsp;'.
 3996:                      '<label><input type="radio" name="retainsec" value="0" />'.
 3997:                      &mt('No').'</label></span>';
 3998:             if ($env{'form.showrole'} eq 'Any') {
 3999:                 $info .= '<br />'.$lt{'dnap'};
 4000:             }
 4001:             $info .= '</p>';
 4002:         } else {
 4003:             $info = '<input type="hidden" name="retainsec" value="0" />'; 
 4004:         }
 4005:         my $rowtitle = &mt('New section to assign');
 4006:         my $secbox = &section_picker($cdom,$cnum,$env{'form.showrole'},$rowtitle,
 4007:                                      $permission,$context,'chgsec',$crstype);
 4008:         $output .= $info.$secbox;
 4009:     }
 4010:     $output .= '<p>'.
 4011: '<input type="button" name="dateselection" value="'.&mt('Save').'" onclick="javascript:saveselections(this.form)" /></p>'."\n".
 4012: '</form>';
 4013:     return $output;
 4014: }
 4015: 
 4016: sub section_picker {
 4017:     my ($cdom,$cnum,$role,$rowtitle,$permission,$context,$mode,$crstype,
 4018:         $showcredits,$credits) = @_;
 4019:     my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 4020:     my $sections_select .= &course_sections(\%sections_count,$role);
 4021:     my $secbox = '<div>'.&Apache::lonhtmlcommon::start_pick_box()."\n";
 4022:     if ($mode eq 'upload') {
 4023:         my ($options,$cb_script,$coursepick) =
 4024:             &default_role_selector($context,1,$crstype,$showcredits);
 4025:         $secbox .= &Apache::lonhtmlcommon::row_title(&mt('role'),'LC_oddrow_value').
 4026:                    $options. &Apache::lonhtmlcommon::row_closure(1)."\n";
 4027:     }
 4028:     $secbox .= &Apache::lonhtmlcommon::row_title($rowtitle,'LC_oddrow_value')."\n";
 4029:     if ($env{'request.course.sec'} eq '') {
 4030:         $secbox .= '<table class="LC_createuser"><tr class="LC_section_row">'."\n".
 4031:                    '<td align="center">'.&mt('Existing sections')."\n".
 4032:                    '<br />'.$sections_select.'</td><td align="center">'.
 4033:                    &mt('New section').'<br />'."\n".
 4034:                    '<input type="text" name="newsec" size="15" value="" />'."\n".
 4035:                    '<input type="hidden" name="sections" value="" />'."\n".
 4036:                    '</td></tr></table>'."\n";
 4037:     } else {
 4038:         $secbox .= '<input type="hidden" name="sections" value="'.
 4039:                    $env{'request.course.sec'}.'" />'.
 4040:                    $env{'request.course.sec'};
 4041:     }
 4042:     $secbox .= &Apache::lonhtmlcommon::row_closure(1)."\n";
 4043:     unless ($mode eq 'chgsec') {
 4044:         if ($showcredits) {
 4045:             $secbox .= 
 4046:                 &Apache::lonhtmlcommon::row_title(&mt('credits (students)'),
 4047:                                                   'LC_evenrow_value')."\n".
 4048:                 '<input type="text" name="credits" size="3" value="'.$credits.'" />'."\n".
 4049:                 &Apache::lonhtmlcommon::row_closure(1)."\n";
 4050:         }
 4051:     }
 4052:     $secbox .= &Apache::lonhtmlcommon::end_pick_box().'</div>';
 4053:     return $secbox;
 4054: }
 4055: 
 4056: sub results_header_row {
 4057:     my ($rolefilter,$statusmode,$context,$permission,$mode,$crstype) = @_;
 4058:     my ($description,$showfilter);
 4059:     if ($rolefilter ne 'Any') {
 4060:         $showfilter = $rolefilter;
 4061:     }
 4062:     if ($context eq 'course') {
 4063:         if ($mode eq 'csv' || $mode eq 'excel') {
 4064:             if ($crstype eq 'Community') {
 4065:                 $description = &mt('Community - [_1]:',$env{'course.'.$env{'request.course.id'}.'.description'}).' ';
 4066:             } else {
 4067:                 $description = &mt('Course - [_1]:',$env{'course.'.$env{'request.course.id'}.'.description'}).' ';
 4068:             }
 4069:         }
 4070:         if ($statusmode eq 'Expired') {
 4071:             if ($crstype eq 'Community') {
 4072:                 $description .= &mt('Users in community with expired [_1] roles',$showfilter);
 4073:             } else {
 4074:                 $description .= &mt('Users in course with expired [_1] roles',$showfilter);
 4075:             }
 4076:         } elsif ($statusmode eq 'Future') {
 4077:             if ($crstype eq 'Community') {
 4078:                 $description .= &mt('Users in community with future [_1] roles',$showfilter);
 4079:             } else {
 4080:                 $description .= &mt('Users in course with future [_1] roles',$showfilter);
 4081:             }
 4082:         } elsif ($statusmode eq 'Active') {
 4083:             if ($crstype eq 'Community') {
 4084:                 $description .= &mt('Users in community with active [_1] roles',$showfilter);
 4085:             } else {
 4086:                 $description .= &mt('Users in course with active [_1] roles',$showfilter);
 4087:             }
 4088:         } else {
 4089:             if ($rolefilter eq 'Any') {
 4090:                 if ($crstype eq 'Community') {
 4091:                     $description .= &mt('All users in community');
 4092:                 } else {
 4093:                     $description .= &mt('All users in course');
 4094:                 }
 4095:             } else {
 4096:                 if ($crstype eq 'Community') {
 4097:                     $description .= &mt('All users in community with [_1] roles',$rolefilter);
 4098:                 } else {
 4099:                     $description .= &mt('All users in course with [_1] roles',$rolefilter);
 4100:                 }
 4101:             }
 4102:         }
 4103:         my $constraint;
 4104:         my $viewablesec = &viewable_section($permission);
 4105:         if ($viewablesec ne '') {
 4106:             if ($env{'form.showrole'} eq 'st') {
 4107:                 $constraint = &mt('only users in section "[_1]"',$viewablesec);
 4108:             } elsif (($env{'form.showrole'} ne 'cc') && ($env{'form.showrole'} ne 'co')) {
 4109:                 $constraint = &mt('only users affiliated with no section or section "[_1]"',$viewablesec);
 4110:             }
 4111:             if (($env{'form.grpfilter'} ne 'all') && ($env{'form.grpfilter'} ne '')) {
 4112:                 if ($env{'form.grpfilter'} eq 'none') {
 4113:                     $constraint .= &mt(' and not in any group');
 4114:                 } else {
 4115:                     $constraint .= &mt(' and members of group: "[_1]"',$env{'form.grpfilter'});
 4116:                 }
 4117:             }
 4118:         } else {
 4119:             if (($env{'form.secfilter'} ne 'all') && ($env{'form.secfilter'} ne '')) {
 4120:                 if ($env{'form.secfilter'} eq 'none') {
 4121:                     $constraint = &mt('only users affiliated with no section');
 4122:                 } else {
 4123:                     $constraint = &mt('only users affiliated with section "[_1]"',$env{'form.secfilter'});
 4124:                 }
 4125:             }
 4126:             if (($env{'form.grpfilter'} ne 'all') && ($env{'form.grpfilter'} ne '')) {
 4127:                 if ($env{'form.grpfilter'} eq 'none') {
 4128:                     if ($constraint eq '') {
 4129:                         $constraint = &mt('only users not in any group');
 4130:                     } else {
 4131:                         $constraint .= &mt(' and also not in any group'); 
 4132:                     }
 4133:                 } else {
 4134:                     if ($constraint eq '') {
 4135:                         $constraint = &mt('only members of group: "[_1]"',$env{'form.grpfilter'});
 4136:                     } else {
 4137:                         $constraint .= &mt(' and also members of group: "[_1]"'.$env{'form.grpfilter'});
 4138:                     }
 4139:                 }
 4140:             }
 4141:         }
 4142:         if ($constraint ne '') {
 4143:             $description .= ' ('.$constraint.')';
 4144:         } 
 4145:     } elsif ($context eq 'author') {
 4146:         $description = 
 4147:             &mt('Author space for [_1]'
 4148:                 ,'<span class="LC_cusr_emph">'
 4149:                 .&Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'})
 4150:                 .'</span>')
 4151:             .':&nbsp;&nbsp;';
 4152:         if ($statusmode eq 'Expired') {
 4153:             $description .= &mt('Co-authors with expired [_1] roles',$showfilter);
 4154:         } elsif ($statusmode eq 'Future') {
 4155:             $description .= &mt('Co-authors with future [_1] roles',$showfilter);
 4156:         } elsif ($statusmode eq 'Active') {
 4157:             $description .= &mt('Co-authors with active [_1] roles',$showfilter);
 4158:         } else {
 4159:             if ($rolefilter eq 'Any') {
 4160:                 $description .= &mt('All co-authors');
 4161:             } else {
 4162:                 $description .= &mt('All co-authors with [_1] roles',$rolefilter);
 4163:             }
 4164:         }
 4165:     } elsif ($context eq 'domain') {
 4166:         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 4167:         $description = &mt('Domain - [_1]:',$domdesc).' ';
 4168:         if ($env{'form.roletype'} eq 'domain') {
 4169:             if ($statusmode eq 'Expired') {
 4170:                 $description .= &mt('Users in domain with expired [_1] roles',$showfilter);
 4171:             } elsif ($statusmode eq 'Future') {
 4172:                 $description .= &mt('Users in domain with future [_1] roles',$showfilter);
 4173:             } elsif ($statusmode eq 'Active') {
 4174:                 $description .= &mt('Users in domain with active [_1] roles',$showfilter);
 4175:             } else {
 4176:                 if ($rolefilter eq 'Any') {
 4177:                     $description .= &mt('All users in domain');
 4178:                 } else {
 4179:                     $description .= &mt('All users in domain with [_1] roles',$rolefilter);
 4180:                 }
 4181:             }
 4182:         } elsif ($env{'form.roletype'} eq 'author') {
 4183:             if ($statusmode eq 'Expired') {
 4184:                 $description .= &mt('Co-authors in domain with expired [_1] roles',$showfilter);
 4185:             } elsif ($statusmode eq 'Future') {
 4186:                 $description .= &mt('Co-authors in domain with future [_1] roles',$showfilter);
 4187:             } elsif ($statusmode eq 'Active') {
 4188:                $description .= &mt('Co-authors in domain with active [_1] roles',$showfilter);
 4189:             } else {
 4190:                 if ($rolefilter eq 'Any') {
 4191:                     $description .= &mt('All users with co-author roles in domain',$showfilter);
 4192:                 } else {
 4193:                     $description .= &mt('All co-authors in domain with [_1] roles',$rolefilter);
 4194:                 }
 4195:             }
 4196:         } elsif (($env{'form.roletype'} eq 'course') || 
 4197:                  ($env{'form.roletype'} eq 'community')) {
 4198:             my $coursefilter = $env{'form.coursepick'};
 4199:             if ($env{'form.roletype'} eq 'course') {
 4200:                 if ($coursefilter eq 'category') {
 4201:                     my $instcode = &instcode_from_coursefilter();
 4202:                     if ($instcode eq '.') {
 4203:                         $description .= &mt('All courses in domain').' - ';
 4204:                     } else {
 4205:                         $description .= &mt('Courses in domain with institutional code: [_1]',$instcode).' - ';
 4206:                     }
 4207:                 } elsif ($coursefilter eq 'selected') {
 4208:                     $description .= &mt('Selected courses in domain').' - ';
 4209:                 } elsif ($coursefilter eq 'all') {
 4210:                     $description .= &mt('All courses in domain').' - ';
 4211:                 }
 4212:             } elsif ($env{'form.roletype'} eq 'community') {
 4213:                 if ($coursefilter eq 'selected') {
 4214:                     $description .= &mt('Selected communities in domain').' - ';
 4215:                 } elsif ($coursefilter eq 'all') {
 4216:                     $description .= &mt('All communities in domain').' - ';
 4217:                 }
 4218:             }
 4219:             if ($statusmode eq 'Expired') {
 4220:                 $description .= &mt('users with expired [_1] roles',$showfilter);
 4221:             } elsif ($statusmode eq 'Future') {
 4222:                 $description .= &mt('users with future [_1] roles',$showfilter);
 4223:             } elsif ($statusmode eq 'Active') {
 4224:                 $description .= &mt('users with active [_1] roles',$showfilter);
 4225:             } else {
 4226:                 if ($rolefilter eq 'Any') {
 4227:                     $description .= &mt('all users');
 4228:                 } else {
 4229:                     $description .= &mt('users with [_1] roles',$rolefilter);
 4230:                 }
 4231:             }
 4232:         }
 4233:     }
 4234:     return $description;
 4235: }
 4236: 
 4237: sub viewable_section {
 4238:     my ($permission) = @_;
 4239:     my $viewablesec;
 4240:     if (ref($permission) eq 'HASH') {
 4241:         if (exists($permission->{'view_section'})) {
 4242:             $viewablesec = $permission->{'view_section'};
 4243:         } elsif (exists($permission->{'cusr_section'})) {
 4244:             $viewablesec = $permission->{'cusr_section'};
 4245:         }
 4246:     }
 4247:     return $viewablesec;
 4248: }
 4249: 
 4250:     
 4251: #################################################
 4252: #################################################
 4253: sub show_drop_list {
 4254:     my ($r,$classlist,$nosort,$permission,$crstype) = @_;
 4255:     my $cid = $env{'request.course.id'};
 4256:     my ($cnum,$cdom) = &get_course_identity($cid);
 4257:     if (! exists($env{'form.sortby'})) {
 4258:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4259:                                                 ['sortby']);
 4260:     }
 4261:     my $sortby = $env{'form.sortby'};
 4262:     if ($sortby !~ /^(username|domain|section|groups|fullname|id|start|end)$/) {
 4263:         $sortby = 'username';
 4264:     }
 4265:     my $action = "drop";
 4266:     my $check_uncheck_js = &Apache::loncommon::check_uncheck_jscript();
 4267:     $r->print(<<END);
 4268: <input type="hidden" name="sortby" value="$sortby" />
 4269: <input type="hidden" name="action" value="$action" />
 4270: <input type="hidden" name="state"  value="done" />
 4271: <script type="text/javascript" language="Javascript">
 4272: // <![CDATA[
 4273: $check_uncheck_js
 4274: // ]]>
 4275: </script>
 4276: <input type="hidden" name="phase" value="four" />
 4277: END
 4278:     my ($indexhash,$keylist) = &make_keylist_array();
 4279:     my $studentcount = 0;
 4280:     if (ref($classlist) eq 'HASH') {
 4281:         foreach my $student (keys(%{$classlist})) {
 4282:             my $sdata = $classlist->{$student}; 
 4283:             my $status = $sdata->[$indexhash->{'status'}];
 4284:             my $section = $sdata->[$indexhash->{'section'}];
 4285:             if ($status ne 'Active') {
 4286:                 delete($classlist->{$student});
 4287:                 next;
 4288:             }
 4289:             if ($env{'request.course.sec'} ne '') {
 4290:                 if ($section ne $env{'request.course.sec'}) {
 4291:                     delete($classlist->{$student});
 4292:                     next;
 4293:                 }
 4294:             }
 4295:             $studentcount ++;
 4296:         }
 4297:     }
 4298:     if (!$studentcount) {
 4299:        my $msg = '';
 4300:         if ($crstype eq 'Community') {
 4301:             $msg = &mt('There are no members to drop.');
 4302:         } else {
 4303:             $msg = &mt('There are no students to drop.');
 4304:         }
 4305:         $r->print('<p class="LC_info">'.$msg.'</p>');
 4306:         return;
 4307:     }
 4308:     my ($classgroups) = &Apache::loncoursedata::get_group_memberships(
 4309:                                               $classlist,$keylist,$cdom,$cnum);
 4310:     my %lt=&Apache::lonlocal::texthash('usrn'   => "username",
 4311:                                        'dom'    => "domain",
 4312:                                        'id'     => "ID",
 4313:                                        'sn'     => "student name",
 4314:                                        'mn'     => "member name",
 4315:                                        'sec'    => "section",
 4316:                                        'start'  => "start date",
 4317:                                        'end'    => "end date",
 4318:                                        'groups' => "active groups",
 4319:                                       );
 4320:     my $nametitle = $lt{'sn'};
 4321:     if ($crstype eq 'Community') {
 4322:         $nametitle = $lt{'mn'};
 4323:     }
 4324:     if ($nosort) {
 4325:         $r->print(&Apache::loncommon::start_data_table().
 4326:                   &Apache::loncommon::start_data_table_header_row());
 4327:         $r->print(<<END);
 4328:     <th>&nbsp;</th>
 4329:     <th>$lt{'usrn'}</th>
 4330:     <th>$lt{'dom'}</th>
 4331:     <th>$lt{'id'}</th>
 4332:     <th>$nametitle</th>
 4333:     <th>$lt{'sec'}</th>
 4334:     <th>$lt{'start'}</th>
 4335:     <th>$lt{'end'}</th>
 4336:     <th>$lt{'groups'}</th>
 4337: END
 4338:         $r->print(&Apache::loncommon::end_data_table_header_row());
 4339:     } else  {
 4340:         $r->print(&Apache::loncommon::start_data_table().
 4341:                   &Apache::loncommon::start_data_table_header_row());
 4342:         $r->print(<<END);
 4343:     <th>&nbsp;</th>
 4344:     <th>
 4345:        <a href="/adm/createuser?action=$action&amp;sortby=username">$lt{'usrn'}</a>
 4346:     </th><th>
 4347:        <a href="/adm/createuser?action=$action&amp;sortby=domain">$lt{'dom'}</a>
 4348:     </th><th>
 4349:        <a href="/adm/createuser?action=$action&amp;sortby=id">$lt{'id'}</a>
 4350:     </th><th>
 4351:        <a href="/adm/createuser?action=$action&amp;sortby=fullname">$nametitle</a>
 4352:     </th><th>
 4353:        <a href="/adm/createuser?action=$action&amp;sortby=section">$lt{'sec'}</a>
 4354:     </th><th>
 4355:        <a href="/adm/createuser?action=$action&amp;sortby=start">$lt{'start'}</a>
 4356:     </th><th>
 4357:        <a href="/adm/createuser?action=$action&amp;sortby=end">$lt{'end'}</a>
 4358:     </th><th>
 4359:        <a href="/adm/createuser?action=$action&amp;sortby=groups">$lt{'groups'}</a>
 4360:     </th>
 4361: END
 4362:         $r->print(&Apache::loncommon::end_data_table_header_row());
 4363:     }
 4364:     #
 4365:     # Sort the students
 4366:     my $index  = $indexhash->{$sortby};
 4367:     my $second = $indexhash->{'username'};
 4368:     my $third  = $indexhash->{'domain'};
 4369:     my @Sorted_Students = sort {
 4370:         lc($classlist->{$a}->[$index])  cmp lc($classlist->{$b}->[$index])
 4371:             ||
 4372:         lc($classlist->{$a}->[$second]) cmp lc($classlist->{$b}->[$second])
 4373:             ||
 4374:         lc($classlist->{$a}->[$third]) cmp lc($classlist->{$b}->[$third])
 4375:         } (keys(%{$classlist}));
 4376:     foreach my $student (@Sorted_Students) {
 4377:         my $error;
 4378:         my $sdata = $classlist->{$student};
 4379:         my $username = $sdata->[$indexhash->{'username'}];
 4380:         my $domain   = $sdata->[$indexhash->{'domain'}];
 4381:         my $section  = $sdata->[$indexhash->{'section'}];
 4382:         my $name     = $sdata->[$indexhash->{'fullname'}];
 4383:         my $id       = $sdata->[$indexhash->{'id'}];
 4384:         my $start    = $sdata->[$indexhash->{'start'}];
 4385:         my $end      = $sdata->[$indexhash->{'end'}];
 4386:         my $groups = $classgroups->{$student};
 4387:         my $active_groups;
 4388:         if (ref($groups->{active}) eq 'HASH') {
 4389:             $active_groups = join(', ',keys(%{$groups->{'active'}}));
 4390:         }
 4391:         if (! defined($start) || $start == 0) {
 4392:             $start = &mt('none');
 4393:         } else {
 4394:             $start = &Apache::lonlocal::locallocaltime($start);
 4395:         }
 4396:         if (! defined($end) || $end == 0) {
 4397:             $end = &mt('none');
 4398:         } else {
 4399:             $end = &Apache::lonlocal::locallocaltime($end);
 4400:         }
 4401:         my $studentkey = $student.':'.$section;
 4402:         my $startitem = '<input type="hidden" name="'.$studentkey.'_start" value="'.$sdata->[$indexhash->{'start'}].'" />';
 4403:         #
 4404:         $r->print(&Apache::loncommon::start_data_table_row());
 4405:         $r->print(<<"END");
 4406:     <td><input type="checkbox" name="droplist" value="$studentkey" /></td>
 4407:     <td>$username</td>
 4408:     <td>$domain</td>
 4409:     <td>$id</td>
 4410:     <td>$name</td>
 4411:     <td>$section</td>
 4412:     <td>$start $startitem</td>
 4413:     <td>$end</td>
 4414:     <td>$active_groups</td>
 4415: END
 4416:         $r->print(&Apache::loncommon::end_data_table_row());
 4417:     }
 4418:     $r->print(&Apache::loncommon::end_data_table().'<br />');
 4419:     %lt=&Apache::lonlocal::texthash(
 4420:                        'dp'   => "Drop Students",
 4421:                        'dm'   => "Drop Members",
 4422:                        'ca'   => "check all",
 4423:                        'ua'   => "uncheck all",
 4424:                                        );
 4425:     my $btn = $lt{'dp'};
 4426:     if ($crstype eq 'Community') {
 4427:         $btn = $lt{'dm'}; 
 4428:     }
 4429:     $r->print(<<"END");
 4430: <p>
 4431: <input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.droplist)" /> &nbsp;
 4432: <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.droplist)" />
 4433: </p>
 4434: <p>
 4435: <input type="submit" value="$btn" />
 4436: </p>
 4437: END
 4438:     return;
 4439: }
 4440: 
 4441: #
 4442: # Print out the initial form to get the file containing a list of users
 4443: #
 4444: sub print_first_users_upload_form {
 4445:     my ($r,$context) = @_;
 4446:     my $str;
 4447:     $str  = '<input type="hidden" name="phase" value="two" />';
 4448:     $str .= '<input type="hidden" name="action" value="upload" />';
 4449:     $str .= '<input type="hidden" name="state"  value="got_file" />';
 4450: 
 4451:     $str .= &Apache::grades::checkforfile_js();
 4452: 
 4453:     $str .= '<h2>'.&mt('Upload a file containing information about users').'</h2>'."\n";
 4454: 
 4455:     # Excel and CSV Help
 4456:     $str .= '<div class="LC_columnSection">'
 4457:            .&Apache::loncommon::help_open_topic("Course_Create_Class_List",
 4458:                 &mt("How do I create a users list from a spreadsheet"))
 4459:            .' '.&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4460:                 &mt("How do I create a CSV file from a spreadsheet"))
 4461:            ."</div>\n";
 4462:     $str .= &Apache::lonhtmlcommon::start_pick_box()
 4463:            .&Apache::lonhtmlcommon::row_title(&mt('File'));
 4464:     if (&Apache::lonlocal::current_language() ne 'en') {
 4465:         if ($context eq 'course') { 
 4466:             $str .= '<p class="LC_info">'."\n"
 4467:                    .&mt('Please upload an UTF8 encoded file to ensure a correct character encoding in your classlist.')."\n"
 4468:                    .'</p>'."\n";
 4469:         }
 4470:     }
 4471:     $str .= &Apache::loncommon::upfile_select_html()
 4472:            .&Apache::lonhtmlcommon::row_closure()
 4473:            .&Apache::lonhtmlcommon::row_title(
 4474:                 '<label for="noFirstLine">'
 4475:                .&mt('Ignore First Line')
 4476:                .'</label>')
 4477:            .'<input type="checkbox" name="noFirstLine" id="noFirstLine" />'
 4478:            .&Apache::lonhtmlcommon::row_closure(1)
 4479:            .&Apache::lonhtmlcommon::end_pick_box();
 4480: 
 4481:     $str .= '<p>'
 4482:            .'<input type="button" name="fileupload" value="'.&mt('Next').'"'
 4483:            .' onclick="javascript:checkUpload(this.form);" />'
 4484:            .'</p>';
 4485: 
 4486:     $r->print($str);
 4487:     return;
 4488: }
 4489: 
 4490: # ================================================= Drop/Add from uploaded file
 4491: sub upfile_drop_add {
 4492:     my ($r,$context,$permission,$showcredits) = @_;
 4493:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4494:     if ($datatoken ne '') {
 4495:         &Apache::loncommon::load_tmp_file($r,$datatoken);
 4496:     }
 4497:     my @userdata=&Apache::loncommon::upfile_record_sep();
 4498:     if($env{'form.noFirstLine'}){shift(@userdata);}
 4499:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4500:     my %fields=();
 4501:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4502:         if ($env{'form.upfile_associate'} eq 'reverse') {
 4503:             if ($env{'form.f'.$i} ne 'none') {
 4504:                 $fields{$keyfields[$i]}=$env{'form.f'.$i};
 4505:             }
 4506:         } else {
 4507:             $fields{$env{'form.f'.$i}}=$keyfields[$i];
 4508:         }
 4509:     }
 4510:     #
 4511:     # Store the field choices away
 4512:     my @storefields = qw/username names fname mname lname gen id 
 4513:                          sec ipwd email role domain inststatus/;
 4514:     if ($showcredits) {
 4515:         push (@storefields,'credits');
 4516:     }
 4517:     my %fieldstype; 
 4518:     foreach my $field (@storefields) {
 4519:         $env{'form.'.$field.'_choice'}=$fields{$field};
 4520:         $fieldstype{$field.'_choice'} = 'scalar';
 4521:     }
 4522:     &Apache::loncommon::store_course_settings('enrollment_upload',\%fieldstype);
 4523:     my ($cid,$crstype,$setting,$crsdom,$crsnum);
 4524:     if ($context eq 'domain') {
 4525:         $setting = $env{'form.roleaction'};
 4526:     }
 4527:     if ($env{'request.course.id'} ne '') {
 4528:         $cid = $env{'request.course.id'};
 4529:         $crstype = &Apache::loncommon::course_type();
 4530:         $crsdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4531:         $crsnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4532:     } elsif ($setting eq 'course') {
 4533:         if (&Apache::lonnet::is_course($env{'form.dcdomain'},$env{'form.dccourse'})) {
 4534:             $cid = $env{'form.dcdomain'}.'_'.$env{'form.dccourse'};
 4535:             $crstype = &Apache::loncommon::course_type($cid);
 4536:             $crsdom = $env{'form.dcdomain'};
 4537:             $crsnum = $env{'form.dccourse'};
 4538:         }
 4539:     }
 4540:     my ($startdate,$enddate) = &get_dates_from_form();
 4541:     if ($env{'form.makedatesdefault'}) {
 4542:         $r->print(&make_dates_default($startdate,$enddate,$context,$crstype));
 4543:     }
 4544:     # Determine domain and desired host (home server)
 4545:     my $defdom=$env{'request.role.domain'};
 4546:     my $domain;
 4547:     if ($env{'form.defaultdomain'} ne '') {
 4548:         if (($context eq 'course') || ($setting eq 'course')) {
 4549:             if ($env{'form.defaultdomain'} eq $crsdom) {
 4550:                 $domain = $env{'form.defaultdomain'};
 4551:             } else {
 4552:                 if (&Apache::lonnet::will_trust('enroll',$crsdom,$env{'form.defaultdomain'})) {
 4553:                     $domain = $env{'form.defaultdomain'};
 4554:                 } else {
 4555:                     $r->print('<span class="LC_error">'.&mt('Error').': '.
 4556:                               &mt('Enrollment of users not permitted for specified default domain: [_1].',
 4557:                                   &Apache::lonnet::domain($env{'form.defaultdomain'},'description')).'</span>');
 4558:                     return 'untrusted';
 4559:                 }
 4560:             }
 4561:         } elsif ($context eq 'author') {
 4562:             if ($env{'form.defaultdomain'} eq $defdom) {
 4563:                 $domain = $env{'form.defaultdomain'}; 
 4564:             } else {
 4565:                 if ((&Apache::lonnet::will_trust('othcoau',$defdom,$env{'form.defaultdomain'})) &&
 4566:                     (&Apache::lonnet::will_trust('coaurem',$env{'form.defaultdomain'},$defdom))) {
 4567:                     $domain = $env{'form.defaultdomain'};
 4568:                 } else {
 4569:                     $r->print('<span class="LC_error">'.&mt('Error').': '.
 4570:                               &mt('Addition of users not permitted for specified default domain: [_1].',
 4571:                                   &Apache::lonnet::domain($env{'form.defaultdomain'},'description')).'</span>');
 4572:                     return 'untrusted';
 4573:                 }
 4574:             }
 4575:         } elsif (($context eq 'domain') && ($setting eq 'domain')) {
 4576:             if ($env{'form.defaultdomain'} eq $defdom) {
 4577:                 $domain = $env{'form.defaultdomain'};
 4578:             } else {
 4579:                 if (&Apache::lonnet::will_trust('domroles',$defdom,$env{'form.defaultdomain'})) {
 4580:                     $domain = $env{'form.defaultdomain'};
 4581:                 } else {
 4582:                     $r->print('<span class="LC_error">'.&mt('Error').': '.
 4583:                               &mt('Addition of users not permitted for specified default domain: [_1].',
 4584:                                   &Apache::lonnet::domain($env{'form.defaultdomain'},'description')).'</span>');
 4585:                     return 'untrusted';
 4586:                 }
 4587:             }
 4588:         }
 4589:     } else {
 4590:         $domain = $defdom;
 4591:     }
 4592:     my $desiredhost = $env{'form.lcserver'};
 4593:     if (lc($desiredhost) eq 'default') {
 4594:         $desiredhost = undef;
 4595:     } else {
 4596:         my %home_servers = &Apache::lonnet::get_servers($defdom,'library');
 4597:         if (! exists($home_servers{$desiredhost})) {
 4598:             $r->print('<p class="LC_error">'.&mt('Error').': '.
 4599:                       &mt('Invalid home server specified').'</p>');
 4600:             return 'invalidhome';
 4601:         }
 4602:     }
 4603:     # Determine authentication mechanism
 4604:     my $changeauth;
 4605:     if ($context eq 'domain') {
 4606:         $changeauth = $env{'form.changeauth'};
 4607:     }
 4608:     my $amode  = '';
 4609:     my $genpwd = '';
 4610:     my @genpwdfail;
 4611:     if ($env{'form.login'} eq 'krb') {
 4612:         $amode='krb';
 4613:         $amode.=$env{'form.krbver'};
 4614:         $genpwd=$env{'form.krbarg'};
 4615:     } elsif ($env{'form.login'} eq 'int') {
 4616:         $amode='internal';
 4617:         if ((defined($env{'form.intarg'})) && ($env{'form.intarg'})) {
 4618:             $genpwd=$env{'form.intarg'};
 4619:             @genpwdfail =
 4620:                 &Apache::loncommon::check_passwd_rules($domain,$genpwd);
 4621:         }
 4622:     } elsif ($env{'form.login'} eq 'loc') {
 4623:         $amode='localauth';
 4624:         if ((defined($env{'form.locarg'})) && ($env{'form.locarg'})) {
 4625:             $genpwd=$env{'form.locarg'};
 4626:         }
 4627:     } elsif ($env{'form.login'} eq 'lti') {
 4628:         $amode='lti';
 4629:     }
 4630:     if ($amode =~ /^krb/) {
 4631:         if (! defined($genpwd) || $genpwd eq '') {
 4632:             $r->print('<span class="Error">'.
 4633:                       &mt('Unable to enroll users').' '.
 4634:                       &mt('No Kerberos domain was specified.').'</span></p>');
 4635:             $amode = ''; # This causes the loop below to be skipped
 4636:         }
 4637:     }
 4638:     my ($defaultsec,$defaultrole,$defaultcredits,$commoncredits);
 4639:     if ($context eq 'domain') {
 4640:         if ($setting eq 'domain') {
 4641:             $defaultrole = $env{'form.defaultrole'};
 4642:         } elsif ($setting eq 'course') {
 4643:             $defaultrole = $env{'form.courserole'};
 4644:             $defaultsec = $env{'form.sections'};
 4645:             if ($showcredits) {
 4646:                 $commoncredits = $env{'form.credits'};
 4647:                 if ($crstype ne 'Community') {
 4648:                     my %coursehash=&Apache::lonnet::coursedescription($cid);
 4649:                     $defaultcredits = $coursehash{'internal.defaultcredits'};
 4650:                 }
 4651:             }
 4652:         }
 4653:     } elsif ($context eq 'author') {
 4654:         $defaultrole = $env{'form.defaultrole'};
 4655:     } elsif ($context eq 'course') {
 4656:         $defaultrole = $env{'form.defaultrole'};
 4657:         $defaultsec = $env{'form.sections'};
 4658:         if ($showcredits) {
 4659:             $commoncredits = $env{'form.credits'};
 4660:             $defaultcredits = $env{'course.'.$cid.'.internal.defaultcredits'};
 4661:         }
 4662:     }
 4663:     # Check to see if user information can be changed
 4664:     my @userinfo = ('firstname','middlename','lastname','generation',
 4665:                     'permanentemail','id');
 4666:     my %canmodify;
 4667:     if (&Apache::lonnet::allowed('mau',$domain)) {
 4668:         push(@userinfo,'inststatus');
 4669:         foreach my $field (@userinfo) {
 4670:             $canmodify{$field} = 1;
 4671:         }
 4672:     }
 4673:     my (%userlist,%modifiable_fields,@poss_roles);
 4674:     my $secidx = &Apache::loncoursedata::CL_SECTION();
 4675:     my @courseroles = &roles_by_context('course',1,$crstype);
 4676:     if (!&Apache::lonnet::allowed('mau',$domain)) {
 4677:         if ($context eq 'course' || $context eq 'author') {
 4678:             @poss_roles =  &curr_role_permissions($context,'','',$crstype);
 4679:             my @statuses = ('active','future');
 4680:             my ($indexhash,$keylist) = &make_keylist_array();
 4681:             my %info;
 4682:             foreach my $role (@poss_roles) {
 4683:                 %{$modifiable_fields{$role}} = &can_modify_userinfo($context,$domain,
 4684:                                                         \@userinfo,[$role]);
 4685:             }
 4686:             if ($context eq 'course') {
 4687:                 my ($cnum,$cdom) = &get_course_identity();
 4688:                 my $roster = &Apache::loncoursedata::get_classlist();
 4689:                 if (ref($roster) eq 'HASH') {
 4690:                     %userlist = %{$roster};
 4691:                 }
 4692:                 my %advrolehash = &Apache::lonnet::get_my_roles($cnum,$cdom,undef,
 4693:                                                          \@statuses,\@poss_roles);
 4694:                 &gather_userinfo($context,'view',\%userlist,$indexhash,\%info,
 4695:                                 \%advrolehash,$permission);
 4696:             } elsif ($context eq 'author') {
 4697:                 my %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 4698:                                                   \@statuses,\@poss_roles);
 4699:                 &gather_userinfo($context,'view',\%userlist,$indexhash,\%info,
 4700:                              \%cstr_roles,$permission);
 4701:             }
 4702:         }
 4703:     }
 4704:     if ($datatoken eq '') {
 4705:         $r->print('<p class="LC_error">'.&mt('Error').': '.
 4706:                   &mt('Invalid datatoken').'</p>');
 4707:         return 'missingdata';
 4708:     }
 4709:     if ( $domain eq &LONCAPA::clean_domain($domain)
 4710:         && ($amode ne '')) {
 4711:         #######################################
 4712:         ##         Add/Modify Users          ##
 4713:         #######################################
 4714:         if ($context eq 'course') {
 4715:             $r->print('<h3>'.&mt('Enrolling Users')."</h3>\n<p>\n");
 4716:         } elsif ($context eq 'author') {
 4717:             $r->print('<h3>'.&mt('Updating Co-authors')."</h3>\n<p>\n");
 4718:         } else {
 4719:             $r->print('<h3>'.&mt('Adding/Modifying Users')."</h3>\n<p>\n");
 4720:         }
 4721:         $r->rflush;
 4722:         my (%got_role_approvals,%got_instdoms,%process_by,%instdoms,
 4723:             %pending,%reject,%notifydc);
 4724: 
 4725:         my %counts = (
 4726:                        user => 0,
 4727:                        auth => 0,
 4728:                        role => 0,
 4729:                      );
 4730:         my $flushc=0;
 4731:         my %student=();
 4732:         my (%curr_groups,@sections,@cleansec,$defaultwarn,$groupwarn);
 4733:         my %userchg;
 4734:         if ($context eq 'course' || $setting eq 'course') {
 4735:             if ($context eq 'course') {
 4736:                 # Get information about course groups
 4737:                 %curr_groups = &Apache::longroup::coursegroups();
 4738:             } elsif ($setting eq 'course') {
 4739:                 if ($cid) {
 4740:                     %curr_groups =
 4741:                         &Apache::longroup::coursegroups($env{'form.dcdomain'},
 4742:                                                         $env{'form.dccourse'});
 4743:                 }
 4744:             }
 4745:             # determine section number
 4746:             if ($defaultsec =~ /,/) {
 4747:                 push(@sections,split(/,/,$defaultsec));
 4748:             } else {
 4749:                 push(@sections,$defaultsec);
 4750:             }
 4751:             # remove non alphanumeric values from section
 4752:             foreach my $item (@sections) {
 4753:                 $item =~ s/\W//g;
 4754:                 if ($item eq "none" || $item eq 'all') {
 4755:                     $defaultwarn = &mt('Default section name [_1] could not be used as it is a reserved word.',$item);
 4756:                 } elsif ($item ne ''  && exists($curr_groups{$item})) {
 4757:                     $groupwarn = &mt('Default section name "[_1]" is the name of a course group. Section names and group names must be distinct.',$item);
 4758:                 } elsif ($item ne '') {
 4759:                     push(@cleansec,$item);
 4760:                 }
 4761:             }
 4762:             if ($defaultwarn) {
 4763:                 $r->print($defaultwarn.'<br />');
 4764:             }
 4765:             if ($groupwarn) {
 4766:                 $r->print($groupwarn.'<br />');
 4767:             }
 4768:         }
 4769:         my (%curr_rules,%got_rules,%alerts,%cancreate);
 4770:         my %customroles = &my_custom_roles($crstype);
 4771:         my @permitted_roles = 
 4772:             &roles_on_upload($context,$setting,$crstype,%customroles);
 4773:         my %longtypes = &Apache::lonlocal::texthash(
 4774:                             official   => 'Institutional',
 4775:                             unofficial => 'Non-institutional',
 4776:                         );
 4777:         my $newuserdom = $env{'request.role.domain'};
 4778:         map { $cancreate{$_} = &can_create_user($newuserdom,$context,$_); } keys(%longtypes);
 4779:         # Get new users list
 4780:         my (%existinguser,%userinfo,%disallow,%rulematch,%inst_results,%alerts,%checkuname,
 4781:             %showpasswdrules,$haspasswdmap);
 4782:         my $counter = -1;
 4783:         my (%willtrust,%trustchecked);
 4784:         foreach my $line (@userdata) {
 4785:             $counter ++;
 4786:             my @secs;
 4787:             my %entries=&Apache::loncommon::record_sep($line);
 4788:             # Determine user name
 4789:             $entries{$fields{'username'}} =~ s/^\s+|\s+$//g;
 4790:             unless (($entries{$fields{'username'}} eq '') ||
 4791:                     (!defined($entries{$fields{'username'}}))) {
 4792:                 my ($fname, $mname, $lname,$gen) = ('','','','');
 4793:                 if (defined($fields{'names'})) {
 4794:                     ($lname,$fname,$mname)=($entries{$fields{'names'}}=~
 4795:                                             /([^\,]+)\,\s*(\w+)\s*(.*)$/);
 4796:                 } else {
 4797:                     if (defined($fields{'fname'})) {
 4798:                         $fname=$entries{$fields{'fname'}};
 4799:                     }
 4800:                     if (defined($fields{'mname'})) {
 4801:                         $mname=$entries{$fields{'mname'}};
 4802:                     }
 4803:                     if (defined($fields{'lname'})) {
 4804:                         $lname=$entries{$fields{'lname'}};
 4805:                     }
 4806:                     if (defined($fields{'gen'})) {
 4807:                         $gen=$entries{$fields{'gen'}};
 4808:                     }
 4809:                 }
 4810: 
 4811:                 if ($entries{$fields{'username'}}
 4812:                     ne &LONCAPA::clean_username($entries{$fields{'username'}})) {
 4813:                     my $nowhitespace;
 4814:                     if ($entries{$fields{'username'}} =~ /\s/) {
 4815:                         $nowhitespace = ' - '.&mt('usernames may not contain spaces.');
 4816:                     }
 4817:                     $disallow{$counter} =
 4818:                         &mt('Unacceptable username [_1] for user [_2] [_3] [_4] [_5]',
 4819:                             '"<b>'.$entries{$fields{'username'}}.'</b>"',
 4820:                             $fname,$mname,$lname,$gen).$nowhitespace;
 4821:                     next;
 4822:                 } else {
 4823:                     $entries{$fields{'domain'}} =~ s/^\s+|\s+$//g;
 4824:                     if ($entries{$fields{'domain'}} 
 4825:                         ne &LONCAPA::clean_domain($entries{$fields{'domain'}})) {
 4826:                         $disallow{$counter} =
 4827:                             &mt('Unacceptable domain [_1] for user [_2] [_3] [_4] [_5]',
 4828:                                 '"<b>'.$entries{$fields{'domain'}}.'</b>"',
 4829:                                 $fname,$mname,$lname,$gen);
 4830:                         next;
 4831:                     } elsif ($entries{$fields{'domain'}} ne $domain) {
 4832:                         my $possdom = $entries{$fields{'domain'}};
 4833:                         if ($context eq 'course' || $setting eq 'course') {
 4834:                             unless ($trustchecked{$possdom}) {
 4835:                                 $willtrust{$possdom} = &Apache::lonnet::will_trust('enroll',$domain,$possdom);
 4836:                                 $trustchecked{$possdom} = 1;
 4837:                             }
 4838:                         } elsif ($context eq 'author') {
 4839:                             unless ($trustchecked{$possdom}) {
 4840:                                 $willtrust{$possdom} = &Apache::lonnet::will_trust('othcoau',$domain,$possdom);
 4841:                             }
 4842:                             if ($willtrust{$possdom}) {
 4843:                                 $willtrust{$possdom} = &Apache::lonnet::will_trust('coaurem',$possdom,$domain); 
 4844:                             }
 4845:                         }
 4846:                         unless ($willtrust{$possdom}) {
 4847:                             $disallow{$counter} =
 4848:                                 &mt('Unacceptable domain [_1] for user [_2] [_3] [_4] [_5]',
 4849:                                     '"<b>'.$possdom.'</b>"',
 4850:                                     $fname,$mname,$lname,$gen);
 4851:                             next;
 4852:                         }
 4853:                     }
 4854:                     my $username = $entries{$fields{'username'}};
 4855:                     my $userdomain = $entries{$fields{'domain'}};
 4856:                     if ($userdomain eq '') {
 4857:                         $userdomain = $domain;
 4858:                     }
 4859:                     if (defined($fields{'sec'})) {
 4860:                         if (defined($entries{$fields{'sec'}})) {
 4861:                             $entries{$fields{'sec'}} =~ s/\W//g;
 4862:                             my $item = $entries{$fields{'sec'}};
 4863:                             if ($item eq "none" || $item eq 'all') {
 4864:                                 $disallow{$counter} =
 4865:                                     &mt('[_1]: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]" - this is a reserved word.',
 4866:                                         '<b>'.$username.'</b>',$fname,$mname,$lname,$gen,$item);
 4867:                                 next;
 4868:                             } elsif (exists($curr_groups{$item})) {
 4869:                                 $disallow{$counter} =
 4870:                                     &mt('[_1]: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]" - this is a course group.',
 4871:                                         '<b>'.$username.'</b>',$fname,$mname,$lname,$gen,$item).' '.
 4872:                                     &mt('Section names and group names must be distinct.');
 4873:                                 next;
 4874:                             } else {
 4875:                                 push(@secs,$item);
 4876:                             }
 4877:                         }
 4878:                     }
 4879:                     if ($env{'request.course.sec'} ne '') {
 4880:                         @secs = ($env{'request.course.sec'});
 4881:                         if (ref($userlist{$username.':'.$userdomain}) eq 'ARRAY') {
 4882:                             my $currsec = $userlist{$username.':'.$userdomain}[$secidx];
 4883:                             if ($currsec ne $env{'request.course.sec'}) {
 4884:                                 $disallow{$counter} =
 4885:                                     &mt('[_1]: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]".',
 4886:                                         '<b>'.$username.'</b>',$fname,$mname,$lname,$gen,$secs[0]);
 4887:                                 if ($currsec eq '') {
 4888:                                     $disallow{$counter} .=
 4889:                                         &mt('This user already has an active/future student role in the course, unaffiliated to any section.');
 4890: 
 4891:                                 } else {
 4892:                                     $disallow{$counter} .=
 4893:                                         &mt('This user already has an active/future role in section "[_1]" of the course.',$currsec);
 4894:                                 }
 4895:                                 $disallow{$counter} .=
 4896:                                     '<br />'.
 4897:                                     &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.',
 4898:                                         $secs[0]);
 4899:                                 next;
 4900:                             }
 4901:                         }
 4902:                     } elsif ($context eq 'course' || $setting eq 'course') {
 4903:                         if (@secs == 0) {
 4904:                             @secs = @cleansec;
 4905:                         }
 4906:                     }
 4907:                     # determine id number
 4908:                     my $id='';
 4909:                     if (defined($fields{'id'})) {
 4910:                         if (defined($entries{$fields{'id'}})) {
 4911:                             $id=$entries{$fields{'id'}};
 4912:                         }
 4913:                         $id=~tr/A-Z/a-z/;
 4914:                     }
 4915:                     # determine email address
 4916:                     my $email='';
 4917:                     if (defined($fields{'email'})) {
 4918:                         $entries{$fields{'email'}} =~ s/^\s+|\s+$//g;
 4919:                         if (defined($entries{$fields{'email'}})) {
 4920:                             $email=$entries{$fields{'email'}};
 4921:                             unless ($email=~/^[^\@]+\@[^\@]+$/) { $email=''; }
 4922:                         }
 4923:                     }
 4924:                     # determine affiliation
 4925:                     my $inststatus='';
 4926:                     if (defined($fields{'inststatus'})) {
 4927:                         if (defined($entries{$fields{'inststatus'}})) {
 4928:                             $inststatus=$entries{$fields{'inststatus'}};
 4929:                         }
 4930:                     }
 4931:                     # determine user password
 4932:                     my $password;
 4933:                     my $passwdfromfile;
 4934:                     if (defined($fields{'ipwd'})) {
 4935:                         if ($entries{$fields{'ipwd'}}) {
 4936:                             $password=$entries{$fields{'ipwd'}};
 4937:                             $passwdfromfile = 1;
 4938:                             if ($env{'form.login'} eq 'int') {
 4939:                                 my $uhome=&Apache::lonnet::homeserver($username,$userdomain);
 4940:                                 if (($uhome eq 'no_host') || ($changeauth)) {
 4941:                                     my @brokepwdrules =
 4942:                                         &Apache::loncommon::check_passwd_rules($domain,$password);
 4943:                                     if (@brokepwdrules) {
 4944:                                         $disallow{$counter} = &mt('[_1]: Password included in file for this user did not meet requirements.',
 4945:                                                                   '<b>'.$username.'</b>');
 4946:                                         map { $showpasswdrules{$_} = 1; } @brokepwdrules;
 4947:                                         next;
 4948:                                     }
 4949:                                 }
 4950:                             }
 4951:                         }
 4952:                     }
 4953:                     unless ($passwdfromfile) {
 4954:                         if ($env{'form.login'} eq 'int') {
 4955:                             if (@genpwdfail) {
 4956:                                 my $uhome=&Apache::lonnet::homeserver($username,$userdomain);
 4957:                                 if (($uhome eq 'no_host') || ($changeauth)) {
 4958:                                     $disallow{$counter} = &mt('[_1]: No specific password in file for this user; default password did not meet requirements',
 4959:                                                               '<b>'.$username.'</b>');
 4960:                                     unless ($haspasswdmap) {
 4961:                                         map { $showpasswdrules{$_} = 1; } @genpwdfail;
 4962:                                         $haspasswdmap = 1;
 4963:                                     }
 4964:                                 }
 4965:                                 next;
 4966:                             }
 4967:                         }
 4968:                         $password = $genpwd;
 4969:                     }
 4970:                     # determine user role
 4971:                     my $role = '';
 4972:                     if (defined($fields{'role'})) {
 4973:                         if ($entries{$fields{'role'}}) {
 4974:                             $entries{$fields{'role'}}  =~ s/(\s+$|^\s+)//g;
 4975:                             if ($entries{$fields{'role'}} ne '') {
 4976:                                 if (grep(/^\Q$entries{$fields{'role'}}\E$/,@permitted_roles)) {
 4977:                                     $role = $entries{$fields{'role'}};
 4978:                                 }
 4979:                             }
 4980:                             if ($role eq '') {
 4981:                                 my $rolestr = join(', ',@permitted_roles);
 4982:                                 $disallow{$counter} =
 4983:                                     &mt('[_1]: You do not have permission to add the requested role [_2] for the user.'
 4984:                                         ,'<b>'.$entries{$fields{'username'}}.'</b>'
 4985:                                         ,$entries{$fields{'role'}})
 4986:                                         .'<br />'
 4987:                                         .&mt('Allowable role(s) is/are: [_1].',$rolestr);
 4988:                                 next;
 4989:                             }
 4990:                         }
 4991:                     }
 4992:                     if ($role eq '') {
 4993:                         $role = $defaultrole;
 4994:                     }
 4995:                     # Clean up whitespace
 4996:                     foreach (\$id,\$fname,\$mname,\$lname,\$gen,\$inststatus) {
 4997:                         $$_ =~ s/(\s+$|^\s+)//g;
 4998:                     }
 4999:                     my $credits;
 5000:                     if ($showcredits) {
 5001:                         if (($role eq 'st') && ($crstype ne 'Community')) {
 5002:                             $credits = $entries{$fields{'credits'}};
 5003:                             if ($credits ne '') {
 5004:                                 $credits =~ s/[^\d\.]//g;
 5005:                             }
 5006:                             if ($credits eq '') {
 5007:                                 $credits = $commoncredits;
 5008:                             }
 5009:                             if ($credits eq $defaultcredits) {
 5010:                                 undef($credits);
 5011:                             }
 5012:                         }
 5013:                     }
 5014:                     # check against rules
 5015:                     my $checkid = 0;
 5016:                     my $newuser = 0;
 5017:                     my $uhome=&Apache::lonnet::homeserver($username,$userdomain);
 5018:                     if ($uhome eq 'no_host') {
 5019:                         if ($userdomain ne $newuserdom) {
 5020:                             if ($context eq 'course') {
 5021:                                 $disallow{$counter} =
 5022:                                     &mt('[_1]: The domain specified ([_2]) is different to that of the course.',
 5023:                                        '<b>'.$username.'</b>',$userdomain);
 5024:                             } elsif ($context eq 'author') {
 5025:                                 $disallow{$counter} =
 5026:                                     &mt('[_1]: The domain specified ([_2]) is different to that of the author.',
 5027:                                         '<b>'.$username.'</b>',$userdomain); 
 5028:                             } else {
 5029:                                 $disallow{$counter} =
 5030:                                     &mt('[_1]: The domain specified ([_2]) is different to that of your current role.',
 5031:                                         '<b>'.$username.'</b>',$userdomain);
 5032:                             }
 5033:                             $disallow{$counter} .=
 5034:                                 &mt('The user does not already exist, and you may not create a new user in a different domain.');
 5035:                             next;
 5036:                         } else {
 5037:                             unless (($password ne '') || ($env{'form.login'} eq 'loc') || ($env{'form.login'} eq 'lti')) {
 5038:                                 $disallow{$counter} =
 5039:                                     &mt('[_1]: This is a new user but no default password was provided, and the authentication type requires one.',
 5040:                                         '<b>'.$username.'</b>');
 5041:                                 next;
 5042:                             }
 5043:                         }
 5044:                         $checkid = 1;
 5045:                         $newuser = 1;
 5046:                         $checkuname{$username.':'.$newuserdom} = { 'newuser' => $newuser, 'id' => $id };
 5047:                     } else {
 5048:                         if ($context eq 'course' || $context eq 'author') {
 5049:                             if ($userdomain eq $domain ) {
 5050:                                 if ($role eq '') {
 5051:                                     my @checkroles;
 5052:                                     foreach my $role (@poss_roles) {
 5053:                                         my $endkey;
 5054:                                         if ($role ne 'st') {
 5055:                                             $endkey = ':'.$role;
 5056:                                         }
 5057:                                         if (exists($userlist{$username.':'.$userdomain.$endkey})) {
 5058:                                             if (!grep(/^\Q$role\E$/,@checkroles)) {
 5059:                                                 push(@checkroles,$role);
 5060:                                             }
 5061:                                         }
 5062:                                     }
 5063:                                     if (@checkroles > 0) {
 5064:                                         %canmodify = &can_modify_userinfo($context,$domain,\@userinfo,\@checkroles);
 5065:                                     }
 5066:                                 } elsif (ref($modifiable_fields{$role}) eq 'HASH') {
 5067:                                     %canmodify = %{$modifiable_fields{$role}};
 5068:                                 }
 5069:                             }
 5070:                             my @newinfo = (\$fname,\$mname,\$lname,\$gen,\$email,\$id);
 5071:                             for (my $i=0; $i<@newinfo; $i++) {
 5072:                                 if (${$newinfo[$i]} ne '') {
 5073:                                     if (!$canmodify{$userinfo[$i]}) {
 5074:                                         ${$newinfo[$i]} = '';
 5075:                                     }
 5076:                                 }
 5077:                             }
 5078:                         }
 5079:                         if ($id) {
 5080:                             $existinguser{$userdomain}{$username} = $id;
 5081:                         }
 5082:                     }
 5083:                     $userinfo{$counter} = {
 5084:                                           username   => $username,
 5085:                                           domain     => $userdomain,
 5086:                                           fname      => $fname,
 5087:                                           mname      => $mname,
 5088:                                           lname      => $lname,
 5089:                                           gen        => $gen,
 5090:                                           email      => $email,
 5091:                                           id         => $id, 
 5092:                                           password   => $password,
 5093:                                           inststatus => $inststatus,
 5094:                                           role       => $role,
 5095:                                           sections   => \@secs,
 5096:                                           credits    => $credits,
 5097:                                           newuser    => $newuser,
 5098:                                           checkid    => $checkid,
 5099:                                         };
 5100:                 }
 5101:             }
 5102:         } # end of foreach (@userdata)
 5103:         if ($counter > -1) {
 5104:             my $total = $counter + 1;
 5105:             my %checkids;
 5106:             if ((keys(%existinguser)) || (keys(%checkuname))) {
 5107:                 $r->print(&mt('Please be patient -- checking for institutional data ...'));
 5108:                 $r->rflush();
 5109:                 if (keys(%existinguser)) {
 5110:                     foreach my $dom (keys(%existinguser)) {
 5111:                         if (ref($existinguser{$dom}) eq 'HASH') {
 5112:                             my %idhash = &Apache::lonnet::idrget($dom,keys(%{$existinguser{$dom}}));
 5113:                             foreach my $username (keys(%{$existinguser{$dom}})) {
 5114:                                 if ($idhash{$username} ne $existinguser{$dom}{$username}) {
 5115:                                     $checkids{$username.':'.$dom} = {
 5116:                                                                     'id' => $existinguser{$dom}{$username},
 5117:                                                                     };
 5118:                                 }
 5119:                             }
 5120:                             if (keys(%checkids)) {
 5121:                                 &Apache::loncommon::user_rule_check(\%checkids,{ 'id' => 1 },
 5122:                                                                     \%alerts,\%rulematch,
 5123:                                                                     \%inst_results,\%curr_rules,
 5124:                                                                     \%got_rules);
 5125:                             }
 5126:                         }
 5127:                     }
 5128:                 }
 5129:                 if (keys(%checkuname)) {
 5130:                     &Apache::loncommon::user_rule_check(\%checkuname,{ 'username' => 1, 'id' => 1, },
 5131:                                                         \%alerts,\%rulematch,\%inst_results,
 5132:                                                         \%curr_rules,\%got_rules);
 5133:                 }
 5134:                 $r->print(' '.&mt('done').'<br /><br />');
 5135:                 $r->rflush();
 5136:             }
 5137:             my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,$total);
 5138:             $r->print('<ul>');
 5139:             for (my $i=0; $i<=$counter; $i++) {
 5140:                 if ($disallow{$i}) {
 5141:                     $r->print('<li>'.$disallow{$i}.'</li>');
 5142:                 } elsif (ref($userinfo{$i}) eq 'HASH') {
 5143:                     my $password = $userinfo{$i}{'password'}; 
 5144:                     my $newuser = $userinfo{$i}{'newuser'};
 5145:                     my $checkid = $userinfo{$i}{'checkid'};
 5146:                     my $id = $userinfo{$i}{'id'};
 5147:                     my $role = $userinfo{$i}{'role'};
 5148:                     my @secs;
 5149:                     if (ref($userinfo{$i}{'sections'}) eq 'ARRAY') {
 5150:                         @secs = @{$userinfo{$i}{'sections'}};
 5151:                     }
 5152:                     my $fname = $userinfo{$i}{'fname'};
 5153:                     my $mname = $userinfo{$i}{'mname'}; 
 5154:                     my $lname = $userinfo{$i}{'lname'};
 5155:                     my $gen = $userinfo{$i}{'gen'};
 5156:                     my $email = $userinfo{$i}{'email'};
 5157:                     my $inststatus = $userinfo{$i}{'inststatus'};
 5158:                     my $credits = $userinfo{$i}{'credits'};
 5159:                     my $username = $userinfo{$i}{'username'};
 5160:                     my $userdomain = $userinfo{$i}{'domain'};
 5161:                     my $user = $username.':'.$userdomain;
 5162:                     if ($newuser) {
 5163:                         if (ref($alerts{'username'}) eq 'HASH') {
 5164:                             if (ref($alerts{'username'}{$userdomain}) eq 'HASH') {
 5165:                                 if ($alerts{'username'}{$userdomain}{$username}) {
 5166:                                     $r->print('<li>'.
 5167:                                               &mt('[_1]: matches the username format at your institution, but is not known to your directory service.','<b>'.$username.'</b>').'<br />'.
 5168:                                               &mt('Consequently, the user was not created.').'</li>');
 5169:                                     next;
 5170:                                 }
 5171:                             }
 5172:                         }
 5173:                         if (ref($inst_results{$user}) eq 'HASH') {
 5174:                             if ($inst_results{$user}{'firstname'} ne '') {
 5175:                                 $fname = $inst_results{$user}{'firstname'};
 5176:                             }
 5177:                             if ($inst_results{$user}{'middlename'} ne '') {
 5178:                                 $mname = $inst_results{$user}{'middlename'};
 5179:                             }
 5180:                             if ($inst_results{$user}{'lasttname'} ne '') {
 5181:                                 $lname = $inst_results{$user}{'lastname'};
 5182:                             }
 5183:                             if ($inst_results{$user}{'permanentemail'} ne '') {
 5184:                                 $email = $inst_results{$user}{'permanentemail'};
 5185:                             }
 5186:                             if ($inst_results{$user}{'id'} ne '') {
 5187:                                 $id = $inst_results{$user}{'id'};
 5188:                                 $checkid = 0;
 5189:                             }
 5190:                             if (ref($inst_results{$user}{'inststatus'}) eq 'ARRAY') {
 5191:                                 $inststatus = join(':',@{$inst_results{$user}{'inststatus'}});
 5192:                             }
 5193:                         }
 5194:                         if (($checkid) && ($id ne '')) {
 5195:                             if (ref($alerts{'id'}) eq 'HASH') {
 5196:                                 if (ref($alerts{'id'}{$userdomain}) eq 'HASH') {
 5197:                                     if ($alerts{'id'}{$userdomain}{$username}) {
 5198:                                         $r->print('<li>'.
 5199:                                                   &mt('[_1]: has a student/employee ID matching the format at your institution, but the ID is not found by your directory service.',
 5200:                                                   '<b>'.$username.'</b>').'<br />'.
 5201:                                                   &mt('Consequently, the user was not created.').'</li>');
 5202:                                         next;
 5203:                                     }
 5204:                                 }
 5205:                             }
 5206:                         }
 5207:                         my $usertype = 'unofficial';
 5208:                         if (ref($rulematch{$user}) eq 'HASH') {
 5209:                             if ($rulematch{$user}{'username'}) {
 5210:                                 $usertype = 'official';
 5211:                             }
 5212:                         }
 5213:                         unless ($cancreate{$usertype}) {
 5214:                             my $showtype = $longtypes{$usertype};
 5215:                             $r->print('<li>'.
 5216:                                       &mt('[_1]: The user does not exist, and you are not permitted to create users of type: [_2].','<b>'.$username.'</b>',$showtype).'</li>');
 5217:                             next;
 5218:                         }
 5219:                     } elsif ($id ne '') {
 5220:                         if (exists($checkids{$user})) {
 5221:                             $checkid = 1; 
 5222:                             if (ref($alerts{'id'}) eq 'HASH') {
 5223:                                 if (ref($alerts{'id'}{$userdomain}) eq 'HASH') {
 5224:                                     if ($alerts{'id'}{$userdomain}{$username}) {
 5225:                                         $r->print('<li>'.
 5226:                                                   &mt('[_1]: has a student/employee ID matching the format at your institution, but the ID is not found by your directory service.',
 5227:                                                   '<b>'.$username.'</b>').'<br />'.
 5228:                                                   &mt('Consequently, the ID was not changed.').'</li>');
 5229:                                         $id = '';
 5230:                                     }
 5231:                                 }
 5232:                             }
 5233:                         }
 5234:                     }
 5235:                     my $multiple = 0;
 5236:                     my ($userresult,$authresult,$roleresult,$idresult);
 5237:                     my (%userres,%authres,%roleres,%idres);
 5238:                     my $singlesec = '';
 5239:                     if ($role eq 'st') {
 5240:                         if (($context eq 'domain') && ($changeauth eq 'Yes') && (!$newuser)) {
 5241:                             if ((&Apache::lonnet::allowed('mau',$userdomain)) &&
 5242:                                 (&Apache::lonnet::homeserver($username,$userdomain) ne 'no_host')) {
 5243:                                 if ((($amode =~ /^krb4|krb5|internal$/) && $password ne '') ||
 5244:                                      ($amode eq 'localauth')) {
 5245:                                     $authresult =
 5246:                                         &Apache::lonnet::modifyuserauth($userdomain,$username,$amode,$password);
 5247:                                 }
 5248:                             }
 5249:                         }
 5250:                         my $sec;
 5251:                         if (ref($userinfo{$i}{'sections'}) eq 'ARRAY') {
 5252:                             if (@secs > 0) {
 5253:                                 $sec = $secs[0];
 5254:                             }
 5255:                         }
 5256:                         if ($userdomain ne $env{'request.role.domain'}) {
 5257:                             my $item = "/$crsdom/$crsnum" ;
 5258:                             if ($sec ne '') {
 5259:                                 $item .= "/$sec";
 5260:                             }
 5261:                             $item .= '_st';
 5262:                             next if (&restricted_dom($context,$item,$userdomain,$username,$role,$startdate,
 5263:                                                      $enddate,$crsdom,$crsnum,$sec,$credits,\%process_by,
 5264:                                                      \%instdoms,\%got_role_approvals,\%got_instdoms,\%reject,
 5265:                                                      \%pending,\%notifydc));
 5266:                         }
 5267:                         &modifystudent($userdomain,$username,$cid,$sec,
 5268:                                        $desiredhost,$context);
 5269:                         $roleresult =
 5270:                             &Apache::lonnet::modifystudent
 5271:                                 ($userdomain,$username,$id,$amode,$password,
 5272:                                  $fname,$mname,$lname,$gen,$sec,$enddate,
 5273:                                  $startdate,$env{'form.forceid'},
 5274:                                  $desiredhost,$email,'manual','',$cid,
 5275:                                  '',$context,$inststatus,$credits);
 5276:                         $userresult = $roleresult;
 5277:                     } else {
 5278:                         my $possrole;
 5279:                         if ($role ne '') {
 5280:                             if ($context eq 'course' || $setting eq 'course') {
 5281:                                 if ($customroles{$role}) {
 5282:                                     $role = 'cr_'.$env{'user.domain'}.'_'.
 5283:                                             $env{'user.name'}.'_'.$role;
 5284:                                 }
 5285:                                 $possrole = $role;
 5286:                                 if ($possrole =~ /^cr_/) {
 5287:                                     $possrole =~ s{_}{/}g;
 5288:                                 }
 5289:                                 if (($role ne 'cc') && ($role ne 'co')) {
 5290:                                    if (@secs > 1) {
 5291:                                         $multiple = 1;
 5292:                                         my $prefix = "/$crsdom/$crsnum";
 5293:                                         foreach my $sec (@secs) {
 5294:                                             if ($userdomain ne $env{'request.role.domain'}) {
 5295:                                                 my $item = $prefix;
 5296:                                                 if ($sec ne '') {
 5297:                                                     $item .= "/$sec";
 5298:                                                 }
 5299:                                                 $item .= '_'.$possrole;
 5300:                                                 next if (&restricted_dom($context,$item,$userdomain,$username,$possrole,
 5301:                                                                          $startdate,$enddate,$crsdom,$crsnum,$sec,
 5302:                                                                          $credits,\%process_by,\%instdoms,\%got_role_approvals,
 5303:                                                                          \%got_instdoms,\%reject,\%pending,\%notifydc));
 5304:                                             }
 5305:                                             ($userres{$sec},$authres{$sec},$roleres{$sec},$idres{$sec}) =
 5306:                                             &modifyuserrole($context,$setting,
 5307:                                                 $changeauth,$cid,$userdomain,$username,
 5308:                                                 $id,$amode,$password,$fname,
 5309:                                                 $mname,$lname,$gen,$sec,
 5310:                                                 $env{'form.forceid'},$desiredhost,
 5311:                                                 $email,$role,$enddate,
 5312:                                                 $startdate,$checkid,$inststatus);
 5313:                                         }
 5314:                                     } elsif (@secs > 0) {
 5315:                                         $singlesec = $secs[0];
 5316:                                     }
 5317:                                 }
 5318:                             } else {
 5319:                                 $possrole = $role;
 5320:                             }
 5321:                         }
 5322:                         if (!$multiple) {
 5323:                             if (($userdomain ne $env{'request.role.domain'}) && ($role ne '')) {
 5324:                                 my $item = "/$crsdom/$crsnum";
 5325:                                 if ($singlesec ne '') {
 5326:                                     $item .= "/$singlesec";
 5327:                                 }
 5328:                                 $item .= '_'.$possrole;
 5329:                                 next if (&restricted_dom($context,$item,$userdomain,$username,$possrole,$startdate,$enddate,
 5330:                                                          $crsdom,$crsnum,$singlesec,$credits,\%process_by,\%instdoms,
 5331:                                                          \%got_role_approvals,\%got_instdoms,\%reject,\%pending,\%notifydc));
 5332:                             }
 5333:                             ($userresult,$authresult,$roleresult,$idresult) = 
 5334:                                 &modifyuserrole($context,$setting,
 5335:                                                 $changeauth,$cid,$userdomain,$username, 
 5336:                                                 $id,$amode,$password,$fname,
 5337:                                                 $mname,$lname,$gen,$singlesec,
 5338:                                                 $env{'form.forceid'},$desiredhost,
 5339:                                                 $email,$role,$enddate,$startdate,
 5340:                                                 $checkid,$inststatus);
 5341:                         }
 5342:                     }
 5343:                     if ($multiple) {
 5344:                         foreach my $sec (sort(keys(%userres))) {
 5345:                             $flushc =
 5346:                                 &user_change_result($r,$userres{$sec},$authres{$sec},
 5347:                                                     $roleres{$sec},$idres{$sec},\%counts,$flushc,
 5348:                                                     $username,$userdomain,\%userchg);
 5349: 
 5350:                         }
 5351:                     } else {
 5352:                         $flushc = 
 5353:                             &user_change_result($r,$userresult,$authresult,
 5354:                                                 $roleresult,$idresult,\%counts,$flushc,
 5355:                                                 $username,$userdomain,\%userchg);
 5356:                     }
 5357:                 }
 5358:                 &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last user');
 5359:             } # end of loop
 5360:             $r->print('</ul>');
 5361:             &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 5362:         }
 5363:         # Flush the course logs so reverse user roles immediately updated
 5364:         $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 5365:         $r->print("</p>\n<p>\n".&mt('Processed [quant,_1,user].',$counts{'user'}).
 5366:                   "</p>\n");
 5367:         if ($counts{'role'} > 0) {
 5368:             $r->print("<p>\n".
 5369:                       &mt('Roles added for [quant,_1,user].',$counts{'role'}).' '.
 5370:                       &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.').
 5371:                       "</p>\n");
 5372:         } else {
 5373:             $r->print('<p>'.&mt('No roles added').'</p>');
 5374:         }
 5375:         if ($counts{'auth'} > 0) {
 5376:             $r->print("<p>\n".
 5377:                       &mt('Authentication changed for [_1] existing users.',
 5378:                           $counts{'auth'})."</p>\n");
 5379:         }
 5380:         $r->print(&print_namespacing_alerts($domain,\%alerts,\%curr_rules));
 5381:         $r->print(&passwdrule_alerts($domain,\%showpasswdrules));
 5382:         if (keys(%reject)) {
 5383:             $r->print(&print_roles_rejected($context,\%reject));
 5384:         }
 5385:         if (keys(%pending)) {
 5386:             $r->print(&print_roles_queued($context,\%pending,\%notifydc));
 5387:         }
 5388:         #####################################
 5389:         # Display list of students to drop  #
 5390:         #####################################
 5391:         if ($env{'form.fullup'} eq 'yes') {
 5392:             $r->print('<h3>'.&mt('Students to Drop')."</h3>\n");
 5393:             #  Get current classlist
 5394:             my $classlist = &Apache::loncoursedata::get_classlist();
 5395:             if (! defined($classlist)) {
 5396:                 $r->print('<p class="LC_info">'.
 5397:                           &mt('There are no students with current/future access to the course.').
 5398:                           '</p>'."\n");
 5399:             } elsif (ref($classlist) eq 'HASH') {
 5400:                 # Remove the students we just added from the list of students.
 5401:                 foreach my $line (@userdata) {
 5402:                     my %entries=&Apache::loncommon::record_sep($line);
 5403:                     unless (($entries{$fields{'username'}} eq '') ||
 5404:                             (!defined($entries{$fields{'username'}}))) {
 5405:                         delete($classlist->{$entries{$fields{'username'}}.
 5406:                                                 ':'.$domain});
 5407:                     }
 5408:                 }
 5409:                 # Print out list of dropped students.
 5410:                 &show_drop_list($r,$classlist,'nosort',$permission);
 5411:             }
 5412:         }
 5413:     } # end of unless
 5414:     return 'ok';
 5415: }
 5416: 
 5417: sub print_namespacing_alerts {
 5418:     my ($domain,$alerts,$curr_rules) = @_;
 5419:     my $output;
 5420:     if (ref($alerts) eq 'HASH') {
 5421:         if (keys(%{$alerts}) > 0) {
 5422:             if (ref($alerts->{'username'}) eq 'HASH') {
 5423:                 foreach my $dom (sort(keys(%{$alerts->{'username'}}))) {
 5424:                     my $count;
 5425:                     if (ref($alerts->{'username'}{$dom}) eq 'HASH') {
 5426:                         $count = keys(%{$alerts->{'username'}{$dom}});
 5427:                     }
 5428:                     my $domdesc = &Apache::lonnet::domain($domain,'description');
 5429:                     if (ref($curr_rules->{$dom}) eq 'HASH') {
 5430:                         $output .= &Apache::loncommon::instrule_disallow_msg(
 5431:                                         'username',$domdesc,$count,'upload');
 5432:                     }
 5433:                     $output .= &Apache::loncommon::user_rule_formats($dom,
 5434:                                    $domdesc,$curr_rules->{$dom}{'username'},
 5435:                                    'username');
 5436:                 }
 5437:             }
 5438:             if (ref($alerts->{'id'}) eq 'HASH') {
 5439:                 foreach my $dom (sort(keys(%{$alerts->{'id'}}))) {
 5440:                     my $count;
 5441:                     if (ref($alerts->{'id'}{$dom}) eq 'HASH') {
 5442:                         $count = keys(%{$alerts->{'id'}{$dom}});
 5443:                     }
 5444:                     my $domdesc = &Apache::lonnet::domain($domain,'description');
 5445:                     if (ref($curr_rules->{$dom}) eq 'HASH') {
 5446:                         $output .= &Apache::loncommon::instrule_disallow_msg(
 5447:                                               'id',$domdesc,$count,'upload');
 5448:                     }
 5449:                     $output .= &Apache::loncommon::user_rule_formats($dom,
 5450:                                     $domdesc,$curr_rules->{$dom}{'id'},'id');
 5451:                 }
 5452:             }
 5453:         }
 5454:     }
 5455: }
 5456: 
 5457: sub passwdrule_alerts {
 5458:     my ($domain,$passwdrules) = @_;
 5459:     my $warning;
 5460:     if (ref($passwdrules) eq 'HASH') {
 5461:         my %showrules = %{$passwdrules};
 5462:         if (keys(%showrules)) {
 5463:             my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 5464:             $warning = '<b>'.&mt('Password requirement(s) unmet for one or more users:').'</b><ul>';
 5465:             if ($showrules{'min'}) {
 5466:                 my $min = $passwdconf{'min'};
 5467:                 if ($min eq '') {
 5468:                     $min = $Apache::lonnet::passwdmin;
 5469:                 }
 5470:                 $warning .= '<li>'.&mt('minimum [quant,_1,character]',$min).'</li>';
 5471:             }
 5472:             if ($showrules{'max'}) {
 5473:                 $warning .= '<li>'.&mt('maximum [quant,_1,character]',$passwdconf{'max'}).'</li>';
 5474:             }
 5475:             if ($showrules{'uc'}) {
 5476:                 $warning .= '<li>'.&mt('contain at least one upper case letter').'</li>';
 5477:             }
 5478:             if ($showrules{'lc'}) {
 5479:                 $warning .= '<li>'.&mt('contain at least one lower case letter').'</li>';
 5480:             }
 5481:             if ($showrules{'num'}) {
 5482:                 $warning .= '<li>'.&mt('contain at least one number').'</li>';
 5483:             }
 5484:             if ($showrules{'spec'}) {
 5485:                 $warning .= '<li>'.&mt('contain at least one non-alphanumeric').'</li>';
 5486:             }
 5487:             $warning .= '</ul>';
 5488:         }
 5489:     }
 5490:     return $warning;
 5491: }
 5492: 
 5493: sub user_change_result {
 5494:     my ($r,$userresult,$authresult,$roleresult,$idresult,$counts,$flushc,
 5495:         $username,$userdomain,$userchg) = @_;
 5496:     my $okresult = 0;
 5497:     my @status;
 5498:     if ($userresult ne 'ok') {
 5499:         if ($userresult =~ /^error:(.+)$/) {
 5500:             my $error = $1;
 5501:             push(@status,
 5502:                  &mt('[_1]: Unable to add/modify: [_2]','<b>'.$username.':'.$userdomain.'</b>',$error));
 5503:         }
 5504:     } else {
 5505:         $counts->{'user'} ++;
 5506:         $okresult = 1;
 5507:     }
 5508:     if ($authresult ne 'ok') {
 5509:         if ($authresult =~ /^error:(.+)$/) {
 5510:             my $error = $1;
 5511:             push(@status, 
 5512:                  &mt('[_1]: Unable to modify authentication: [_2]','<b>'.$username.':'.$userdomain.'</b>',$error));
 5513:         } 
 5514:     } else {
 5515:         $counts->{'auth'} ++;
 5516:         $okresult = 1;
 5517:     }
 5518:     if ($roleresult ne 'ok') {
 5519:         if ($roleresult =~ /^error:(.+)$/) {
 5520:             my $error = $1;
 5521:             push(@status,
 5522:                  &mt('[_1]: Unable to add role: [_2]','<b>'.$username.':'.$userdomain.'</b>',$error));
 5523:         }
 5524:     } else {
 5525:         $counts->{'role'} ++;
 5526:         $okresult = 1;
 5527:     }
 5528:     if ($okresult) {
 5529:         $flushc++;
 5530:         $userchg->{$username.':'.$userdomain}=1;
 5531:         if ($flushc>15) {
 5532:             $r->rflush;
 5533:             $flushc=0;
 5534:         }
 5535:     }
 5536:     if ($idresult) {
 5537:         push(@status,$idresult);
 5538:     }
 5539:     if (@status) {
 5540:         $r->print('<li>'.join('<br />',@status).'</li>');
 5541:     }
 5542:     return $flushc;
 5543: }
 5544: 
 5545: # ========================================================= Menu Phase Two Drop
 5546: sub print_drop_menu {
 5547:     my ($r,$context,$permission,$crstype) = @_;
 5548:     my $heading;
 5549:     if ($crstype eq 'Community') {
 5550:         $heading = &mt("Drop Members");
 5551:     } else {
 5552:         $heading = &mt("Drop Students");
 5553:     }
 5554:     $r->print('<h3>'.$heading.'</h3>'."\n".
 5555:               '<form name="studentform" method="post" action="">'."\n");
 5556:     my $classlist = &Apache::loncoursedata::get_classlist();
 5557:     if (! defined($classlist)) {
 5558:         my $msg = '';
 5559:         if ($crstype eq 'Community') {
 5560:             $msg = &mt('There are no members currently enrolled.');
 5561:         } else {
 5562:             $msg = &mt('There are no students currently enrolled.');
 5563:         }
 5564:         $r->print('<p class="LC_info">'.$msg."</p>\n");
 5565:     } else {
 5566:         &show_drop_list($r,$classlist,'nosort',$permission,$crstype);
 5567:     }
 5568:     $r->print('</form>');
 5569:     return;
 5570: }
 5571: 
 5572: # ================================================================== Phase four
 5573: 
 5574: sub update_user_list {
 5575:     my ($r,$context,$setting,$choice,$crstype) = @_;
 5576:     my $now = time;
 5577:     my $count=0;
 5578:     if ($context eq 'course') {
 5579:         $crstype = &Apache::loncommon::course_type();
 5580:     }
 5581:     my (@changelist,%got_role_approvals,%got_instdoms,%process_by,%instdoms,
 5582:         %pending,%reject,%notifydc);
 5583:     if ($choice eq 'drop') {
 5584:         @changelist = &Apache::loncommon::get_env_multiple('form.droplist');
 5585:     } else {
 5586:         @changelist = &Apache::loncommon::get_env_multiple('form.actionlist');
 5587:     }
 5588:     my %result_text = ( ok    => { 'revoke'   => 'Revoked',
 5589:                                    'delete'   => 'Deleted',
 5590:                                    'reenable' => 'Re-enabled',
 5591:                                    'activate' => 'Activated',
 5592:                                    'chgdates' => 'Changed Access Dates for',
 5593:                                    'chgsec'   => 'Changed section(s) for',
 5594:                                    'drop'     => 'Dropped',
 5595:                                  },
 5596:                         error => {'revoke'    => 'revoking',
 5597:                                   'delete'    => 'deleting',
 5598:                                   'reenable'  => 're-enabling',
 5599:                                   'activate'  => 'activating',
 5600:                                   'chgdates'  => 'changing access dates for',
 5601:                                   'chgsec'    => 'changing section for',
 5602:                                   'drop'      => 'dropping',
 5603:                                  },
 5604:                       );
 5605:     my ($startdate,$enddate);
 5606:     if ($choice eq 'chgdates' || $choice eq 'reenable' || $choice eq 'activate') {
 5607:         ($startdate,$enddate) = &get_dates_from_form();
 5608:     }
 5609:     foreach my $item (@changelist) {
 5610:         my ($role,$uname,$udom,$cid,$sec,$scope,$result,$type,$locktype,
 5611:             @sections,$scopestem,$singlesec,$showsecs,$warn_singlesec,
 5612:             $nothingtodo,$keepnosection,$credits,$instsec,$cdom,$cnum);
 5613:         if ($choice eq 'drop') {
 5614:             ($uname,$udom,$sec) = split(/:/,$item,-1);
 5615:             $role = 'st';
 5616:             $cid = $env{'request.course.id'};
 5617:             $scopestem = '/'.$cid;
 5618:             $scopestem =~s/\_/\//g;
 5619:             if ($sec eq '') {
 5620:                 $scope = $scopestem;
 5621:             } else {
 5622:                 $scope = $scopestem.'/'.$sec;
 5623:             }
 5624:         } elsif ($context eq 'course') {
 5625:             ($uname,$udom,$role,$sec,$type,$locktype,$credits,$instsec) =
 5626:                 split(/\:/,$item,8);
 5627:             $instsec = &unescape($instsec);
 5628:             $cid = $env{'request.course.id'};
 5629:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5630:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5631:             $scopestem = '/'.$cid;
 5632:             $scopestem =~s/\_/\//g;
 5633:             if ($sec eq '') {
 5634:                 $scope = $scopestem;
 5635:             } else {
 5636:                 $scope = $scopestem.'/'.$sec;
 5637:             }
 5638:         } elsif ($context eq 'author') {
 5639:             ($uname,$udom,$role) = split(/\:/,$item,-1);
 5640:             $scope = '/'.$env{'user.domain'}.'/'.$env{'user.name'};
 5641:             $cdom = $env{'user.domain'};
 5642:             $cnum = $env{'user.name'};
 5643:         } elsif ($context eq 'domain') {
 5644:             if ($setting eq 'domain') {
 5645:                 ($role,$uname,$udom) = split(/\:/,$item,-1);
 5646:                 $scope = '/'.$env{'request.role.domain'}.'/';
 5647:                 $cdom = $env{'request.role.domain'};
 5648:             } elsif ($setting eq 'author') { 
 5649:                 ($uname,$udom,$role,$scope) = split(/\:/,$item);
 5650:                 (undef,$cdom,$cnum) = split(/\//,$scope);
 5651:             } elsif ($setting eq 'course') {
 5652:                 ($uname,$udom,$role,$cid,$sec,$type,$locktype,$credits,$instsec) = 
 5653:                     split(/\:/,$item,9);
 5654:                 ($cdom,$cnum) = split('_',$cid);
 5655:                 $instsec = &unescape($instsec);
 5656:                 $scope = '/'.$cid;
 5657:                 $scope =~s/\_/\//g;
 5658:                 if ($sec ne '') {
 5659:                     $scope .= '/'.$sec;
 5660:                 }
 5661:             }
 5662:         }
 5663:         my $plrole = &Apache::lonnet::plaintext($role,$crstype);
 5664:         my $start = $env{'form.'.$item.'_start'};
 5665:         my $end = $env{'form.'.$item.'_end'};
 5666:         if ($choice eq 'drop') {
 5667:             # drop students
 5668:             $end = $now;
 5669:             $type = 'manual';
 5670:             $result =
 5671:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
 5672:         } elsif ($choice eq 'revoke') {
 5673:             # revoke or delete user role
 5674:             $end = $now; 
 5675:             if ($role eq 'st') {
 5676:                 $result = 
 5677:                     &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5678:             } else {
 5679:                 $result = 
 5680:                     &Apache::lonnet::revokerole($udom,$uname,$scope,$role,
 5681:                                                 '','',$context);
 5682:             }
 5683:         } elsif ($choice eq 'delete') {
 5684:             if ($role eq 'st') {
 5685:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$now,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5686:             }
 5687:             $result =
 5688:                 &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$now,
 5689:                                             $start,1,'',$context);
 5690:         } else {
 5691:             #reenable, activate, change access dates or change section
 5692:             if ($choice ne 'chgsec') {
 5693:                 $start = $startdate; 
 5694:                 $end = $enddate;
 5695:             }
 5696:             my $id = $scope.'_'.$role;
 5697:             if ($choice eq 'reenable') {
 5698:                 next if (&restricted_dom($context,$id,$udom,$uname,$role,$now,$end,$cdom,$cnum,
 5699:                                          $sec,$credits,\%process_by,\%instdoms,\%got_role_approvals,
 5700:                                          \%got_instdoms,\%reject,\%pending,\%notifydc));
 5701:                 if ($role eq 'st') {
 5702:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5703:                 } else {
 5704:                     $result = 
 5705:                         &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
 5706:                                                     $now,'','',$context);
 5707:                 }
 5708:             } elsif ($choice eq 'activate') {
 5709:                 next if (&restricted_dom($context,$id,$udom,$uname,$role,$now,$end,$cdom,$cnum,
 5710:                                          $sec,$credits,\%process_by,\%instdoms,\%got_role_approvals,
 5711:                                          \%got_instdoms,\%reject,\%pending,\%notifydc));
 5712:                 if ($role eq 'st') {
 5713:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5714:                 } else {
 5715:                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
 5716:                                             $now,'','',$context);
 5717:                 }
 5718:             } elsif ($choice eq 'chgdates') {
 5719:                 next if (&restricted_dom($context,$id,$udom,$uname,$role,$start,$end,$cdom,$cnum,
 5720:                                          $sec,$credits,\%process_by,\%instdoms,\%got_role_approvals,
 5721:                                          \%got_instdoms,\%reject,\%pending,\%notifydc));
 5722:                 if ($role eq 'st') {
 5723:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5724:                 } else {
 5725:                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
 5726:                                                 $start,'','',$context);
 5727:                 }
 5728:             } elsif ($choice eq 'chgsec') {
 5729:                 my (@newsecs,$revresult,$nochg,@retained);
 5730:                 if (($role ne 'cc') && ($role ne 'co')) {
 5731:                     my @secs = sort(split(/,/,$env{'form.newsecs'}));
 5732:                     if (@secs) {
 5733:                         my %curr_groups = &Apache::longroup::coursegroups();
 5734:                         foreach my $sec (@secs) {
 5735:                             next if (($sec =~ /\W/) || ($sec eq 'none') ||
 5736:                             (exists($curr_groups{$sec})));
 5737:                             push(@newsecs,$sec);
 5738:                         }
 5739:                     }
 5740:                 }
 5741:                 # remove existing section if not to be retained.   
 5742:                 if (!$env{'form.retainsec'} || ($role eq 'st')) {
 5743:                     if ($sec eq '') {
 5744:                         if (@newsecs == 0) {
 5745:                             $result = 'ok';
 5746:                             $nochg = 1;
 5747:                             $nothingtodo = 1;
 5748:                         } else {
 5749:                             $revresult =
 5750:                                 &Apache::lonnet::revokerole($udom,$uname,
 5751:                                                             $scope,$role,
 5752:                                                             '','',$context);
 5753:                         } 
 5754:                     } else {
 5755:                         if (@newsecs > 0) {
 5756:                             if (grep(/^\Q$sec\E$/,@newsecs)) {
 5757:                                 push(@retained,$sec);
 5758:                             } else {
 5759:                                 $revresult =
 5760:                                     &Apache::lonnet::revokerole($udom,$uname,
 5761:                                                                 $scope,$role,
 5762:                                                                 '','',$context);
 5763:                             }
 5764:                         } else {
 5765:                             $revresult =
 5766:                                 &Apache::lonnet::revokerole($udom,$uname,
 5767:                                                             $scope,$role,
 5768:                                                             '','',$context);
 5769:                         }
 5770:                     }
 5771:                 } else {
 5772:                     if ($sec eq '') {
 5773:                         $nochg = 1;
 5774:                         $keepnosection = 1;
 5775:                     } else {
 5776:                         push(@retained,$sec);
 5777:                     }
 5778:                 }
 5779:                 # add new sections
 5780:                 my (@diffs,@shownew);
 5781:                 if (@retained) {
 5782:                     @diffs = &Apache::loncommon::compare_arrays(\@retained,\@newsecs);
 5783:                 } else {
 5784:                     @diffs = @newsecs;
 5785:                 }
 5786:                 if (@newsecs == 0) {
 5787:                     if ($nochg) {
 5788:                         $result = 'ok';
 5789:                         $nothingtodo = 1;
 5790:                     } else {
 5791:                         if ($role eq 'st') {
 5792:                             $result = 
 5793:                                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,undef,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5794:                         } else {
 5795:                             my $newscope = $scopestem;
 5796:                             $result = &Apache::lonnet::assignrole($udom,$uname,$newscope,$role,$end,$start,'','',$context);
 5797:                         }
 5798:                     }
 5799:                     $showsecs = &mt('No section');
 5800:                 } elsif (@diffs == 0) {
 5801:                     $result = 'ok';
 5802:                     $nothingtodo = 1;
 5803:                 } else {
 5804:                     foreach my $newsec (@newsecs) {
 5805:                         if (!grep(/^\Q$newsec\E$/,@retained)) {
 5806:                             if ($role eq 'st') {
 5807:                                 $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$newsec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5808:                                 if (@newsecs > 1) {
 5809:                                     my $showsingle; 
 5810:                                     if ($newsec eq '') {
 5811:                                         $showsingle = &mt('No section');
 5812:                                     } else {
 5813:                                         $showsingle = $newsec;
 5814:                                     }
 5815:                                     if ($crstype eq 'Community') {
 5816:                                         $warn_singlesec = &mt('Although more than one section was indicated, a role was only added for the first section - [_1], as each community member may only be in one section at a time.','<i>'.$showsingle.'</i>');
 5817:                                     } else { 
 5818:                                         $warn_singlesec = &mt('Although more than one section was indicated, a role was only added for the first section - [_1], as each student may only be in one section of a course at a time.','<i>'.$showsingle.'</i>');
 5819:                                     }
 5820:                                     $showsecs = $showsingle; 
 5821:                                     last;
 5822:                                 } else {
 5823:                                     if ($newsec eq '') {
 5824:                                         $showsecs = &mt('No section');
 5825:                                     } else {
 5826:                                         $showsecs = $newsec;
 5827:                                     }
 5828:                                 }
 5829:                             } else {
 5830:                                 my $newscope = $scopestem;
 5831:                                 if ($newsec ne '') {
 5832:                                    $newscope .= '/'.$newsec;
 5833:                                    push(@shownew,$newsec); 
 5834:                                 }
 5835:                                 $result = &Apache::lonnet::assignrole($udom,$uname,
 5836:                                                         $newscope,$role,$end,$start);
 5837:                                 
 5838:                             }
 5839:                         }
 5840:                     }
 5841:                 }
 5842:                 unless ($role eq 'st') {
 5843:                     unless ($showsecs) {
 5844:                         my @tolist = sort(@shownew,@retained);
 5845:                         if ($keepnosection) {
 5846:                             push(@tolist,&mt('No section'));
 5847:                         }
 5848:                         $showsecs = join(', ',@tolist);
 5849:                     }
 5850:                 }
 5851:             }
 5852:         }
 5853:         my $extent = $scope;
 5854:         if ($choice eq 'drop' || $context eq 'course') {
 5855:             my ($cnum,$cdom,$cdesc) = &get_course_identity($cid);
 5856:             if ($cdesc) {
 5857:                 $extent = $cdesc;
 5858:             }
 5859:         }
 5860:         if ($result eq 'ok' || $result eq 'ok:') {
 5861:             my $dates;
 5862:             if (($choice eq 'chgsec') || ($choice eq 'chgdates')) {
 5863:                 $dates = &dates_feedback($start,$end,$now);
 5864:             }
 5865:             if ($choice eq 'chgsec') {
 5866:                 if ($nothingtodo) {
 5867:                     $r->print(&mt("Section assignment for role of '[_1]' in [_2] for '[_3]' unchanged.",$plrole,$extent,'<i>'.
 5868:                           &Apache::loncommon::plainname($uname,$udom).
 5869:                           '</i>').' ');
 5870:                     if ($sec eq '') {
 5871:                         $r->print(&mt('[_1]No section[_2] - [_3]','<b>','</b>',$dates));
 5872:                     } else {
 5873:                         $r->print(&mt('Section(s): [_1] - [_2]',
 5874:                                       '<b>'.$showsecs.'</b>',$dates));
 5875:                     }
 5876:                     $r->print('<br />');
 5877:                 } else {
 5878:                     $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]' to [_4] - [_5]",$plrole,$extent,
 5879:                         '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
 5880:                         '<b>'.$showsecs.'</b>',$dates).'<br />');
 5881:                    $count ++;
 5882:                }
 5883:                if ($warn_singlesec) {
 5884:                    $r->print('<div class="LC_warning">'.$warn_singlesec.'</div>');
 5885:                }
 5886:             } elsif ($choice eq 'chgdates') {
 5887:                 $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]' - [_4]",$plrole,$extent, 
 5888:                       '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
 5889:                       $dates).'<br />');
 5890:                $count ++;
 5891:             } else {
 5892:                 $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]'.",$plrole,$extent,
 5893:                       '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>').
 5894:                           '<br />');
 5895:                 $count ++;
 5896:             }
 5897:         } else {
 5898:             $r->print(
 5899:                 &mt("Error $result_text{'error'}{$choice} [_1] in [_2] for '[_3]': [_4].",
 5900:                     $plrole,$extent,
 5901:                     '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
 5902:                     $result).'<br />');
 5903:         }
 5904:     }
 5905:     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n");
 5906:     if ($choice eq 'drop') {
 5907:         $r->print('<input type="hidden" name="action" value="listusers" />'."\n".
 5908:                   '<input type="hidden" name="Status" value="Active" />'."\n".
 5909:                   '<input type="hidden" name="showrole" value="st" />'."\n");
 5910:     } else {
 5911:         foreach my $item ('action','sortby','roletype','showrole','Status','secfilter','grpfilter') {
 5912:             if ($env{'form.'.$item} ne '') {
 5913:                 $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.
 5914:                           '" />'."\n");
 5915:             }
 5916:         }
 5917:     }
 5918:     $r->print('<p><b>'.&mt("$result_text{'ok'}{$choice} [quant,_1,user role,user roles,no user roles].",$count).'</b></p>');
 5919:     if ($count > 0) {
 5920:         if ($choice eq 'revoke' || $choice eq 'drop') {
 5921:             $r->print('<p>'.&mt('Re-enabling will re-activate data for the role.').'</p>');
 5922:         }
 5923:         # Flush the course logs so reverse user roles immediately updated
 5924:         $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 5925:     }
 5926:     if ($env{'form.makedatesdefault'}) {
 5927:         if ($choice eq 'chgdates' || $choice eq 'reenable' || $choice eq 'activate') {
 5928:             $r->print(&make_dates_default($startdate,$enddate,$context,$crstype));
 5929:         }
 5930:     }
 5931:     if (keys(%reject)) {
 5932:         $r->print(&print_roles_rejected($context,\%reject));
 5933:     }
 5934:     if (keys(%pending)) {
 5935:         $r->print(&print_roles_queued($context,\%pending,\%notifydc));
 5936:     }
 5937:     my $linktext = &mt('Display User Lists');
 5938:     if ($choice eq 'drop') {
 5939:         $linktext = &mt('Display current class roster');
 5940:     }
 5941:     $r->print(
 5942:         &Apache::lonhtmlcommon::actionbox(
 5943:             ['<a href="javascript:document.studentform.submit()">'.$linktext.'</a>'])
 5944:        .'</form>'."\n");
 5945: }
 5946: 
 5947: sub dates_feedback {
 5948:     my ($start,$end,$now) = @_;
 5949:     my $dates;
 5950:     if ($start < $now) {
 5951:         if ($end == 0) {
 5952:             $dates = &mt('role(s) active now; no end date');
 5953:         } elsif ($end > $now) {
 5954:             $dates = &mt('role(s) active now; ends [_1].',&Apache::lonlocal::locallocaltime($end));
 5955:         } else {
 5956:             $dates = &mt('role(s) expired: [_1].',&Apache::lonlocal::locallocaltime($end));
 5957:         }
 5958:      } else {
 5959:         if ($end == 0 || $end > $now) {
 5960:             $dates = &mt('future role(s); starts: [_1].',&Apache::lonlocal::locallocaltime($start));
 5961:         } else {
 5962:             $dates = &mt('role(s) expired: [_1].',&Apache::lonlocal::locallocaltime($end));
 5963:         }
 5964:     }
 5965:     return $dates;
 5966: }
 5967: 
 5968: sub classlist_drop {
 5969:     my ($scope,$uname,$udom,$now) = @_;
 5970:     my ($cdom,$cnum) = ($scope=~m{^/($match_domain)/($match_courseid)});
 5971:     if (&Apache::lonnet::is_course($cdom,$cnum)) {
 5972:         if (!&active_student_roles($cnum,$cdom,$uname,$udom)) {
 5973:             my %user;
 5974:             my $result = &update_classlist($cdom,$cnum,$udom,$uname,\%user,$now);
 5975:             return &mt('Drop from classlist: [_1]',
 5976:                        '<b>'.$result.'</b>').'<br />';
 5977:         }
 5978:     }
 5979: }
 5980: 
 5981: sub active_student_roles {
 5982:     my ($cnum,$cdom,$uname,$udom) = @_;
 5983:     my %roles =
 5984:         &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 5985:                                       ['future','active'],['st']);
 5986:     return exists($roles{"$cnum:$cdom:st"});
 5987: }
 5988: 
 5989: sub section_check_js {
 5990:     my $groupslist= &get_groupslist();
 5991:     my %js_lt = &Apache::lonlocal::texthash(
 5992:         mayn   => 'may not be used as the name for a section, as it is a reserved word.',
 5993:         plch   => 'Please choose a different section name.',
 5994:         mnot   => 'may not be used as a section name, as it is the name of a course group.',
 5995:         secn   => 'Section names and group names must be distinct. Please choose a different section name.',
 5996:     );
 5997:     &js_escape(\%js_lt);
 5998:     return <<"END";
 5999: function validate(caller) {
 6000:     var groups = new Array($groupslist);
 6001:     var secname = caller.value;
 6002:     if ((secname == 'all') || (secname == 'none')) {
 6003:         alert("'"+secname+"' $js_lt{'mayn'}\\n$js_lt{'plch'}");
 6004:         return 'error';
 6005:     }
 6006:     if (secname != '') {
 6007:         for (var k=0; k<groups.length; k++) {
 6008:             if (secname == groups[k]) {
 6009:                 alert("'"+secname+"' $js_lt{'mnot'}\\n$js_lt{'secn'}");
 6010:                 return 'error';
 6011:             }
 6012:         }
 6013:     }
 6014:     return 'ok';
 6015: }
 6016: END
 6017: }
 6018: 
 6019: sub set_login {
 6020:     my ($dom,$authformkrb,$authformint,$authformloc,$authformlti) = @_;
 6021:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 6022:     my $response;
 6023:     my ($authnum,%can_assign) =
 6024:         &Apache::loncommon::get_assignable_auth($dom);
 6025:     if ($authnum) {
 6026:         $response = &Apache::loncommon::start_data_table();
 6027:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 6028:             $response .= &Apache::loncommon::start_data_table_row().
 6029:                          '<td>'.$authformkrb.'</td>'.
 6030:                          &Apache::loncommon::end_data_table_row()."\n";
 6031:         }
 6032:         if ($can_assign{'int'}) {
 6033:             $response .= &Apache::loncommon::start_data_table_row().
 6034:                          '<td>'.$authformint.'</td>'.
 6035:                          &Apache::loncommon::end_data_table_row()."\n"
 6036:         }
 6037:         if ($can_assign{'loc'}) {
 6038:             $response .= &Apache::loncommon::start_data_table_row().
 6039:                          '<td>'.$authformloc.'</td>'.
 6040:                          &Apache::loncommon::end_data_table_row()."\n";
 6041:         }
 6042:         if ($can_assign{'lti'}) {
 6043:             $response .= &Apache::loncommon::start_data_table_row().
 6044:                          '<td>'.$authformlti.'</td>'.
 6045:                          &Apache::loncommon::end_data_table_row()."\n";
 6046:         }
 6047:         $response .= &Apache::loncommon::end_data_table();
 6048:     }
 6049:     return $response;
 6050: }
 6051: 
 6052: sub course_sections {
 6053:     my ($sections_count,$role,$current_sec,$disabled) = @_;
 6054:     my $output = '';
 6055:     my @sections = (sort {$a <=> $b} keys(%{$sections_count}));
 6056:     my $numsec = scalar(@sections);
 6057:     my $is_selected = ' selected="selected"';
 6058:     if ($numsec <= 1) {
 6059:         $output = '<select name="currsec_'.$role.'"'.$disabled.'>'."\n".
 6060:                   '  <option value="">'.&mt('Select').'</option>'."\n";
 6061:         if ($current_sec eq 'none') {
 6062:             $output .=       
 6063:                   '  <option value=""'.$is_selected.'>'.&mt('No section').'</option>'."\n";
 6064:         } else {
 6065:             $output .=
 6066:                   '  <option value="">'.&mt('No section').'</option>'."\n";
 6067:         }
 6068:         if ($numsec == 1) {
 6069:             if ($current_sec eq $sections[0]) {
 6070:                 $output .=
 6071:                   '  <option value="'.$sections[0].'"'.$is_selected.'>'.$sections[0].'</option>'."\n";
 6072:             } else {
 6073:                 $output .=  
 6074:                   '  <option value="'.$sections[0].'" >'.$sections[0].'</option>'."\n";
 6075:             }
 6076:         }
 6077:     } else {
 6078:         $output = '<select name="currsec_'.$role.'" ';
 6079:         my $multiple = 4;
 6080:         if (scalar(@sections) < 4) { $multiple = scalar(@sections); }
 6081:         if ($role eq 'st') {
 6082:             $output .= $disabled.'>'."\n".
 6083:                        '  <option value="">'.&mt('Select').'</option>'."\n";
 6084:             if ($current_sec eq 'none') {
 6085:                 $output .= 
 6086:                        '  <option value=""'.$is_selected.'>'.&mt('No section')."</option>\n";
 6087:             } else {
 6088:                 $output .=
 6089:                        '  <option value="">'.&mt('No section')."</option>\n";
 6090:             }
 6091:         } else {
 6092:             $output .= 'multiple="multiple" size="'.$multiple.'"'.$disabled.'>'."\n";
 6093:         }
 6094:         foreach my $sec (@sections) {
 6095:             if ($current_sec eq $sec) {
 6096:                 $output .= '<option value="'.$sec.'"'.$is_selected.'>'.$sec."</option>\n";
 6097:             } else {
 6098:                 $output .= '<option value="'.$sec.'">'.$sec."</option>\n";
 6099:             }
 6100:         }
 6101:     }
 6102:     $output .= '</select>';
 6103:     return $output;
 6104: }
 6105: 
 6106: sub get_groupslist {
 6107:     my $groupslist;
 6108:     my %curr_groups = &Apache::longroup::coursegroups();
 6109:     if (%curr_groups) {
 6110:         $groupslist = join('","',sort(keys(%curr_groups)));
 6111:         $groupslist = '"'.$groupslist.'"';
 6112:     }
 6113:     return $groupslist; 
 6114: }
 6115: 
 6116: sub setsections_javascript {
 6117:     my ($formname,$groupslist,$mode,$checkauth,$crstype,$showcredits) = @_;
 6118:     my ($checkincluded,$finish,$rolecode,$setsection_js);
 6119:     if ($mode eq 'upload') {
 6120:         $checkincluded = 'formname.name == "'.$formname.'"';
 6121:         $finish = "return 'ok';";
 6122:         $rolecode = "var role = formname.defaultrole.options[formname.defaultrole.selectedIndex].value;\n";
 6123:     } elsif ($formname eq 'cu') {
 6124:         if (($crstype eq 'Course') && ($showcredits)) {
 6125:             $checkincluded = "((role == 'st') && (formname.elements[i-2].checked == true)) || ((role != 'st') && (formname.elements[i-1].checked == true))";
 6126:         } else {
 6127:             $checkincluded = 'formname.elements[i-1].checked == true';
 6128:         }
 6129:         if ($checkauth) {
 6130:             $finish = "var authcheck = auth_check();\n".
 6131:                       "   if (authcheck == 'ok') {\n".
 6132:                       "       formname.submit();\n".
 6133:                       "   }\n";
 6134:         } else {
 6135:             $finish = 'formname.submit()';
 6136:         }
 6137:         $rolecode = "var match = str.split('_');
 6138:                 var role = match[3];\n";
 6139:     } elsif (($formname eq 'enrollstudent') || ($formname eq 'selfenroll')) {
 6140:         $checkincluded = 'formname.name == "'.$formname.'"';
 6141:         if ($checkauth) {
 6142:             $finish = "var authcheck = auth_check();\n".
 6143:                       "   if (authcheck == 'ok') {\n".
 6144:                       "       formname.submit();\n".
 6145:                       "   }\n";
 6146:         } else {
 6147:             $finish = 'formname.submit()';
 6148:         }
 6149:         $rolecode = "var match = str.split('_');
 6150:                 var role = match[1];\n";
 6151:     } else {
 6152:         $checkincluded = 'formname.name == "'.$formname.'"'; 
 6153:         $finish = "seccheck = 'ok';";
 6154:         $rolecode = "var match = str.split('_');
 6155:                 var role = match[1];\n";
 6156:         $setsection_js = "var seccheck = 'alert';"; 
 6157:     }
 6158:     my %alerts = &Apache::lonlocal::texthash(
 6159:                     secd => 'Section designations do not apply to Course Coordinator roles.',
 6160:                     sedn => 'Section designations do not apply to Coordinator roles.',
 6161:                     accr => 'A course coordinator role will be added with access to all sections.',
 6162:                     acor => 'A coordinator role will be added with access to all sections',
 6163:                     inea => 'In each course, each user may only have one student role at a time.',
 6164:                     inco => 'In each community, each user may only have one member role at a time.',
 6165:                     youh => 'You had selected',
 6166:                     secs => 'sections.',
 6167:                     plmo => 'Please modify your selections so they include no more than one section.',
 6168:                     mayn => 'may not be used as the name for a section, as it is a reserved word.',
 6169:                     plch => 'Please choose a different section name.',
 6170:                     mnot => 'may not be used as a section name, as it is the name of a course group.',
 6171:                     secn => 'Section names and group names must be distinct. Please choose a different section name.',
 6172:                     nonw => 'Section names may only contain letters or numbers.',
 6173:                  );
 6174:     &js_escape(\%alerts);
 6175:     $setsection_js .= <<"ENDSECCODE";
 6176: 
 6177: function setSections(formname,crstype) {
 6178:     var re1 = /^currsec_/;
 6179:     var re2 =/\\W/;
 6180:     var trimleading = /^\\s+/;
 6181:     var trimtrailing = /\\s+\$/;
 6182:     var groups = new Array($groupslist);
 6183:     for (var i=0;i<formname.elements.length;i++) {
 6184:         var str = formname.elements[i].name;
 6185:         if (typeof(str) === "undefined") {
 6186:             continue;
 6187:         }
 6188:         var checkcurr = str.match(re1);
 6189:         if (checkcurr != null) {
 6190:             var num = i;
 6191:             $rolecode
 6192:             if ($checkincluded) {
 6193:                 if (role == 'cc' || role == 'co') {
 6194:                     if (role == 'cc') {
 6195:                         alert("$alerts{'secd'}\\n$alerts{'accr'}");
 6196:                     } else {
 6197:                         alert("$alerts{'sedn'}\\n$alerts{'acor'}");
 6198:                     }
 6199:                 } else {
 6200:                     var sections = '';
 6201:                     var numsec = 0;
 6202:                     var fromexisting = new Array();
 6203:                     for (var j=0; j<formname.elements[num].length; j++) {
 6204:                         if (formname.elements[num].options[j].selected == true ) {
 6205:                             var addsec = formname.elements[num].options[j].value;
 6206:                             if ((addsec != "") && (addsec != null)) {
 6207:                                 fromexisting.push(addsec);
 6208:                                 if (numsec == 0) {
 6209:                                     sections = addsec;
 6210:                                 } else {
 6211:                                     sections = sections + "," +  addsec;
 6212:                                 }
 6213:                                 numsec ++;
 6214:                             }
 6215:                         }
 6216:                     }
 6217:                     var newsecs = formname.elements[num+1].value;
 6218:                     var validsecs = new Array();
 6219:                     var validsecstr = '';
 6220:                     var badsecs = new Array();
 6221:                     if (newsecs != null && newsecs != "") {
 6222:                         var numsplit;
 6223:                         if (newsecs.indexOf(',') == -1) {
 6224:                             numsplit = new Array(newsecs);
 6225:                         } else {
 6226:                             numsplit = newsecs.split(/,/g);
 6227:                         }
 6228:                         for (var m=0; m<numsplit.length; m++) {
 6229:                             var newsec = numsplit[m];
 6230:                             newsec = newsec.replace(trimleading,'');
 6231:                             newsec = newsec.replace(trimtrailing,'');
 6232:                             if (re2.test(newsec) == true) {
 6233:                                 badsecs.push(newsec);
 6234:                             } else {
 6235:                                 if (newsec != '') {
 6236:                                     var isnew = 1;
 6237:                                     if (fromexisting != null) {
 6238:                                         for (var n=0; n<fromexisting.length; n++) {
 6239:                                             if (newsec == fromexisting[n]) {
 6240:                                                 isnew = 0;
 6241:                                             }
 6242:                                         }
 6243:                                     }
 6244:                                     if (isnew == 1) {
 6245:                                         validsecs.push(newsec);
 6246:                                     }
 6247:                                 }
 6248:                             }
 6249:                         }
 6250:                         if (badsecs.length > 0) {
 6251:                             alert("$alerts{'nonw'}\\n$alerts{'plch'}");
 6252:                             return;
 6253:                         }
 6254:                         numsec = numsec + validsecs.length;
 6255:                     }
 6256:                     if ((role == 'st') && (numsec > 1)) {
 6257:                         if (crstype == 'Community') {
 6258:                             alert("$alerts{'inea'} $alerts{'youh'} "+numsec+" $alerts{'secs'}\\n$alerts{'plmo'}");
 6259:                         } else {
 6260:                             alert("$alerts{'inco'} $alerts{'youh'} "+numsec+" $alerts{'secs'}\\n$alerts{'plmo'}");
 6261:                         }
 6262:                         return;
 6263:                     } else {
 6264:                         if (validsecs != null) {
 6265:                             for (var j=0; j<validsecs.length; j++) {
 6266:                                 if (validsecstr == '' || validsecstr == null) {
 6267:                                     validsecstr = validsecs[j];
 6268:                                 } else {
 6269:                                     validsecstr += ','+validsecs[j];
 6270:                                 }
 6271:                                 if ((validsecs[j] == 'all') ||
 6272:                                     (validsecs[j] == 'none')) {
 6273:                                     alert("'"+validsecs[j]+"' $alerts{'mayn'}\\n$alerts{'plch'}");
 6274:                                     return;
 6275:                                 }
 6276:                                 for (var k=0; k<groups.length; k++) {
 6277:                                     if (validsecs[j] == groups[k]) {
 6278:                                         alert("'"+validsecs[j]+"' $alerts{'mnot'}\\n$alerts{'secn'}");
 6279:                                         return;
 6280:                                     }
 6281:                                 }
 6282:                             }
 6283:                         }
 6284:                     }
 6285:                     if ((validsecstr != '') && (validsecstr != null)) {
 6286:                         if ((sections == '') || (sections == null)) {
 6287:                             sections = validsecstr;
 6288:                         } else {
 6289:                             sections = sections + "," + validsecstr;
 6290:                         }
 6291:                     }
 6292:                     formname.elements[num+2].value = sections;
 6293:                 }
 6294:             }
 6295:         }
 6296:     }
 6297:     $finish
 6298: }
 6299: ENDSECCODE
 6300:     return $setsection_js; 
 6301: }
 6302: 
 6303: sub can_create_user {
 6304:     my ($dom,$context,$usertype) = @_;
 6305:     my %domconf = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 6306:     my $cancreate = 1;
 6307:     if (&Apache::lonnet::allowed('mau',$dom)) {
 6308:         return $cancreate;
 6309:     } elsif ($context eq 'domain') {
 6310:         $cancreate = 0;
 6311:         return $cancreate;
 6312:     }
 6313:     if (ref($domconf{'usercreation'}) eq 'HASH') {
 6314:         if (ref($domconf{'usercreation'}{'cancreate'}) eq 'HASH') {
 6315:             if ($context eq 'course' || $context eq 'author' || $context eq 'requestcrs') {
 6316:                 my $creation = $domconf{'usercreation'}{'cancreate'}{$context};
 6317:                 if ($creation eq 'none') {
 6318:                     $cancreate = 0;
 6319:                 } elsif ($creation ne 'any') {
 6320:                     if (defined($usertype)) {
 6321:                         if ($creation ne $usertype) {
 6322:                             $cancreate = 0;
 6323:                         }
 6324:                     }
 6325:                 }
 6326:             }
 6327:         }
 6328:     }
 6329:     return $cancreate;
 6330: }
 6331: 
 6332: sub can_modify_userinfo {
 6333:     my ($context,$dom,$fields,$userroles) = @_;
 6334:     my %domconfig =
 6335:        &Apache::lonnet::get_dom('configuration',['usermodification'],
 6336:                                 $dom);
 6337:     my %canmodify;
 6338:     if (ref($fields) eq 'ARRAY') {
 6339:         foreach my $field (@{$fields}) {
 6340:             $canmodify{$field}  = 0;
 6341:             if (&Apache::lonnet::allowed('mau',$dom)) {
 6342:                 $canmodify{$field} = 1;
 6343:             } else {
 6344:                 if (ref($domconfig{'usermodification'}) eq 'HASH') {
 6345:                     if (ref($domconfig{'usermodification'}{$context}) eq 'HASH') {
 6346:                         if (ref($userroles) eq 'ARRAY') {
 6347:                             foreach my $role (@{$userroles}) {
 6348:                                 my $testrole;
 6349:                                 if ($context eq 'selfcreate') {
 6350:                                     $testrole = $role;
 6351:                                 } else {
 6352:                                     if ($role =~ /^cr\//) {
 6353:                                         $testrole = 'cr';
 6354:                                     } else {
 6355:                                         $testrole = $role;
 6356:                                     }
 6357:                                 }
 6358:                                 if (ref($domconfig{'usermodification'}{$context}{$testrole}) eq 'HASH') {
 6359:                                     if ($domconfig{'usermodification'}{$context}{$testrole}{$field}) {
 6360:                                         $canmodify{$field} = 1;
 6361:                                         last;
 6362:                                     }
 6363:                                 }
 6364:                             }
 6365:                         } else {
 6366:                             foreach my $key (keys(%{$domconfig{'usermodification'}{$context}})) {
 6367:                                 if (ref($domconfig{'usermodification'}{$context}{$key}) eq 'HASH') {
 6368:                                     if ($domconfig{'usermodification'}{$context}{$key}{$field}) {
 6369:                                         $canmodify{$field} = 1;
 6370:                                         last;
 6371:                                     }
 6372:                                 }
 6373:                             }
 6374:                         }
 6375:                     }
 6376:                 } elsif ($context eq 'course') {
 6377:                     if (ref($userroles) eq 'ARRAY') {
 6378:                         if (grep(/^st$/,@{$userroles})) {
 6379:                             $canmodify{$field} = 1;
 6380:                         }
 6381:                     } else {
 6382:                         $canmodify{$field} = 1;
 6383:                     }
 6384:                 }
 6385:             }
 6386:         }
 6387:     }
 6388:     return %canmodify;
 6389: }
 6390: 
 6391: sub can_change_internalpass {
 6392:     my ($uname,$udom,$crstype,$permission) = @_;
 6393:     my $canchange;
 6394:     if (&Apache::lonnet::allowed('mau',$udom)) {
 6395:         $canchange = 1;
 6396:     } elsif ((ref($permission) eq 'HASH') && ($permission->{'mip'}) &&
 6397:              ($udom eq $env{'request.role.domain'})) {
 6398:         unless ($env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'}) {
 6399:             my ($cnum,$cdom) = &get_course_identity();
 6400:             if ((&Apache::lonnet::is_course_owner($cdom,$cnum)) && ($udom eq $env{'user.domain'})) {
 6401:                 my @userstatuses = ('default');
 6402:                 my %userenv = &Apache::lonnet::userenvironment($udom,$uname,'inststatus');
 6403:                 if ($userenv{'inststatus'} ne '') {
 6404:                     @userstatuses =  split(/:/,$userenv{'inststatus'});
 6405:                 }
 6406:                 my $noupdate = 1;
 6407:                 my %passwdconf = &Apache::lonnet::get_passwdconf($cdom);
 6408:                 if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 6409:                     if (ref($passwdconf{'crsownerchg'}{'for'}) eq 'ARRAY') {
 6410:                         foreach my $status (@userstatuses) {
 6411:                             if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'for'}})) {
 6412:                                 undef($noupdate);
 6413:                                 last;
 6414:                             }
 6415:                         }
 6416:                     }
 6417:                 }
 6418:                 if ($noupdate) {
 6419:                     return;
 6420:                 }
 6421:                 my %owned = &Apache::lonnet::courseiddump($cdom,'.',1,'.',
 6422:                                                           $env{'user.name'}.':'.$env{'user.domain'},
 6423:                                                           undef,undef,undef,'.');
 6424:                 my %roleshash = &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 6425:                                                               ['active','future']);
 6426:                 foreach my $key (keys(%roleshash)) {
 6427:                     my ($name,$domain,$role) = split(/:/,$key);
 6428:                     if ($role eq 'st') {
 6429:                         next if (($name eq $cnum) && ($domain eq $cdom));
 6430:                         if ($owned{$domain.'_'.$name}) {
 6431:                             if (ref($owned{$domain.'_'.$name}) eq 'HASH') {
 6432:                                 if ($owned{$domain.'_'.$name}{'nopasswdchg'}) {
 6433:                                     $noupdate = 1;
 6434:                                     last;
 6435:                                 }
 6436:                             }
 6437:                         } else {
 6438:                             $noupdate = 1;
 6439:                             last;
 6440:                         }
 6441:                     } else {
 6442:                         $noupdate = 1;
 6443:                         last;
 6444:                     }
 6445:                 }
 6446:                 unless ($noupdate) {
 6447:                     $canchange = 1;
 6448:                 }
 6449:             }
 6450:         }
 6451:     }
 6452:     return $canchange;
 6453: }
 6454: 
 6455: sub check_usertype {
 6456:     my ($dom,$uname,$rules,$curr_rules,$got_rules) = @_;
 6457:     my $usertype;
 6458:     if ((ref($got_rules) eq 'HASH') && (ref($curr_rules) eq 'HASH')) {
 6459:         if (!$got_rules->{$dom}) {
 6460:             my %domconfig = &Apache::lonnet::get_dom('configuration',
 6461:                                               ['usercreation'],$dom);
 6462:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6463:                 foreach my $item ('username','id') {
 6464:                     if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 6465:                         $curr_rules->{$dom}{$item} =
 6466:                                 $domconfig{'usercreation'}{$item.'_rule'};
 6467:                     }
 6468:                 }
 6469:             }
 6470:             $got_rules->{$dom} = 1;
 6471:         }
 6472:         if (ref($rules) eq 'HASH') {
 6473:             my @user_rules;
 6474:             if (ref($curr_rules->{$dom}{'username'}) eq 'ARRAY') {
 6475:                 foreach my $rule (keys(%{$rules})) {
 6476:                     if (grep(/^\Q$rule\E/,@{$curr_rules->{$dom}{'username'}})) {
 6477:                         push(@user_rules,$rule);
 6478:                     }
 6479:                 } 
 6480:             }
 6481:             if (@user_rules > 0) {
 6482:                 my %rule_check = &Apache::lonnet::inst_rulecheck($dom,$uname,undef,'username',\@user_rules);
 6483:                 if (keys(%rule_check) > 0) {
 6484:                     $usertype = 'unofficial';
 6485:                     foreach my $item (keys(%rule_check)) {
 6486:                         if ($rule_check{$item}) {
 6487:                             $usertype = 'official';
 6488:                             last;
 6489:                         }
 6490:                     }
 6491:                 }
 6492:             }
 6493:         }
 6494:     }
 6495:     return $usertype;
 6496: }
 6497: 
 6498: sub roles_by_context {
 6499:     my ($context,$custom,$crstype) = @_;
 6500:     my @allroles;
 6501:     if ($context eq 'course') {
 6502:         @allroles = ('st');
 6503:         if ($env{'request.role'} =~ m{^dc\./}) {
 6504:             push(@allroles,'ad');
 6505:         }
 6506:         push(@allroles,('ta','ep','in'));
 6507:         if ($crstype eq 'Community') {
 6508:             push(@allroles,'co');
 6509:         } else {
 6510:             push(@allroles,'cc');
 6511:         }
 6512:         if ($custom) {
 6513:             push(@allroles,'cr');
 6514:         }
 6515:     } elsif ($context eq 'author') {
 6516:         @allroles = ('ca','aa');
 6517:     } elsif ($context eq 'domain') {
 6518:         @allroles = ('li','ad','dg','dh','da','sc','au','dc');
 6519:     }
 6520:     return @allroles;
 6521: }
 6522: 
 6523: sub get_permission {
 6524:     my ($context,$crstype) = @_;
 6525:     my %permission;
 6526:     if ($context eq 'course') {
 6527:         my $custom = 1;
 6528:         my @allroles = &roles_by_context($context,$custom,$crstype);
 6529:         foreach my $role (@allroles) {
 6530:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
 6531:                 $permission{'cusr'} = 1;
 6532:                 last;
 6533:             }
 6534:         }
 6535:         if (&Apache::lonnet::allowed('ccr',$env{'request.course.id'})) {
 6536:             $permission{'custom'} = 1;
 6537:         }
 6538:         if (&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) {
 6539:             $permission{'view'} = 1;
 6540:         }
 6541:         if (!$permission{'view'}) {
 6542:             my $scope = $env{'request.course.id'}.'/'.$env{'request.course.sec'};
 6543:             $permission{'view'} =  &Apache::lonnet::allowed('vcl',$scope);
 6544:             if ($permission{'view'}) {
 6545:                 $permission{'view_section'} = $env{'request.course.sec'};
 6546:             }
 6547:         }
 6548:         if (!$permission{'cusr'}) {
 6549:             if ($env{'request.course.sec'} ne '') {
 6550:                 my $scope = $env{'request.course.id'}.'/'.$env{'request.course.sec'};
 6551:                 $permission{'cusr'} = (&Apache::lonnet::allowed('cst',$scope));
 6552:                 if ($permission{'cusr'}) {
 6553:                     $permission{'cusr_section'} = $env{'request.course.sec'};
 6554:                 }
 6555:             }
 6556:         }
 6557:         if (&Apache::lonnet::allowed('mdg',$env{'request.course.id'})) {
 6558:             $permission{'grp_manage'} = 1;
 6559:         }
 6560:         if ($permission{'cusr'}) {
 6561:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6562:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6563:             my %coursehash = (
 6564:                 'internal.selfenrollmgrdc' => $env{'course.'.$env{'request.course.id'}.'.internal.selfenrollmgrdc'},
 6565:                 'internal.selfenrollmgrcc' => $env{'course.'.$env{'request.course.id'}.'.internal.selfenrollmgrcc'},
 6566:                 'internal.coursecode'      => $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'},
 6567:                 'internal.textbook'        =>$env{'course.'.$env{'request.course.id'}.'.internal.textbook'},
 6568:             );
 6569:             my ($managed_by_cc,$managed_by_dc) = &selfenrollment_administration($cdom,$cnum,$crstype,\%coursehash);
 6570:             if (ref($managed_by_cc) eq 'ARRAY') {
 6571:                 if (@{$managed_by_cc}) {
 6572:                     $permission{'selfenrolladmin'} = 1;
 6573:                 }
 6574:             }
 6575:         }
 6576:         if ($env{'request.course.id'}) {
 6577:             my $user;
 6578:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 6579:                 $user = $env{'user.name'}.':'.$env{'user.domain'};
 6580:             }
 6581:             if (($user ne '') && ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq
 6582:                                   $user)) {
 6583:                 $permission{'owner'} = 1;
 6584:                 if (&Apache::lonnet::allowed('mip',$env{'request.course.id'})) {
 6585:                     $permission{'mip'} = 1;
 6586:                 }
 6587:             } elsif (($user ne '') && ($env{'course.'.$env{'request.course.id'}.'.internal.co-owners'} ne '')) {
 6588:                 if (grep(/^\Q$user\E$/,split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.co-owners'}))) {
 6589:                     $permission{'co-owner'} = 1;
 6590:                 }
 6591:             }
 6592:         }
 6593:     } elsif ($context eq 'author') {
 6594:         $permission{'cusr'} = &authorpriv($env{'user.name'},$env{'request.role.domain'});
 6595:         $permission{'view'} = $permission{'cusr'};
 6596:     } else {
 6597:         my @allroles = &roles_by_context($context);
 6598:         foreach my $role (@allroles) {
 6599:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
 6600:                 $permission{'cusr'} = 1;
 6601:                 last;
 6602:             }
 6603:         }
 6604:         if (!$permission{'cusr'}) {
 6605:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 6606:                 $permission{'cusr'} = 1;
 6607:             }
 6608:         }
 6609:         if (&Apache::lonnet::allowed('ccr',$env{'request.role.domain'})) {
 6610:             $permission{'custom'} = 1;
 6611:         }
 6612:         if (&Apache::lonnet::allowed('vac',$env{'request.role.domain'})) {
 6613:             $permission{'activity'} = 1;
 6614:         }
 6615:         if (&Apache::lonnet::allowed('vur',$env{'request.role.domain'})) {
 6616:             $permission{'view'} = 1;
 6617:         }
 6618:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 6619:             $permission{'owner'} = 1;
 6620:         }
 6621:     }
 6622:     my $allowed = 0;
 6623:     foreach my $key (keys(%permission)) {
 6624:         next if (($key eq 'owner') || ($key eq 'co-owner'));
 6625:         if ($permission{$key}) { $allowed=1; last; }
 6626:     }
 6627:     return (\%permission,$allowed);
 6628: }
 6629: 
 6630: # ==================================================== Figure out author access
 6631: 
 6632: sub authorpriv {
 6633:     my ($auname,$audom)=@_;
 6634:     unless ((&Apache::lonnet::allowed('cca',$audom.'/'.$auname))
 6635:          || (&Apache::lonnet::allowed('caa',$audom.'/'.$auname))) { return ''; }    return 1;
 6636: }
 6637: 
 6638: sub roles_on_upload {
 6639:     my ($context,$setting,$crstype,%customroles) = @_;
 6640:     my (@possible_roles,@permitted_roles);
 6641:     @possible_roles = &curr_role_permissions($context,$setting,1,$crstype);
 6642:     foreach my $role (@possible_roles) {
 6643:         if ($role eq 'cr') {
 6644:             push(@permitted_roles,keys(%customroles));
 6645:         } else {
 6646:             push(@permitted_roles,$role);
 6647:         }
 6648:     }
 6649:     return @permitted_roles;
 6650: }
 6651: 
 6652: sub get_course_identity {
 6653:     my ($cid) = @_;
 6654:     my ($cnum,$cdom,$cdesc);
 6655:     if ($cid eq '') {
 6656:         $cid = $env{'request.course.id'}
 6657:     }
 6658:     if ($cid ne '') {
 6659:         $cnum = $env{'course.'.$cid.'.num'};
 6660:         $cdom = $env{'course.'.$cid.'.domain'};
 6661:         $cdesc = $env{'course.'.$cid.'.description'};
 6662:         if ($cnum eq '' || $cdom eq '') {
 6663:             my %coursehash =
 6664:                 &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 6665:             $cdom = $coursehash{'domain'};
 6666:             $cnum = $coursehash{'num'};
 6667:             $cdesc = $coursehash{'description'};
 6668:         }
 6669:     }
 6670:     return ($cnum,$cdom,$cdesc);
 6671: }
 6672: 
 6673: sub dc_setcourse_js {
 6674:     my ($formname,$mode,$context,$showcredits,$domain) = @_;
 6675:     my ($dc_setcourse_code,$authen_check);
 6676:     my $cctext = &Apache::lonnet::plaintext('cc');
 6677:     my $cotext = &Apache::lonnet::plaintext('co');
 6678:     my %alerts = &sectioncheck_alerts();
 6679:     my $role = 'role';
 6680:     if ($mode eq 'upload') {
 6681:         $role = 'courserole';
 6682:     } else {
 6683:         $authen_check = &verify_authen($formname,$context,$domain);
 6684:     }
 6685:     $dc_setcourse_code = (<<"SCRIPTTOP");
 6686: $authen_check
 6687: 
 6688: function setCourse() {
 6689:     var course = document.$formname.dccourse.value;
 6690:     if (course != "") {
 6691:         if (document.$formname.dcdomain.value != document.$formname.origdom.value) {
 6692:             alert("$alerts{'curd'}");
 6693:             return;
 6694:         }
 6695:         var userrole = document.$formname.$role.options[document.$formname.$role.selectedIndex].value
 6696:         var section="";
 6697:         var numsections = 0;
 6698:         var newsecs = new Array();
 6699:         for (var i=0; i<document.$formname.currsec.length; i++) {
 6700:             if (document.$formname.currsec.options[i].selected == true ) {
 6701:                 if (document.$formname.currsec.options[i].value != "" && document.$formname.currsec.options[i].value != null) {
 6702:                     if (numsections == 0) {
 6703:                         section = document.$formname.currsec.options[i].value
 6704:                         numsections = 1;
 6705:                     }
 6706:                     else {
 6707:                         section = section + "," +  document.$formname.currsec.options[i].value
 6708:                         numsections ++;
 6709:                     }
 6710:                 }
 6711:             }
 6712:         }
 6713:         if (document.$formname.newsec.value != "" && document.$formname.newsec.value != null) {
 6714:             if (numsections == 0) {
 6715:                 section = document.$formname.newsec.value
 6716:             }
 6717:             else {
 6718:                 section = section + "," +  document.$formname.newsec.value
 6719:             }
 6720:             newsecs = document.$formname.newsec.value.split(/,/g);
 6721:             numsections = numsections + newsecs.length;
 6722:         }
 6723:         if ((userrole == 'st') && (numsections > 1)) {
 6724:             if (document.$formname.crstype.value == 'Community') {
 6725:                 alert("$alerts{'inco'}. $alerts{'youh'} "+numsections+" $alerts{'sect'}.\\n$alerts{'plsm'}.")
 6726:             } else {
 6727:                 alert("$alerts{'inea'}. $alerts{'youh'} "+numsections+" $alerts{'sect'}.\\n$alerts{'plsm'}.")
 6728:             }
 6729:             return;
 6730:         }
 6731:         for (var j=0; j<newsecs.length; j++) {
 6732:             if ((newsecs[j] == 'all') || (newsecs[j] == 'none')) {
 6733:                 alert("'"+newsecs[j]+"' $alerts{'mayn'}.\\n$alerts{'plsc'}.");
 6734:                 return;
 6735:             }
 6736:             if (document.$formname.groups.value != '') {
 6737:                 var groups = document.$formname.groups.value.split(/,/g);
 6738:                 for (var k=0; k<groups.length; k++) {
 6739:                     if (newsecs[j] == groups[k]) {
 6740:                         if (document.$formname.crstype.value == 'Community') {
 6741:                             alert("'"+newsecs[j]+"' $alerts{'mayc'}.\\n$alerts{'secn'}. $alerts{'plsc'}.");
 6742:                         } else {
 6743:                             alert("'"+newsecs[j]+"' $alerts{'mayt'}.\\n$alerts{'secn'}. $alerts{'plsc'}.");
 6744:                         }
 6745:                         return;
 6746:                     }
 6747:                 }
 6748:             }
 6749:         }
 6750:         if ((userrole == 'cc') && (numsections > 0)) {
 6751:             alert("$alerts{'secd'} $cctext $alerts{'role'}.\\n$alerts{'accr'}.");
 6752:             section = "";
 6753:         }
 6754:         if ((userrole == 'co') && (numsections > 0)) {
 6755:             alert("$alerts{'secd'} $cotext $alerts{'role'}.\\n$alerts{'accr'}.");
 6756:             section = "";
 6757:         }
 6758: SCRIPTTOP
 6759:     if ($mode ne 'upload') {
 6760:         $dc_setcourse_code .= (<<"SCRIPTMID");
 6761:         var coursename = "_$env{'request.role.domain'}"+"_"+course+"_"+userrole
 6762:         var numcourse = getIndex(document.$formname.dccourse);
 6763:         if (numcourse == "-1") {
 6764:             if (document.$formname.type == 'Community') {
 6765:                 alert("$alerts{'thwc'}");
 6766:             } else {
 6767:                 alert("$alerts{'thwa'}");
 6768:             }
 6769:             return;
 6770:         }
 6771:         else {
 6772:             document.$formname.elements[numcourse].name = "act"+coursename;
 6773:             var numnewsec = getIndex(document.$formname.newsec);
 6774:             if (numnewsec != "-1") {
 6775:                 document.$formname.elements[numnewsec].name = "sec"+coursename;
 6776:                 document.$formname.elements[numnewsec].value = section;
 6777:             }
 6778:             var numstart = getIndex(document.$formname.start);
 6779:             if (numstart != "-1") {
 6780:                 document.$formname.elements[numstart].name = "start"+coursename;
 6781:             }
 6782:             var numend = getIndex(document.$formname.end);
 6783:             if (numend != "-1") {
 6784:                 document.$formname.elements[numend].name = "end"+coursename
 6785:             }
 6786: SCRIPTMID
 6787:         if ($showcredits) {
 6788:             $dc_setcourse_code .= <<ENDCRED;
 6789:             var numcredits = getIndex(document.$formname.credits);
 6790:             if (numcredits != "-1") {
 6791:                 document.$formname.elements[numcredits].name = "credits"+coursename;
 6792:             }
 6793: ENDCRED
 6794:         }
 6795:         $dc_setcourse_code .= <<ENDSCRIPT; 
 6796:         }
 6797:     }
 6798:     var authcheck = auth_check();
 6799:     if (authcheck == 'ok') {
 6800:         document.$formname.submit();
 6801:     }
 6802: }
 6803: ENDSCRIPT
 6804:     } else {
 6805:         $dc_setcourse_code .=  "
 6806:         document.$formname.sections.value = section;
 6807:     }
 6808:     return 'ok';
 6809: }
 6810: ";
 6811:     }
 6812:     $dc_setcourse_code .= (<<"ENDSCRIPT");
 6813: 
 6814:     function getIndex(caller) {
 6815:         for (var i=0;i<document.$formname.elements.length;i++) {
 6816:             if (document.$formname.elements[i] == caller) {
 6817:                 return i;
 6818:             }
 6819:         }
 6820:         return -1;
 6821:     }
 6822: ENDSCRIPT
 6823:     return $dc_setcourse_code;
 6824: }
 6825: 
 6826: sub verify_authen {
 6827:     my ($formname,$context,$domain) = @_;
 6828:     my %alerts = &authcheck_alerts();
 6829:     my $finish = "return 'ok';";
 6830:     if ($context eq 'author') {
 6831:         $finish = "document.$formname.submit();";
 6832:     }
 6833:     my ($numrules,$intargjs) =
 6834:         &Apache::loncommon::passwd_validation_js('argpicked',$domain);
 6835:     my $outcome = <<"ENDSCRIPT";
 6836: 
 6837: function auth_check() {
 6838:     var logintype;
 6839:     if (document.$formname.login.length) {
 6840:         if (document.$formname.login.length > 0) {
 6841:             var loginpicked = 0;
 6842:             for (var i=0; i<document.$formname.login.length; i++) {
 6843:                 if (document.$formname.login[i].checked == true) {
 6844:                     loginpicked = 1;
 6845:                     logintype = document.$formname.login[i].value;
 6846:                 }
 6847:             }
 6848:             if (loginpicked == 0) {
 6849:                 alert("$alerts{'authen'}");
 6850:                 return;
 6851:             }
 6852:         }
 6853:     } else {
 6854:         logintype = document.$formname.login.value;
 6855:     }
 6856:     if (logintype == 'nochange') {
 6857:         return 'ok';
 6858:     }
 6859:     var argpicked = document.$formname.elements[logintype+'arg'].value;
 6860:     if ((argpicked == null) || (argpicked == '') || (typeof argpicked == 'undefined')) {
 6861:         var alertmsg = '';
 6862:         switch (logintype) {
 6863:             case 'krb':
 6864:                 alertmsg = '$alerts{'krb'}';
 6865:                 break;
 6866:             case 'int':
 6867:                 alertmsg = '$alerts{'ipass'}';
 6868:                 break;
 6869:             case 'fsys':
 6870:                 alertmsg = '$alerts{'ipass'}';
 6871:                 break;
 6872:             case 'loc':
 6873:                 alertmsg = '';
 6874:                 break;
 6875:             default:
 6876:                 alertmsg = '';
 6877:         }
 6878:         if (alertmsg != '') {
 6879:             alert(alertmsg);
 6880:             return;
 6881:         }
 6882:     } else if (logintype == 'int') {
 6883:         var numrules = $numrules;
 6884:         if (numrules > 0) {
 6885: $intargjs
 6886:         }
 6887:     }
 6888:     $finish
 6889: }
 6890: ENDSCRIPT
 6891: }
 6892: 
 6893: sub sectioncheck_alerts {
 6894:     my %alerts = &Apache::lonlocal::texthash(
 6895:                     curd => 'You must select a course or community in the current domain',
 6896:                     inea => 'In each course, each user may only have one student role at a time',
 6897:                     inco => 'In each community, each user may only have one member role at a time', 
 6898:                     youh => 'You had selected',
 6899:                     sect => 'sections',
 6900:                     plsm => 'Please modify your selections so they include no more than one section',
 6901:                     mayn => 'may not be used as the name for a section, as it is a reserved word',
 6902:                     plsc => 'Please choose a different section name',
 6903:                     mayt => 'may not be used as the name for a section, as it is the name of a course group',
 6904:                     mayc => 'may not be used as the name for a section, as it is the name of a community group',
 6905:                     secn => 'Section names and group names must be distinct',
 6906:                     secd => 'Section designations do not apply to ',
 6907:                     role => 'roles',
 6908:                     accr => 'role will be added with access to all sections',
 6909:                     thwa => 'There was a problem with your course selection',
 6910:                     thwc => 'There was a problem with your community selection',
 6911:                  );
 6912:     &js_escape(\%alerts);
 6913:     return %alerts;
 6914: }
 6915: 
 6916: sub authcheck_alerts {
 6917:     my %alerts = 
 6918:         &Apache::lonlocal::texthash(
 6919:                     authen => 'You must choose an authentication type.',
 6920:                     krb    => 'You need to specify the Kerberos domain.',
 6921:                     ipass  => 'You need to specify the initial password.',
 6922:         );
 6923:     &js_escape(\%alerts);
 6924:     return %alerts;
 6925: }
 6926: 
 6927: sub is_courseowner {
 6928:     my ($thiscourse,$courseowner) = @_;
 6929:     if ($courseowner eq '') {
 6930:         if ($env{'request.course.id'} eq $thiscourse) {
 6931:             $courseowner = $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 6932:         }
 6933:     }
 6934:     if ($courseowner ne '') {
 6935:         if ($courseowner eq $env{'user.name'}.':'.$env{'user.domain'}) {
 6936:             return 1;
 6937:         }
 6938:     }
 6939:     return;
 6940: }
 6941: 
 6942: sub get_selfenroll_titles {
 6943:     my @row = ('types','registered','enroll_dates','access_dates','section',
 6944:                'approval','limit');
 6945:     my %lt = &Apache::lonlocal::texthash (
 6946:                 types        => 'Users allowed to self-enroll',
 6947:                 registered   => 'Registration status (official courses)' ,
 6948:                 enroll_dates => 'Dates self-enrollment available',
 6949:                 access_dates => 'Access dates for self-enrolling users',
 6950:                 section      => "Self-enrolling users' section",
 6951:                 approval     => 'Processing of requests',
 6952:                 limit        => 'Enrollment limit',
 6953:              );
 6954:     return (\@row,\%lt);
 6955: }
 6956: 
 6957: sub selfenroll_default_descs {
 6958:     my %desc = (
 6959:                  types => {
 6960:                             dom => &mt('Course domain'),
 6961:                             all => &mt('Any domain'),
 6962:                             ''  => &mt('None'),
 6963:                           },
 6964:                  limit => {
 6965:                             none         => &mt('No limit'),
 6966:                             allstudents  => &mt('Limit by total students'),
 6967:                             selfenrolled => &mt('Limit by total self-enrolled'),
 6968:                           },
 6969:                  approval => {
 6970:                                 '0' => &mt('Processed automatically'),
 6971:                                 '1' => &mt('Queued for approval'),
 6972:                                 '2' => &mt('Queued, pending validation'),
 6973:                              },
 6974:                  registered => {
 6975:                                  0 => 'No registration required',
 6976:                                  1 => 'Registered students only',
 6977:                                },
 6978:                );
 6979:     return %desc;
 6980: }
 6981: 
 6982: sub selfenroll_validation_types {
 6983:     my @items = ('url','fields','button','markup');
 6984:     my %names =  &Apache::lonlocal::texthash (
 6985:             url      => 'Web address of validation server/script',
 6986:             fields   => 'Form fields to send to validator',
 6987:             button   => 'Text for validation button',
 6988:             markup   => 'Validation description (HTML)',
 6989:     );
 6990:     my @fields = ('username','domain','uniquecode','course','coursetype','description');
 6991:     return (\@items,\%names,\@fields);
 6992: }
 6993: 
 6994: sub get_extended_type {
 6995:     my ($cdom,$cnum,$crstype,$current) = @_;
 6996:     my $type = 'unofficial';
 6997:     my %settings;
 6998:     if (ref($current) eq 'HASH') {
 6999:         %settings = %{$current};
 7000:     } else {
 7001:         %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook'],$cdom,$cnum);
 7002:     }
 7003:     if ($crstype eq 'Community') {
 7004:         $type = 'community';
 7005:     } elsif ($crstype eq 'Placement') {
 7006:         $type = 'placement';
 7007:     } elsif ($settings{'internal.coursecode'}) {
 7008:         $type = 'official';
 7009:     } elsif ($settings{'internal.textbook'}) {
 7010:         $type = 'textbook';
 7011:     }
 7012:     return $type;
 7013: }
 7014: 
 7015: sub selfenrollment_administration {
 7016:     my ($cdom,$cnum,$crstype,$coursehash) = @_;
 7017:     my %settings;
 7018:     if (ref($coursehash) eq 'HASH') {
 7019:         %settings = %{$coursehash};
 7020:     } else {
 7021:         %settings = &Apache::lonnet::get('environment',
 7022:                         ['internal.selfenrollmgrdc','internal.selfenrollmgrcc',
 7023:                          'internal.coursecode','internal.textbook'],$cdom,$cnum);
 7024:     }
 7025:     my ($possconfigs) = &get_selfenroll_titles(); 
 7026:     my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 7027:     my $selfenrolltype = &get_extended_type($cdom,$cnum,$crstype,\%settings);
 7028: 
 7029:     my (@in_course,@in_domain); 
 7030:     if ($settings{'internal.selfenrollmgrcc'} ne '') {
 7031:         @in_course = split(/,/,$settings{'internal.selfenrollmgrcc'}); 
 7032:         my @diffs = &Apache::loncommon::compare_arrays($possconfigs,\@in_course);
 7033:         unless (@diffs) {
 7034:             return (\@in_course,\@in_domain);
 7035:         }
 7036:     }
 7037:     if ($settings{'internal.selfenrollmgrdc'} ne '') {
 7038:         my @in_domain = split(/,/,$settings{'internal.selfenrollmgrdc'});
 7039:         my @diffs = &Apache::loncommon::compare_arrays(\@in_domain,$possconfigs);
 7040:         unless (@diffs) {
 7041:             return (\@in_course,\@in_domain);
 7042:         }
 7043:     }
 7044:     my @combined = @in_course;
 7045:     push(@combined,@in_domain);
 7046:     my @diffs = &Apache::loncommon::compare_arrays(\@combined,$possconfigs); 
 7047:     unless (@diffs) {
 7048:         return (\@in_course,\@in_domain);
 7049:     }
 7050:     if ($domdefaults{$selfenrolltype.'selfenrolladmdc'} eq '') {
 7051:         push(@in_course,@diffs);
 7052:     } else {
 7053:         my @defaultdc = split(/,/,$domdefaults{$selfenrolltype.'selfenrolladmdc'});
 7054:         foreach my $item (@diffs) {
 7055:             if (grep(/^\Q$item\E$/,@defaultdc)) {
 7056:                 push(@in_domain,$item);
 7057:             } else {
 7058:                 push(@in_course,$item);
 7059:             }
 7060:         }
 7061:     }
 7062:     return (\@in_course,\@in_domain);
 7063: }
 7064: 
 7065: sub custom_role_header {
 7066:     my ($context,$crstype,$templaterolerefs,$prefix) = @_;
 7067:     my %lt = &Apache::lonlocal::texthash(
 7068:                  sele => 'Select a Template',
 7069:     );
 7070:     my ($context_code,$button_code);
 7071:     if ($context eq 'domain') {
 7072:         $context_code = &custom_coursetype_switch($crstype,$prefix);
 7073:     }
 7074:     if (ref($templaterolerefs) eq 'ARRAY') {
 7075:         foreach my $role (@{$templaterolerefs}) {
 7076:             my $display = 'inline';
 7077:             if (($context eq 'domain') && ($role eq 'co')) {
 7078:                 $display = 'none';
 7079:             }
 7080:             $button_code .= &make_button_code($role,$crstype,$display,$prefix).' ';
 7081:         }
 7082:     }
 7083:     return <<"END";
 7084: <div class="LC_left_float">
 7085: <fieldset>
 7086: <legend>$lt{'sele'}</legend>
 7087: $button_code
 7088: </fieldset></div>
 7089: $context_code
 7090: <br clear="all" />
 7091: END
 7092: }
 7093: 
 7094: sub custom_coursetype_switch {
 7095:     my ($crstype,$prefix) = @_;
 7096:     my ($checkedcourse,$checkedcommunity);
 7097:     if ($crstype eq 'Community') {
 7098:         $checkedcommunity = ' checked="checked"';
 7099:     } else {
 7100:         $checkedcourse = ' checked="checked"';
 7101:     }
 7102:     my %lt = &Apache::lonlocal::texthash(
 7103:         cont => 'Context',
 7104:         cour => 'Course',
 7105:         comm => 'Community',
 7106:     );
 7107:     return <<"END";
 7108: <div class="LC_left_float">
 7109: <fieldset>
 7110: <legend>$lt{'cont'}</legend>
 7111: <label>
 7112: <input type="radio" name="${prefix}_custrolecrstype" value="Course"$checkedcourse onclick="javascript:customSwitchType('$prefix');" />
 7113: $lt{'cour'}
 7114: </label>&nbsp;&nbsp;
 7115: <label>
 7116: <input type="radio" name="${prefix}_custrolecrstype" value="Community"$checkedcommunity onclick="javascript:customSwitchType('$prefix');" />
 7117: $lt{'comm'}
 7118: </label>
 7119: </fieldset>
 7120: </div>
 7121: END
 7122: }
 7123: 
 7124: sub custom_role_table {
 7125:     my ($crstype,$full,$levels,$levelscurrent,$prefix,$add_class,$id) = @_;
 7126:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 7127:                    (ref($levelscurrent) eq 'HASH'));
 7128:     my %lt=&Apache::lonlocal::texthash (
 7129:                     'prv'  => "Privilege",
 7130:                     'crl'  => "Course Level",
 7131:                     'dml'  => "Domain Level",
 7132:                     'ssl'  => "System Level");
 7133:     my %cr = (
 7134:                course => '_c',
 7135:                domain => '_d',
 7136:                system => '_s',
 7137:              );
 7138: 
 7139:     my $output=&Apache::loncommon::start_data_table($add_class,$id).
 7140:                &Apache::loncommon::start_data_table_header_row().
 7141:                '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
 7142:                '</th><th>'.$lt{'ssl'}.'</th>'.
 7143:                &Apache::loncommon::end_data_table_header_row();
 7144:     foreach my $priv (sort(keys(%{$full}))) {
 7145:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 7146:         $output .= &Apache::loncommon::start_data_table_row().
 7147:                   '<td><span id="'.$prefix.$priv.'">'.$privtext.'</span></td>';
 7148:         foreach my $type ('course','domain','system') {
 7149:             if (($type eq 'system') && ($priv eq 'bre') && ($crstype eq 'Community')) {
 7150:                 $output .= '<td>&nbsp;</td>';
 7151:             } else {
 7152:                 $output .= '<td>'.
 7153:                   ($levels->{$type}{$priv}?'<input type="checkbox" id="'.$prefix.$priv.$cr{$type}.'"'.
 7154:                   ' name="'.$prefix.$priv.$cr{$type}.'"'.
 7155:                   ($levelscurrent->{$type}{$priv}?' checked="checked"':'').' />':'&nbsp;').
 7156:                   '</td>';
 7157:             }
 7158:         }
 7159:         $output .= &Apache::loncommon::end_data_table_row();
 7160:     }
 7161:     $output .= &Apache::loncommon::end_data_table();
 7162:     return $output;
 7163: }
 7164: 
 7165: sub custom_role_privs {
 7166:     my ($privs,$full,$levels,$levelscurrent)= @_;
 7167:     return unless ((ref($privs) eq 'HASH') && (ref($full) eq 'HASH') &&
 7168:                    (ref($levels) eq 'HASH') && (ref($levelscurrent) eq 'HASH'));
 7169:     my %cr = (
 7170:                course => 'cr:c',
 7171:                domain => 'cr:d',
 7172:                system => 'cr:s',
 7173:              );
 7174:     foreach my $type ('course','domain','system') {
 7175:         foreach my $item (split(/\:/,$Apache::lonnet::pr{$cr{$type}})) {
 7176:             my ($priv,$restrict)=split(/\&/,$item);
 7177:             if (!$restrict) { $restrict='F'; }
 7178:             $levels->{$type}->{$priv}=$restrict;
 7179:             if ($privs->{$type}=~/\:$priv/) {
 7180:                 $levelscurrent->{$type}->{$priv}=1;
 7181:             }
 7182:             $full->{$priv}=1;
 7183:         }
 7184:     }
 7185:     return;
 7186: }
 7187: 
 7188: sub custom_template_roles {
 7189:     my ($context,$crstype) = @_;
 7190:     my @template_roles = ("in","ta","ep");
 7191:     if (($context eq 'domain') || ($context eq 'domprefs')) {
 7192:         push(@template_roles,"ad");
 7193:     }
 7194:     push(@template_roles,"st");
 7195:     if ($context eq 'domain') {
 7196:         unshift(@template_roles,('co','cc'));
 7197:     } else {
 7198:         if ($crstype eq 'Community') {
 7199:             unshift(@template_roles,'co');
 7200:         } else {
 7201:             unshift(@template_roles,'cc');
 7202:         }
 7203:     }
 7204:     return @template_roles;
 7205: }
 7206: 
 7207: sub custom_roledefs_js {
 7208:     my ($context,$crstype,$formname,$full,$templaterolesref,$jsback) = @_;
 7209:     my $button_code = "\n";
 7210:     my $head_script = "\n";
 7211:     my (%roletitlestr,$rolenamestr);
 7212:     my %role_titles = (
 7213:                         Course    => [],
 7214:                         Community => [],
 7215:                       );
 7216:     $head_script .= '<script type="text/javascript">'."\n"
 7217:                    .'// <![CDATA['."\n";
 7218:     if (ref($templaterolesref) eq 'ARRAY') {
 7219:         if ($context eq 'domain') {
 7220:             $rolenamestr = join("','",@{$templaterolesref});
 7221:         }
 7222:         foreach my $role (@{$templaterolesref}) {
 7223:             $head_script .= &make_script_template($role,$crstype,$formname);
 7224:             if ($context eq 'domain') {
 7225:                 foreach my $type ('Course','Community') {
 7226:                     push(@{$role_titles{$type}},&Apache::lonnet::plaintext($role,$type));
 7227:                 }
 7228:             }
 7229:         }
 7230:     }
 7231:     if ($context eq 'domain') {
 7232:         foreach my $type ('Course','Community') {
 7233:             $roletitlestr{$type} = join("','",@{$role_titles{$type}});
 7234:         }
 7235:         my %pt = (
 7236:             Community => {
 7237:                            cst => &mt('Grant/revoke role of Member'),
 7238:                            mdc => &mt('Edit community contents'),
 7239:                            pch => &mt('Post discussion on community resources'),
 7240:                            pfo => &mt('Print for other users and entire community'),
 7241:                          },
 7242:             Course    => {
 7243:                            cst => &mt('Grant/revoke role of Student'),
 7244:                            mdc => &mt('Edit course contents'),
 7245:                            pch => &mt('Post discussion on course resources'),
 7246:                            pfo => &mt('Print for other users and entire course'),
 7247:                          },
 7248:         );
 7249:         $head_script .= <<"ENDJS";
 7250: function customSwitchType(prefix) {
 7251:     var privnames = new Array('cst','mdc','pch','pfo');
 7252:     var privtxtcrs = new Array('$pt{Course}{cst}','$pt{Course}{mdc}','$pt{Course}{pch}','$pt{Course}{pfo}');
 7253:     var privtxtcom = new Array('$pt{Community}{cst}','$pt{Community}{mdc}','$pt{Community}{pch}','$pt{Community}{pfo}');
 7254:     var rolenames = new Array('$rolenamestr');
 7255:     var rolescrs = new Array('$roletitlestr{Course}');
 7256:     var rolescom = new Array('$roletitlestr{Community}');
 7257:     var radio = prefix+'_custrolecrstype';
 7258:     if (document.$formname.elements[radio].length > 1) {
 7259:         for (var i=0; i<document.$formname.elements[radio].length; i++) {
 7260:             if (document.$formname.elements[radio][i].checked) {
 7261:                 if ((document.getElementById(prefix+'bre_s')) && (document.getElementById(prefix+'bro_s'))) {
 7262:                     if (document.$formname.elements[radio][i].value == 'Community') {
 7263:                         if (document.getElementById(prefix+'bre_s').checked) {
 7264:                             document.getElementById(prefix+'bro_s').checked = true;
 7265:                             document.getElementById(prefix+'bre_s').checked = false;
 7266: 
 7267:                         }
 7268:                         document.getElementById(prefix+'bre_s').style.visibility = 'hidden';
 7269:                     } else {
 7270:                         document.getElementById(prefix+'bre_s').style.visibility = 'visible';
 7271:                         if (document.getElementById(prefix+'bro_s').checked) {
 7272:                             document.getElementById(prefix+'bre_s').checked = true;
 7273:                             document.getElementById(prefix+'bro_s').checked = false;
 7274:                         }
 7275:                     }
 7276:                 }
 7277:                 for (var j=0; j<privnames.length; j++) {
 7278:                     if (document.getElementById(prefix+privnames[j])) {
 7279:                         if (document.getElementById(prefix+privnames[j])) {
 7280:                             if (document.$formname.elements[radio][i].value == 'Course') {
 7281:                                 document.getElementById(prefix+privnames[j]).innerHTML = privtxtcrs[j];
 7282:                             } else {
 7283:                                 document.getElementById(prefix+privnames[j]).innerHTML = privtxtcom[j];
 7284:                             }
 7285:                         }
 7286:                     }
 7287:                 }
 7288:                 for (var j=0; j<rolenames.length; j++) {
 7289:                     if (document.getElementById(prefix+rolenames[j])) {
 7290:                         if (document.getElementById(prefix+rolenames[j])) {
 7291:                             if (document.$formname.elements[radio][i].value == 'Course') {
 7292:                                 document.getElementById(prefix+rolenames[j]).value = rolescrs[j];
 7293:                                 if (rolenames[j] == 'cc') {
 7294:                                     document.getElementById(prefix+rolenames[j]).style.display = 'inline';
 7295:                                 }
 7296:                                 if (rolenames[j] == 'co') {
 7297:                                     document.getElementById(prefix+rolenames[j]).style.display = 'none';
 7298:                                 }
 7299:                             } else {
 7300:                                 document.getElementById(prefix+rolenames[j]).value = rolescom[j];
 7301:                                 if (rolenames[j] == 'cc') {
 7302:                                     document.getElementById(prefix+rolenames[j]).style.display = 'none';
 7303:                                 }
 7304:                                 if (rolenames[j] == 'co') {
 7305:                                     document.getElementById(prefix+rolenames[j]).style.display = 'inline';
 7306:                                 }
 7307:                             }
 7308:                         }
 7309:                     }
 7310:                 }
 7311:             }
 7312:         }
 7313:     }
 7314:     return;
 7315: }
 7316: ENDJS
 7317:     }
 7318:     $head_script .= "\n".$jsback."\n"
 7319:                    .'// ]]>'."\n"
 7320:                    .'</script>'."\n";
 7321:     return $head_script;
 7322: }
 7323: 
 7324: # --------------------------------------------------------
 7325: sub make_script_template {
 7326:     my ($role,$crstype,$formname) = @_;
 7327:     my $return_script = 'function set_'.$role.'(prefix) {'."\n";
 7328:     my (%full_by_level,%role_priv);
 7329:     foreach my $level ('c','d','s') {
 7330:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:'.$level})) {
 7331:             next if (($level eq 's') && ($crstype eq 'Community') && ($item eq 'bre&S'));
 7332:             my ($priv,$restrict)=split(/\&/,$item);
 7333:             $full_by_level{$level}{$priv}=1;
 7334:         }
 7335:         $role_priv{$level} = {};
 7336:         my @temp = split(/:/,$Apache::lonnet::pr{$role.':'.$level});
 7337:         foreach my $priv (@temp) {
 7338:             my ($priv_item, $dummy) = split(/\&/,$priv);
 7339:             $role_priv{$level}{$priv_item} = 1;
 7340:         }
 7341:     }
 7342:     my %to_check = (
 7343:                       c => ['c','d','s'],
 7344:                       d => ['d','s'],
 7345:                       s => ['s'],
 7346:                    );
 7347:     foreach my $level ('c','d','s') {
 7348:         if (ref($full_by_level{$level}) eq 'HASH') {
 7349:             foreach my $priv (keys(%{$full_by_level{$level}})) {
 7350:                 my $value = 'false';
 7351:                 if (ref($to_check{$level}) eq 'ARRAY') {
 7352:                     foreach my $lett (@{$to_check{$level}}) {
 7353:                         if (exists($role_priv{$lett}{$priv})) {
 7354:                             $value = 'true';
 7355:                             last;
 7356:                         }
 7357:                     }
 7358:                     $return_script .= "document.$formname.elements[prefix+'".$priv."_".$level."'].checked = $value;\n";
 7359:                 }
 7360:             }
 7361:         }
 7362:     }
 7363:     $return_script .= '}'."\n";
 7364:     return ($return_script);
 7365: }
 7366: # ----------------------------------------------------------
 7367: sub make_button_code {
 7368:     my ($role,$crstype,$display,$prefix) = @_;
 7369:     my $label = &Apache::lonnet::plaintext($role,$crstype);
 7370:     my $button_code = '<input type="button" onclick="set_'.$role."('$prefix'".')" '.
 7371:                       'id="'.$prefix.$role.'" value="'.$label.'" '.
 7372:                       'style="display:'.$display.'" />';
 7373:     return ($button_code);
 7374: }
 7375: 
 7376: sub custom_role_update {
 7377:     my ($rolename,$prefix) = @_;
 7378: # ------------------------------------------------------- What can be assigned?
 7379:     my %privs = (
 7380:                       c => '',
 7381:                       d => '',
 7382:                       s => '',
 7383:                     );
 7384:     foreach my $level (keys(%privs)) {
 7385:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:'.$level})) {
 7386:             my ($priv,$restrict)=split(/\&/,$item);
 7387:             if (!$restrict) { $restrict=''; }
 7388:             if ($env{'form.'.$prefix.$priv.'_'.$level}) {
 7389:                 $privs{$level} .=':'.$item;
 7390:             }
 7391:         }
 7392:     }
 7393:     return %privs;
 7394: }
 7395: 
 7396: sub adhoc_status_types {
 7397:     my ($cdom,$context,$role,$selectedref,$othertitle,$usertypes,$types,$disabled) = @_;
 7398:     my $output = &Apache::loncommon::start_data_table();
 7399:     my $numinrow = 3;
 7400:     my $rem;
 7401:     if (ref($types) eq 'ARRAY') {
 7402:         for (my $i=0; $i<@{$types}; $i++) {
 7403:             if (defined($usertypes->{$types->[$i]})) {
 7404:                 my $rem = $i%($numinrow);
 7405:                 if ($rem == 0) {
 7406:                     if ($i > 0) {
 7407:                         $output .= &Apache::loncommon::end_data_table_row();
 7408:                     }
 7409:                     $output .= &Apache::loncommon::start_data_table_row();
 7410:                 }
 7411:                 my $check;
 7412:                 if (ref($selectedref) eq 'ARRAY') {
 7413:                     if (grep(/^\Q$types->[$i]\E$/,@{$selectedref})) {
 7414:                         $check = ' checked="checked"';
 7415:                     }
 7416:                 }
 7417:                 $output .= '<td>'.
 7418:                            '<span class="LC_nobreak"><label>'.
 7419:                            '<input type="checkbox" name="'.$context.$role.'_status" '.
 7420:                            'value="'.$types->[$i].'"'.$check.$disabled.' />'.
 7421:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 7422:             }
 7423:         }
 7424:         $rem = @{$types}%($numinrow);
 7425:     }
 7426:     my $colsleft = $numinrow - $rem;
 7427:     if (($rem == 0) && (@{$types} > 0)) {
 7428:         $output .= &Apache::loncommon::start_data_table_row();
 7429:     }
 7430:     if ($colsleft > 1) {
 7431:         $output .= '<td colspan="'.$colsleft.'">';
 7432:     } else {
 7433:         $output .= '<td>';
 7434:     }
 7435:     my $defcheck;
 7436:     if (ref($selectedref) eq 'ARRAY') {
 7437:         if (grep(/^default$/,@{$selectedref})) {
 7438:             $defcheck = ' checked="checked"';
 7439:         }
 7440:     }
 7441:     $output .= '<span class="LC_nobreak"><label>'.
 7442:                '<input type="checkbox" name="'.$context.$role.'_status"'.
 7443:                'value="default"'.$defcheck.$disabled.' />'.
 7444:                $othertitle.'</label></span></td>'.
 7445:                &Apache::loncommon::end_data_table_row().
 7446:                &Apache::loncommon::end_data_table();
 7447:     return $output;
 7448: }
 7449: 
 7450: sub adhoc_staff {
 7451:     my ($access,$context,$role,$selectedref,$adhocref,$disabled) = @_;
 7452:     my $output;
 7453:     if (ref($adhocref) eq 'HASH') {
 7454:         my %by_fullname;
 7455:         my $numinrow = 4;
 7456:         my $rem;
 7457:         my @personnel = keys(%{$adhocref});
 7458:         if (@personnel) {
 7459:             foreach my $person (@personnel) {
 7460:                 my ($uname,$udom) = split(/:/,$person);
 7461:                 my $fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 7462:                 $by_fullname{$fullname} = $person;
 7463:             }
 7464:             my @sorted = sort(keys(%by_fullname));
 7465:             my $count = scalar(@sorted);
 7466:             $output = &Apache::loncommon::start_data_table();
 7467:             for (my $i=0; $i<$count; $i++) {
 7468:                 my $rem = $i%($numinrow);
 7469:                 if ($rem == 0) {
 7470:                     if ($i > 0) {
 7471:                         $output .= &Apache::loncommon::end_data_table_row();
 7472:                     }
 7473:                     $output .= &Apache::loncommon::start_data_table_row();
 7474:                 }
 7475:                 my $check;
 7476:                 my $user = $by_fullname{$sorted[$i]};
 7477:                 if (ref($selectedref) eq 'ARRAY') {
 7478:                     if (grep(/^\Q$user\E$/,@{$selectedref})) {
 7479:                         $check = ' checked="checked"';
 7480:                     }
 7481:                 }
 7482:                 if ($i == $count-1) {
 7483:                     my $colsleft = $numinrow - $rem;
 7484:                     if ($colsleft > 1) {
 7485:                         $output .= '<td colspan="'.$colsleft.'">';
 7486:                     } else {
 7487:                         $output .= '<td>';
 7488:                     }
 7489:                 } else {
 7490:                     $output .= '<td>';
 7491:                 }
 7492:                 $output .= '<span class="LC_nobreak"><label>'.
 7493:                            '<input type="checkbox" name="'.$context.$role.'_staff_'.$access.'" '.
 7494:                            'value="'.$user.'"'.$check.$disabled.' />'.$sorted[$i].
 7495:                            '</label></span></td>';
 7496:                 if ($i == $count-1) {
 7497:                     $output .= &Apache::loncommon::end_data_table_row();
 7498:                 }
 7499:             }
 7500:             $output .= &Apache::loncommon::end_data_table();
 7501:         }
 7502:     }
 7503:     return $output;
 7504: }
 7505: 
 7506: 
 7507: 1;
 7508: 

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