File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.148: download - view: text, annotated - select for diffs
Tue Feb 5 16:22:27 2013 UTC (11 years, 3 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Improvements and corrections to user management screen, course/community selection:
- XHTML
- Correction of lonuserutils.pm 1.142 (correct tag closure)
- Added missing labels
- Standard layout and XHTML (replaced pick_box by fieldset)
- Counter field: Internationalization and set to readonly

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

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