File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.209: download - view: text, annotated - select for diffs
Tue Aug 24 00:15:02 2021 UTC (2 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6956. If internally authenticated is an option, but "Local auth" is the
  chosen option, form validation no longer prompts for initial password (for
  internal) if that field is empty.

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

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