File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.201: download - view: text, annotated - select for diffs
Tue Jul 23 13:58:53 2019 UTC (4 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Self-cataloging of courses based on institutional code is cached for 1 hour.

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

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