File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.193: download - view: text, annotated - select for diffs
Sat Nov 4 20:59:39 2017 UTC (6 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- When a csv file of users is uploaded, error messages are displayed in the
  case of (a) an invalid datatoken, or (b) invalid home server for new users,
  In (a) user is prompted to re-upload the file; in (b) user is prompted to
  select default domain again.

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

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