File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.184.4.10.2.7: download - view: text, annotated - select for diffs
Fri Jan 5 04:09:47 2024 UTC (4 months, 3 weeks ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.184.4.10: preferred, unified
- For 2.11.4 (modified)
  Include changes in 1.221

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

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