File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.141: download - view: text, annotated - select for diffs
Tue Aug 21 15:43:27 2012 UTC (11 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6340.
  - Course owner can revoke/modify Course Coordinator roles from list
    users screen. (One exception - course owner can not revoke his/her
    own CC role from this screen).
  - Move &is_courseowner() routine from loncreateuser.pm to
    lonuserutils.pm to facilitate re-use.

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

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