File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.161: download - view: text, annotated - select for diffs
Wed Feb 5 18:02:15 2014 UTC (10 years, 3 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Improve "Disable Safeguard" output and code:
- Moved safeguard directly to id field ("Modify existing user" context)
- Keep safeguard in pick_box ("Upload Users List" context)
- Optimized separation of content data and HTML output

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

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