File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.136.6.2: download - view: text, annotated - select for diffs
Wed Feb 8 19:35:20 2012 UTC (12 years, 3 months ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.136: preferred, unified
- Customization for MITrelate.
  - Eliminate case sensitivity - new users all lower case.
  - Enforce requirement that all usernames are e-mail addresses when
    creating new users.

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

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