File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.149: download - view: text, annotated - select for diffs
Tue Feb 19 17:30:35 2013 UTC (11 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Changes for Domain Coordinator's user listings screen
  - "extent" column
    - not shown/selectable if role type is domain.
    - text for checkbox changed dynamically by javascript when role type of
      course, community, or author selected.
  - "status column"
     - not selectable  if role type is course or community.

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

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