File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.184.4.3: download - view: text, annotated - select for diffs
Fri Jul 26 18:37:16 2019 UTC (4 years, 9 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.184: preferred, unified
- For 2.11
  Backport 1.201

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

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