File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.207: download - view: text, annotated - select for diffs
Wed Jul 8 14:26:37 2020 UTC (3 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- coding style.

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

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