File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.131: download - view: text, annotated - select for diffs
Sun Nov 14 20:29:34 2010 UTC (13 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Prevent javascript error for reverse association (user file upload).

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

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