File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.184.4.10.2.6: download - view: text, annotated - select for diffs
Sun Dec 10 04:31:41 2023 UTC (5 months ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.184.4.10: preferred, unified
- For 2.11.4 (modified)
  Include changes in rev. 1.220

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

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