File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.154: download - view: text, annotated - select for diffs
Thu Aug 29 12:35:32 2013 UTC (10 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_0_RC1, HEAD
- Wording change for consistency with change to phrase in de.pm rev. 1.530.

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

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