File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.109.2.2: download - view: text, annotated - select for diffs
Tue Jan 5 22:08:48 2010 UTC (14 years, 4 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
  - Can only assign student role (or CC role -if course owner) for Concept Tests.

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

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