File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.97.2.9: download - view: text, annotated - select for diffs
Wed Jan 20 20:38:52 2010 UTC (14 years, 3 months ago) by raeburn
Branches: version_2_9_X
- Backport 1.107.

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

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