File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.104: download - view: text, annotated - select for diffs
Thu Nov 12 15:58:22 2009 UTC (14 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Accommodate Communities
  - Custom role template depends on course type.
  - System-wide bre priv unavailable in custom roles used in Communities.
  - System-wide bro priv (own authored/co-authored published resources)
     available for custom roles in Communities.
  - Community Roles (including custom roles) will not be displayed in LON-CAPA
    versions 2.9 or older.

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

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