File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.130: download - view: text, annotated - select for diffs
Tue Nov 9 14:00:28 2010 UTC (13 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Text for alert when optional section field not associated (lost in 1.1 when
  routines in londropadd moved to lonuersutils.pm).
- Fix numbering in javacsript for reverse association.
- Missing argument in call to verify_message for reverse association.

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

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