File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.183: download - view: text, annotated - select for diffs
Mon Apr 10 23:18:54 2017 UTC (7 years ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_2_uiuc, version_2_11_2_educog, version_2_11_2, HEAD
- Current start and end dates included in form, even if dates are not shown,
  so user's access dates will remain unchanged when action is section switch.

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

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