File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.109.2.10: download - view: text, annotated - select for diffs
Mon Nov 15 17:57:35 2010 UTC (13 years, 5 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3
  - Customize message displayed when a CC attempts to add a user with a
    username which is not an e-mail address.

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

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