File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.140: download - view: text, annotated - select for diffs
Tue Aug 21 01:50:34 2012 UTC (11 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Checkboxes so user can choose what user information to include in user listings.

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

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