File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.184.4.10.2.5: download - view: text, annotated - select for diffs
Fri Oct 6 02:27:26 2023 UTC (7 months ago) by raeburn
Branches: version_2_11_4_msu
Diff to branchpoint 1.184.4.10: preferred, unified
- For 2.11.4 (modified)
  Include changes from 1.185 (part), 1.212 (part) and 1.217

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

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