File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.109.2.8: download - view: text, annotated - select for diffs
Tue Nov 9 14:14:55 2010 UTC (13 years, 7 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
  - Backport 1.130.
  - Renumbering for reverse association js as initial password now second in
     option list.
  - Scope issue for $user.

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

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