File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.177: download - view: text, annotated - select for diffs
Fri Oct 14 23:26:21 2016 UTC (7 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Some custom roles may receive only one usernamelink radio button.

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

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