File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.109.2.1: download - view: text, annotated - select for diffs
Sun Dec 20 01:53:42 2009 UTC (14 years, 4 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
  - Eliminate message about UTF-8 coding.
  - Downgrade h2 -> h3.

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

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