File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.175: download - view: text, annotated - select for diffs
Tue Oct 4 21:02:16 2016 UTC (7 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Move routines for creating/modifying custom roles to lonuserutils.pm to
  facilitate re-use.
- Changes to standard role names and privilege names when switching from
  Course to Commmunity, when adding/modifying custom roles, with a domain
  role active, occur client-side, and no longer require page reload.

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

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