File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.97.2.6: download - view: text, annotated - select for diffs
Wed Jan 20 20:28:40 2010 UTC (14 years, 3 months ago) by raeburn
Branches: version_2_9_X
- Backport 1.103.

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

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