File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.109.2.6: download - view: text, annotated - select for diffs
Mon Nov 8 21:08:27 2010 UTC (13 years, 6 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
  - Fix typo in 1.109.2.5.
  - Checking if usertype can be created accommodates case insensitivity of
    usernames.

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

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