File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.144: download - view: text, annotated - select for diffs
Fri Nov 30 16:03:07 2012 UTC (11 years, 5 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
- Label for "Open in a new window" link
- actionbox for "Display User Lists" after action
- Corrected wording (no "...for for..." anymore)

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

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