File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.184.4.9: download - view: text, annotated - select for diffs
Sat May 2 20:34:53 2020 UTC (4 years ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_3_uiuc, version_2_11_3_msu, version_2_11_3
Diff to branchpoint 1.184: preferred, unified
- For 2.11
  Backport 1.206

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

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