File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.188: download - view: text, annotated - select for diffs
Fri Aug 11 00:24:53 2017 UTC (6 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Trust Settings
  - lonnet::trusted_domains() returns array or array refs, for passing to
    loncommon::select_dom_form() or lonnet::will_trust().

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

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