File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.103: download - view: text, annotated - select for diffs
Wed Nov 4 15:35:56 2009 UTC (14 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Accommodate Communities.
  - "co" role is sectionless.
  - additional arg in calls to &loncommon::coursebrowser_javascript().
  - additional arg for &print_upload_manager_header() - $crstype.
  - additional arg for &setsections_javascript() - $crstype.
  - (C)course -> (C)community
- Note about UTF8 encoding in uploaded classlists only shown if
  language is other than en, and in course context.

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

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