File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.184.4.4: download - view: text, annotated - select for diffs
Thu Aug 22 19:31:20 2019 UTC (4 years, 8 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.184: preferred, unified
- For 2.11
  Backport 1.196, 1.197, 1.200

    1: # The LearningOnline Network with CAPA
    2: # Utility functions for managing LON-CAPA user accounts
    3: #
    4: # $Id: lonuserutils.pm,v 1.184.4.4 2019/08/22 19:31:20 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: =pod
   34: 
   35: =head1 NAME
   36: 
   37: Apache::lonuserutils.pm
   38: 
   39: =head1 SYNOPSIS
   40: 
   41:     Utilities for management of users and custom roles
   42: 
   43:     Provides subroutines called by loncreateuser.pm
   44: 
   45: =head1 OVERVIEW
   46: 
   47: =cut
   48: 
   49: use strict;
   50: use Apache::lonnet;
   51: use Apache::loncommon();
   52: use Apache::lonhtmlcommon;
   53: use Apache::lonlocal;
   54: use Apache::longroup;
   55: use HTML::Entities;
   56: use LONCAPA qw(:DEFAULT :match);
   57: 
   58: ###############################################################
   59: ###############################################################
   60: # Drop student from all sections of a course, except optional $csec
   61: sub modifystudent {
   62:     my ($udom,$unam,$courseid,$csec,$desiredhost,$context)=@_;
   63:     # if $csec is undefined, drop the student from all the courses matching
   64:     # this one.  If $csec is defined, drop them from all other sections of
   65:     # this course and add them to section $csec
   66:     my ($cnum,$cdom) = &get_course_identity($courseid);
   67:     my %roles = &Apache::lonnet::dump('roles',$udom,$unam);
   68:     my ($tmp) = keys(%roles);
   69:     # Bail out if we were unable to get the students roles
   70:     return "$1" if ($tmp =~ /^(con_lost|error|no_such_host)/i);
   71:     # Go through the roles looking for enrollment in this course
   72:     my $result = '';
   73:     foreach my $course (keys(%roles)) {
   74:         if ($course=~m{^/\Q$cdom\E/\Q$cnum\E(?:\/)*(?:\s+)*(\w+)*\_st$}) {
   75:             # We are in this course
   76:             my $section=$1;
   77:             $section='' if ($course eq "/$cdom/$cnum".'_st');
   78:             if (defined($csec) && $section eq $csec) {
   79:                 $result .= 'ok:';
   80:             } elsif ( ((!$section) && (!$csec)) || ($section ne $csec) ) {
   81:                 my (undef,$end,$start)=split(/\_/,$roles{$course});
   82:                 my $now=time;
   83:                 # if this is an active role
   84:                 if (!($start && ($now<$start)) || !($end && ($now>$end))) {
   85:                     my $reply=&Apache::lonnet::modifystudent
   86:                         # dom  name  id mode pass     f     m     l     g
   87:                         ($udom,$unam,'',  '',  '',undef,undef,undef,undef,
   88:                          $section,time,undef,undef,$desiredhost,'','manual',
   89:                          '',$courseid,'',$context);
   90:                     $result .= $reply.':';
   91:                 }
   92:             }
   93:         }
   94:     }
   95:     if ($result eq '') {
   96:         $result = &mt('Unable to find section for this student');
   97:     } else {
   98:         $result =~ s/(ok:)+/ok/g;
   99:     }
  100:     return $result;
  101: }
  102: 
  103: sub modifyuserrole {
  104:     my ($context,$setting,$changeauth,$cid,$udom,$uname,$uid,$umode,$upass,
  105:         $first,$middle,$last,$gene,$sec,$forceid,$desiredhome,$email,$role,
  106:         $end,$start,$checkid,$inststatus) = @_;
  107:     my ($scope,$userresult,$authresult,$roleresult,$idresult);
  108:     if ($setting eq 'course' || $context eq 'course') {
  109:         $scope = '/'.$cid;
  110:         $scope =~ s/\_/\//g;
  111:         if (($role ne 'cc') && ($role ne 'co') && ($sec ne '')) {
  112:             $scope .='/'.$sec;
  113:         }
  114:     } elsif ($context eq 'domain') {
  115:         $scope = '/'.$env{'request.role.domain'}.'/';
  116:     } elsif ($context eq 'author') {
  117:         $scope =  '/'.$env{'user.domain'}.'/'.$env{'user.name'};
  118:     }
  119:     if ($context eq 'domain') {
  120:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
  121:         if ($uhome ne 'no_host') {
  122:             if (($changeauth eq 'Yes') && (&Apache::lonnet::allowed('mau',$udom))) {
  123:                 if ((($umode =~ /^krb4|krb5|internal$/) && $upass ne '') ||
  124:                     ($umode eq 'localauth')) {
  125:                     $authresult = &Apache::lonnet::modifyuserauth($udom,$uname,$umode,$upass);
  126:                 }
  127:             }
  128:             if (($forceid) && (&Apache::lonnet::allowed('mau',$udom)) &&
  129:                 ($env{'form.recurseid'}) && ($checkid)) {
  130:                 my %userupdate = (
  131:                                   lastname   => $last,
  132:                                   middlename => $middle,
  133:                                   firstname  => $first,
  134:                                   generation => $gene,
  135:                                   id         => $uid,
  136:                                  );
  137:                 $idresult = &propagate_id_change($uname,$udom,\%userupdate);
  138:             }
  139:         }
  140:     }
  141:     $userresult =
  142:         &Apache::lonnet::modifyuser($udom,$uname,$uid,$umode,$upass,$first,
  143:                                     $middle,$last,$gene,$forceid,$desiredhome,
  144:                                     $email,$inststatus);
  145:     if ($userresult eq 'ok') {
  146:         if ($role ne '') {
  147:             $role =~ s/_/\//g;
  148:             $roleresult = &Apache::lonnet::assignrole($udom,$uname,$scope,
  149:                                                       $role,$end,$start,'',
  150:                                                       '',$context);
  151:         }
  152:     }
  153:     return ($userresult,$authresult,$roleresult,$idresult);
  154: }
  155: 
  156: sub propagate_id_change {
  157:     my ($uname,$udom,$user) = @_;
  158:     my (@types,@roles);
  159:     @types = ('active','future');
  160:     @roles = ('st');
  161:     my $idresult;
  162:     my %roleshash = &Apache::lonnet::get_my_roles($uname,
  163:                         $udom,'userroles',\@types,\@roles);
  164:     my %args = (
  165:                 one_time => 1,
  166:                );
  167:     foreach my $item (keys(%roleshash)) {
  168:         my ($cnum,$cdom,$role) = split(/:/,$item,-1);
  169:         my ($start,$end) = split(/:/,$roleshash{$item});
  170:         if (&Apache::lonnet::is_course($cdom,$cnum)) {
  171:             my $result = &update_classlist($cdom,$cnum,$udom,$uname,$user);
  172:             my %coursehash = 
  173:                 &Apache::lonnet::coursedescription($cdom.'_'.$cnum,\%args);
  174:             my $cdesc = $coursehash{'description'};
  175:             if ($cdesc eq '') { 
  176:                 $cdesc = $cdom.'_'.$cnum;
  177:             }
  178:             if ($result eq 'ok') {
  179:                 $idresult .= &mt('Classlist update for "[_1]" in "[_2]".',$uname.':'.$udom,$cdesc).'<br />'."\n";
  180:             } else {
  181:                 $idresult .= &mt('Error: "[_1]" during classlist update for "[_2]" in "[_3]".',$result,$uname.':'.$udom,$cdesc).'<br />'."\n";
  182:             }
  183:         }
  184:     }
  185:     return $idresult;
  186: }
  187: 
  188: sub update_classlist {
  189:     my ($cdom,$cnum,$udom,$uname,$user,$newend) = @_;
  190:     my ($uid,$classlistentry);
  191:     my $fullname =
  192:         &Apache::lonnet::format_name($user->{'firstname'},$user->{'middlename'},
  193:                                      $user->{'lastname'},$user->{'generation'},
  194:                                      'lastname');
  195:     my %classhash = &Apache::lonnet::get('classlist',[$uname.':'.$udom],
  196:                                          $cdom,$cnum);
  197:     my @classinfo = split(/:/,$classhash{$uname.':'.$udom});
  198:     my $ididx=&Apache::loncoursedata::CL_ID() - 2;
  199:     my $nameidx=&Apache::loncoursedata::CL_FULLNAME() - 2;
  200:     my $endidx = &Apache::loncoursedata::CL_END() - 2;
  201:     my $startidx = &Apache::loncoursedata::CL_START() - 2;
  202:     for (my $i=0; $i<@classinfo; $i++) {
  203:         if ($i == $endidx) {
  204:             if ($newend ne '') {
  205:                 $classlistentry .= $newend.':';
  206:             } else {
  207:                 $classlistentry .= $classinfo[$i].':';
  208:             }
  209:         } elsif ($i == $startidx) {
  210:             if ($newend ne '') {
  211:                 if ($classinfo[$i] > $newend) {
  212:                     $classlistentry .= $newend.':';
  213:                 } else {
  214:                     $classlistentry .= $classinfo[$i].':';
  215:                 }
  216:             } else {
  217:                 $classlistentry .= $classinfo[$i].':';
  218:             }
  219:         } elsif ($i == $ididx) {
  220:             if (defined($user->{'id'})) {
  221:                 $classlistentry .= $user->{'id'}.':';
  222:             } else {
  223:                 $classlistentry .= $classinfo[$i].':';
  224:             }
  225:         } elsif ($i == $nameidx) {
  226:             if (defined($user->{'lastname'})) {
  227:                 $classlistentry .= $fullname.':';
  228:             } else {
  229:                 $classlistentry .= $classinfo[$i].':';
  230:             }
  231:         } else {
  232:             $classlistentry .= $classinfo[$i].':';
  233:         }
  234:     }
  235:     $classlistentry =~ s/:$//;
  236:     my $reply=&Apache::lonnet::cput('classlist',
  237:                                     {"$uname:$udom" => $classlistentry},
  238:                                     $cdom,$cnum);
  239:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
  240:         return 'ok';
  241:     } else {
  242:         return 'error: '.$reply;
  243:     }
  244: }
  245: 
  246: 
  247: ###############################################################
  248: ###############################################################
  249: # build a role type and role selection form
  250: sub domain_roles_select {
  251:     # Set up the role type and role selection boxes when in 
  252:     # domain context   
  253:     #
  254:     # Role types
  255:     my @roletypes = ('domain','author','course','community');
  256:     my %lt = &role_type_names();
  257:     my $onchangefirst = "updateCols('showrole')";
  258:     my $onchangesecond = "updateCols('showrole')";
  259:     #
  260:     # build up the menu information to be passed to
  261:     # &Apache::loncommon::linked_select_forms
  262:     my %select_menus;
  263:     if ($env{'form.roletype'} eq '') {
  264:         $env{'form.roletype'} = 'domain';
  265:     }
  266:     foreach my $roletype (@roletypes) {
  267:         # set up the text for this domain
  268:         $select_menus{$roletype}->{'text'}= $lt{$roletype};
  269:         my $crstype;
  270:         if ($roletype eq 'community') {
  271:             $crstype = 'Community';
  272:         }
  273:         # we want a choice of 'default' as the default in the second menu
  274:         if ($env{'form.roletype'} ne '') {
  275:             $select_menus{$roletype}->{'default'} = $env{'form.showrole'};
  276:         } else { 
  277:             $select_menus{$roletype}->{'default'} = 'Any';
  278:         }
  279:         # Now build up the other items in the second menu
  280:         my @roles;
  281:         if ($roletype eq 'domain') {
  282:             @roles = &domain_roles();
  283:         } elsif ($roletype eq 'author') {
  284:             @roles = &construction_space_roles();
  285:         } else {
  286:             my $custom = 1;
  287:             @roles = &course_roles('domain',undef,$custom,$roletype);
  288:         }
  289:         my $order = ['Any',@roles];
  290:         $select_menus{$roletype}->{'order'} = $order; 
  291:         foreach my $role (@roles) {
  292:             if ($role eq 'cr') {
  293:                 $select_menus{$roletype}->{'select2'}->{$role} =
  294:                               &mt('Custom role');
  295:             } else {
  296:                 $select_menus{$roletype}->{'select2'}->{$role} = 
  297:                               &Apache::lonnet::plaintext($role,$crstype);
  298:             }
  299:         }
  300:         $select_menus{$roletype}->{'select2'}->{'Any'} = &mt('Any');
  301:     }
  302:     my $result = &Apache::loncommon::linked_select_forms
  303:         ('studentform',('&nbsp;'x3).&mt('Role: '),$env{'form.roletype'},
  304:          'roletype','showrole',\%select_menus,
  305:          ['domain','author','course','community'],$onchangefirst,
  306:          $onchangesecond);
  307:     return $result;
  308: }
  309: 
  310: ###############################################################
  311: ###############################################################
  312: sub hidden_input {
  313:     my ($name,$value) = @_;
  314:     return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
  315: }
  316: 
  317: sub print_upload_manager_header {
  318:     my ($r,$datatoken,$distotal,$krbdefdom,$context,$permission,$crstype,
  319:         $can_assign)=@_;
  320:     my $javascript;
  321:     #
  322:     if (! exists($env{'form.upfile_associate'})) {
  323:         $env{'form.upfile_associate'} = 'forward';
  324:     }
  325:     if ($env{'form.associate'} eq 'Reverse Association') {
  326:         if ( $env{'form.upfile_associate'} ne 'reverse' ) {
  327:             $env{'form.upfile_associate'} = 'reverse';
  328:         } else {
  329:             $env{'form.upfile_associate'} = 'forward';
  330:         }
  331:     }
  332:     if ($env{'form.upfile_associate'} eq 'reverse') {
  333:         $javascript=&upload_manager_javascript_reverse_associate($can_assign);
  334:     } else {
  335:         $javascript=&upload_manager_javascript_forward_associate($can_assign);
  336:     }
  337:     #
  338:     # Deal with restored settings
  339:     my $password_choice = '';
  340:     if (exists($env{'form.ipwd_choice'}) &&
  341:         $env{'form.ipwd_choice'} ne '') {
  342:         # If a column was specified for password, assume it is for an
  343:         # internal password.  This is a bug waiting to be filed (could be
  344:         # local or krb auth instead of internal) but I do not have the
  345:         # time to mess around with this now.
  346:         $password_choice = 'int';
  347:     }
  348:     #
  349:     my $groupslist;
  350:     if ($context eq 'course') {
  351:         $groupslist = &get_groupslist();
  352:     }
  353:     my $javascript_validations =
  354:         &javascript_validations('upload',$krbdefdom,$password_choice,undef,
  355:                                 $env{'request.role.domain'},$context,
  356:                                 $groupslist,$crstype);
  357:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
  358:     $r->print(
  359:         '<h3>'.&mt('Identify fields in uploaded list')."</h3>\n".
  360:         '<p class="LC_info">'.
  361:         &mt('Total number of records found in file: [_1]'
  362:            ,'<b>'.$distotal.'</b>').
  363:         "</p>\n"
  364:     );
  365:     if ($distotal == 0) {
  366:         $r->print('<p class="LC_warning">'.&mt('None found').'</p>');
  367:     }
  368:     $r->print(
  369:         '<p>'.
  370:         &mt('Enter as many fields as you can.').'<br />'.
  371:         &mt('The system will inform you and bring you back to this page,[_1]if the data selected are insufficient to add users.','<br />').
  372:         "</p>\n"
  373:     );
  374:     $r->print(&hidden_input('action','upload').
  375:               &hidden_input('state','got_file').
  376:               &hidden_input('associate','').
  377:               &hidden_input('datatoken',$datatoken).
  378:               &hidden_input('fileupload',$env{'form.fileupload'}).
  379:               &hidden_input('upfiletype',$env{'form.upfiletype'}).
  380:               &hidden_input('upfile_associate',$env{'form.upfile_associate'}));
  381:     $r->print(
  382:         '<div class="LC_left_float">'.
  383:         '<fieldset><legend>'.&mt('Functions').'</legend>'.
  384:         '<label><input type="checkbox" name="noFirstLine"'.$checked.' />'.
  385:               &mt('Ignore First Line').'</label>'.
  386:         ' <input type="button" value="'.&mt('Reverse Association').'" '.
  387:               'name="Reverse Association" '.
  388:               'onclick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />'.
  389:         '</fieldset></div><br clear="all" />'
  390:     );
  391:     $r->print(
  392:         '<script type="text/javascript" language="Javascript">'."\n".
  393:         '// <![CDATA['."\n".
  394:         $javascript."\n".$javascript_validations."\n".
  395:         '// ]]>'."\n".
  396:         '</script>'
  397:     );
  398: }
  399: 
  400: ###############################################################
  401: ###############################################################
  402: sub javascript_validations {
  403:     my ($mode,$krbdefdom,$curr_authtype,$curr_authfield,$domain,
  404:         $context,$groupslist,$crstype)=@_;
  405:     my %param = (
  406:                   kerb_def_dom => $krbdefdom,
  407:                   curr_authtype => $curr_authtype,
  408:                 );
  409:     if ($mode eq 'upload') {
  410:         $param{'formname'} = 'studentform';
  411:     } elsif ($mode eq 'createcourse') {
  412:         $param{'formname'} = 'ccrs';
  413:     } elsif ($mode eq 'modifycourse') {
  414:         $param{'formname'} = 'cmod';
  415:         $param{'mode'} = 'modifycourse',
  416:         $param{'curr_autharg'} = $curr_authfield;
  417:     }
  418: 
  419:     my $showcredits;
  420:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  421:     if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'} || $domdefaults{'textbookcredits'}) {
  422:         $showcredits = 1;
  423:     }
  424: 
  425:     my ($setsection_call,$setsections_js);
  426:     my $finish = "  vf.submit();\n";
  427:     if ($mode eq 'upload') {
  428:         if (($context eq 'course') || ($context eq 'domain')) {
  429:             if ($context eq 'course') {
  430:                 if ($env{'request.course.sec'} eq '') {
  431:                     $setsection_call = 'setSections(document.'.$param{'formname'}.",'$crstype'".');';
  432:                     $setsections_js =
  433:                         &setsections_javascript($param{'formname'},$groupslist,
  434:                                                 $mode,'',$crstype,$showcredits);
  435:                 } else {
  436:                     $setsection_call = "'ok'";
  437:                 }
  438:             } elsif ($context eq 'domain') {
  439:                 $setsection_call = 'setCourse()';
  440:                 $setsections_js = &dc_setcourse_js($param{'formname'},$mode,
  441:                                                    $context,$showcredits,$domain);
  442:             }
  443:             $finish = "  var checkSec = $setsection_call\n".
  444:                       "  if (checkSec == 'ok') {\n".
  445:                       "      vf.submit();\n".
  446:                       "   }\n";
  447:         }
  448:     }
  449:     my $authheader = &Apache::loncommon::authform_header(%param);
  450: 
  451:     my %alert = &Apache::lonlocal::texthash
  452:         (username => 'You need to specify the username field.',
  453:          authen   => 'You must choose an authentication type.',
  454:          krb      => 'You need to specify the Kerberos domain.',
  455:          ipass    => 'You need to specify the initial password.',
  456:          name     => 'The optional name field was not specified.',
  457:          snum     => 'The optional student/employee ID field was not specified.',
  458:          section  => 'The optional section field was not specified.',
  459:          email    => 'The optional e-mail address field was not specified.',
  460:          role     => 'The optional role field was not specified.',
  461:          domain   => 'The optional domain field was not specified.',
  462:          continue => 'Continue adding users?',
  463:          );
  464:     if ($showcredits) {
  465:         $alert{'credits'} = &mt('The optional credits field was not specified');
  466:     }
  467:     if (($mode eq 'upload') && ($context eq 'domain')) {
  468:         $alert{'inststatus'} = &mt('The optional affiliation field was not specified'); 
  469:     }
  470:     &js_escape(\%alert);
  471:     my $function_name = <<"END";
  472: $setsections_js
  473: 
  474: function verify_message (vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits) {
  475: END
  476:     my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($domain);
  477:     my $auth_checks;
  478:     if ($mode eq 'createcourse') {
  479:         $auth_checks .= (<<END);
  480:     if (vf.autoadds[0].checked == true) {
  481:         if (current.radiovalue == null || current.radiovalue == 'nochange') {
  482:             alert('$alert{'authen'}');
  483:             return;
  484:         }
  485:     }
  486: END
  487:     } else {
  488:         $auth_checks .= (<<END);
  489:     var foundatype=0;
  490:     if (founduname==0) {
  491:         alert('$alert{'username'}');
  492:         return;
  493:     }
  494: 
  495: END
  496:         if ($authnum > 1) {
  497:             $auth_checks .= (<<END);
  498:     if (current.radiovalue == null || current.radiovalue == '' || current.radiovalue == 'nochange') {
  499:         // They did not check any of the login radiobuttons.
  500:         alert('$alert{'authen'}');
  501:         return;
  502:     }
  503: END
  504:         }
  505:     }
  506:     if ($mode eq 'createcourse') {
  507:         $auth_checks .= "
  508:     if ( (vf.autoadds[0].checked == true) &&
  509:          (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') ) {
  510: ";
  511:     } elsif ($mode eq 'modifycourse') {
  512:         $auth_checks .= "
  513:     if (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') {
  514: ";
  515:     }
  516:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
  517:         $auth_checks .= (<<END);
  518:         var alertmsg = '';
  519:         switch (current.radiovalue) {
  520:             case 'krb':
  521:                 alertmsg = '$alert{'krb'}';
  522:                 break;
  523:             default:
  524:                 alertmsg = '';
  525:         }
  526:         if (alertmsg != '') {
  527:             alert(alertmsg);
  528:             return;
  529:         }
  530:     }
  531: /* regexp here to check for non \d \. in credits */
  532: END
  533:     } else {
  534:         my ($numrules,$intargjs) =
  535:             &passwd_validation_js('vf.elements[current.argfield].value',$domain);
  536:         $auth_checks .= (<<END);
  537:     foundatype=1;
  538:     if (current.argfield == null || current.argfield == '') {
  539:         // The login radiobutton checked does not have an associated textbox
  540:     } else if (vf.elements[current.argfield].value == '') {
  541:         var alertmsg = '';
  542:         switch (current.radiovalue) {
  543:             case 'krb':
  544:                 alertmsg = '$alert{'krb'}';
  545:                 break;
  546:             case 'loc':
  547:             case 'int':
  548:                 alertmsg = '$alert{'ipass'}';
  549:                 break;
  550:             case 'fsys':
  551:                 alertmsg = '$alert{'ipass'}';
  552:                 break;
  553:             default:
  554:                 alertmsg = '';
  555:         }
  556:         if (alertmsg != '') {
  557:             alert(alertmsg);
  558:             return;
  559:         }
  560:     } else if (current.radiovalue == 'int') {
  561:         if ($numrules > 0) {
  562: $intargjs
  563:         }
  564:     }
  565: END
  566:     }
  567:     my $section_checks;
  568:     my $optional_checks = '';
  569:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
  570:         $optional_checks = (<<END);
  571:     vf.submit();
  572: }
  573: END
  574:     } else {
  575:         $section_checks = &section_check_js();
  576:         $optional_checks = (<<END);
  577:     var message='';
  578:     if (foundname==0) {
  579:         message='$alert{'name'}';
  580:     }
  581:     if (foundid==0) {
  582:         if (message!='') {
  583:             message+='\\n';
  584:         }
  585:         message+='$alert{'snum'}';
  586:     }
  587:     if (foundsec==0) {
  588:         if (message!='') {
  589:             message+='\\n';
  590:         }
  591:         message+='$alert{'section'}';
  592:     }
  593:     if (foundemail==0) {
  594:         if (message!='') {
  595:             message+='\\n';
  596:         }
  597:         message+='$alert{'email'}';
  598:     }
  599:     if (foundrole==0) {
  600:         if (message!='') {
  601:             message+='\\n';
  602:         }
  603:         message+='$alert{'role'}';
  604:     }
  605:     if (founddomain==0) {
  606:         if (message!='') {
  607:             message+='\\n';
  608:         }
  609:         message+='$alert{'domain'}';
  610:     }
  611: END
  612:         if ($showcredits) {
  613:             $optional_checks .= <<END;
  614:     if (foundcredits==0) {
  615:         if (message!='') {
  616:             message+='\\n';
  617:         }
  618:         message+='$alert{'credits'}';
  619:     }
  620: END
  621:         }
  622:         if (($mode eq 'upload') && ($context eq 'domain')) {
  623:             $optional_checks .= (<<END);
  624: 
  625:     if (foundinststatus==0) {
  626:         if (message!='') {
  627:             message+='\\n';
  628:         }
  629:         message+='$alert{'inststatus'}';
  630:     }
  631: END
  632:         }
  633:         $optional_checks .= (<<END);
  634: 
  635:     if (message!='') {
  636:         message+= '\\n$alert{'continue'}';
  637:         if (confirm(message)) {
  638:             vf.state.value='enrolling';
  639:             $finish
  640:         }
  641:     } else {
  642:         vf.state.value='enrolling';
  643:         $finish
  644:     }
  645: }
  646: END
  647:     }
  648:     my $result = $function_name.$auth_checks.$optional_checks."\n".
  649:                  $section_checks.$authheader;
  650:     return $result;
  651: }
  652: 
  653: sub passwd_validation_js {
  654:     my ($currpasswdval,$domain) = @_;
  655:     my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
  656:     my ($min,$max,@chars,$numrules,$intargjs,%alert);
  657:     $numrules = 0;
  658:     if (ref($passwdconf{'chars'}) eq 'ARRAY') {
  659:         if ($passwdconf{'min'} =~ /^\d+$/) {
  660:             $min = $passwdconf{'min'};
  661:             $numrules ++;
  662:         }
  663:         if ($passwdconf{'max'} =~ /^\d+$/) {
  664:             $max = $passwdconf{'max'};
  665:             $numrules ++;
  666:         }
  667:         @chars = @{$passwdconf{'chars'}};
  668:         if (@chars) {
  669:             $numrules ++;
  670:         }
  671:     } else {
  672:         $min = 7;
  673:         $numrules ++;
  674:     }
  675:     if (($min ne '') || ($max ne '') || (@chars > 0)) {
  676:         my $alertmsg = &mt('Initial password did not satisfy requirement(s):').'\n\n';
  677:         if ($min) {
  678:             $alert{'min'} = &mt('minimum [quant,_1,character]',$min).'\n';
  679:         }
  680:         if ($max) {
  681:             $alert{'max'} = &mt('maximum [quant,_1,character]',$max).'\n';
  682:         }
  683:         my (@charalerts,@charrules);
  684:         if (@chars) {
  685:             if (grep(/^uc$/,@chars)) {
  686:                 push(@charalerts,&mt('contain at least one upper case letter'));
  687:                 push(@charrules,'uc');
  688:             }
  689:             if (grep(/^lc$/,@chars)) {
  690:                 push(@charalerts,&mt('contain at least one lower case letter'));
  691:                 push(@charrules,'lc');
  692:             }
  693:             if (grep(/^num$/,@chars)) {
  694:                 push(@charalerts,&mt('contain at least one number'));
  695:                 push(@charrules,'num');
  696:             }
  697:             if (grep(/^spec$/,@chars)) {
  698:                 push(@charalerts,&mt('contain at least one non-alphanumeric'));
  699:                 push(@charrules,'spec');
  700:             }
  701:         }
  702:         $intargjs = qq|            var rulesmsg = '';\n|.
  703:                     qq|            var currpwval = $currpasswdval;\n|;
  704:             if ($min) {
  705:                 $intargjs .= qq|
  706:             if (currpwval.length < $min) {
  707:                 rulesmsg += ' - $alert{min}';
  708:             }
  709: |;
  710:             }
  711:             if ($max) {
  712:                 $intargjs .= qq|
  713:             if (currpwval.length > $max) {
  714:                 rulesmsg += ' - $alert{max}';
  715:             }
  716: |;
  717:             }
  718:             if (@chars > 0) {
  719:                 my $charrulestr = '"'.join('","',@charrules).'"';
  720:                 my $charalertstr = '"'.join('","',@charalerts).'"';
  721:                 $intargjs .= qq|            var brokerules = new Array();\n|.
  722:                              qq|            var charrules = new Array($charrulestr);\n|.
  723:                              qq|            var charalerts = new Array($charalertstr);\n|;
  724:                 my %rules;
  725:                 map { $rules{$_} = 1; } @chars;
  726:                 if ($rules{'uc'}) {
  727:                     $intargjs .= qq|
  728:             var ucRegExp = /[A-Z]/;
  729:             if (!ucRegExp.test(currpwval)) {
  730:                 brokerules.push('uc');
  731:             }
  732: |;
  733:                 }
  734:                 if ($rules{'lc'}) {
  735:                     $intargjs .= qq|
  736:             var lcRegExp = /[a-z]/;
  737:             if (!lcRegExp.test(currpwval)) {
  738:                 brokerules.push('lc');
  739:             }
  740: |;
  741:                 }
  742:                 if ($rules{'num'}) {
  743:                      $intargjs .= qq|
  744:             var numRegExp = /[0-9]/;
  745:             if (!numRegExp.test(currpwval)) {
  746:                 brokerules.push('num');
  747:             }
  748: |;
  749:                 }
  750:                 if ($rules{'spec'}) {
  751:                      $intargjs .= q|
  752:             var specRegExp = /[!"#$%&'()*+,\-.\/:;<=>?@[\\^\]_`{\|}~]/;
  753:             if (!specRegExp.test(currpwval)) {
  754:                 brokerules.push('spec');
  755:             }
  756: |;
  757:                 }
  758:                 $intargjs .= qq|
  759:             if (brokerules.length > 0) {
  760:                 for (var i=0; i<brokerules.length; i++) {
  761:                     for (var j=0; j<charrules.length; j++) {
  762:                         if (brokerules[i] == charrules[j]) {
  763:                             rulesmsg += ' - '+charalerts[j]+'\\n';
  764:                             break;
  765:                         }
  766:                     }
  767:                 }
  768:             }
  769: |;
  770:             }
  771:             $intargjs .= qq|
  772:             if (rulesmsg != '') {
  773:                 rulesmsg = '$alertmsg'+rulesmsg;
  774:                 alert(rulesmsg);
  775:                 return false;
  776:             }
  777: |;
  778:     }
  779:     return ($numrules,$intargjs);
  780: }
  781: 
  782: ###############################################################
  783: ###############################################################
  784: sub upload_manager_javascript_forward_associate {
  785:     my ($can_assign) = @_;
  786:     my ($auth_update,$numbuttons,$argreset);
  787:     if (ref($can_assign) eq 'HASH') {
  788:         if ($can_assign->{'krb4'} || $can_assign->{'krb5'}) {
  789:             $argreset .= "      vf.krbarg.value='';\n";
  790:             $numbuttons ++ ;
  791:         }
  792:         if ($can_assign->{'int'}) {
  793:             $argreset .= "      vf.intarg.value='';\n";
  794:             $numbuttons ++;
  795:         }
  796:         if ($can_assign->{'loc'}) {
  797:             $argreset .= "      vf.locarg.value='';\n";
  798:             $numbuttons ++;
  799:         }
  800:         if (!$can_assign->{'int'}) {
  801:             my $warning = &mt('You may not specify an initial password for each user, as this is only available when new users use LON-CAPA internal authentication.')."\n".
  802:                           &mt('Your current role does not have rights to create users with that authentication type.');
  803:             &js_escape(\$warning);
  804:             $auth_update = <<"END";
  805:    // Currently the initial password field is only supported for internal auth
  806:    // (see bug 6368).
  807:    if (nw==9) {
  808:        eval('vf.f'+tf+'.selectedIndex=0;')
  809:        alert('$warning');
  810:    }
  811: END
  812:         } elsif ($numbuttons > 1) {
  813:             $auth_update = <<"END";
  814:    // If we set the password, make the password form below correspond to
  815:    // the new value.
  816:    if (nw==9) {
  817:       changed_radio('int',document.studentform);
  818:       set_auth_radio_buttons('int',document.studentform);
  819: $argreset
  820:    }
  821: 
  822: END
  823:         }
  824:     }
  825: 
  826:     return(<<ENDPICK);
  827: function verify(vf,sec_caller) {
  828:     var founduname=0;
  829:     var foundpwd=0;
  830:     var foundname=0;
  831:     var foundid=0;
  832:     var foundsec=0;
  833:     var foundemail=0;
  834:     var foundrole=0;
  835:     var founddomain=0;
  836:     var foundinststatus=0;
  837:     var foundcredits=0;
  838:     var tw;
  839:     for (i=0;i<=vf.nfields.value;i++) {
  840:         tw=eval('vf.f'+i+'.selectedIndex');
  841:         if (tw==1) { founduname=1; }
  842:         if ((tw>=2) && (tw<=6)) { foundname=1; }
  843:         if (tw==7) { foundid=1; }
  844:         if (tw==8) { foundsec=1; }
  845:         if (tw==9) { foundpwd=1; }
  846:         if (tw==10) { foundemail=1; }
  847:         if (tw==11) { foundrole=1; }
  848:         if (tw==12) { founddomain=1; }
  849:         if (tw==13) { foundinststatus=1; }
  850:         if (tw==14) { foundcredits=1; }
  851:     }
  852:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits);
  853: }
  854: 
  855: //
  856: // vf = this.form
  857: // tf = column number
  858: //
  859: // values of nw
  860: //
  861: // 0 = none
  862: // 1 = username
  863: // 2 = names (lastname, firstnames)
  864: // 3 = fname (firstname)
  865: // 4 = mname (middlename)
  866: // 5 = lname (lastname)
  867: // 6 = gen   (generation)
  868: // 7 = id
  869: // 8 = section
  870: // 9 = ipwd  (password)
  871: // 10 = email address
  872: // 11 = role
  873: // 12 = domain
  874: // 13 = inststatus
  875: // 14 = foundcredits 
  876: 
  877: function flip(vf,tf) {
  878:    var nw=eval('vf.f'+tf+'.selectedIndex');
  879:    var i;
  880:    // make sure no other columns are labeled the same as this one
  881:    for (i=0;i<=vf.nfields.value;i++) {
  882:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
  883:           eval('vf.f'+i+'.selectedIndex=0;')
  884:       }
  885:    }
  886:    // If we set this to 'lastname, firstnames', clear out all the ones
  887:    // set to 'fname','mname','lname','gen' (3,4,5,6) currently.
  888:    if (nw==2) {
  889:       for (i=0;i<=vf.nfields.value;i++) {
  890:          if ((eval('vf.f'+i+'.selectedIndex')>=3) &&
  891:              (eval('vf.f'+i+'.selectedIndex')<=6)) {
  892:              eval('vf.f'+i+'.selectedIndex=0;')
  893:          }
  894:       }
  895:    }
  896:    // If we set this to one of 'fname','mname','lname','gen' (3,4,5,6),
  897:    // clear out any that are set to 'lastname, firstnames' (2)
  898:    if ((nw>=3) && (nw<=6)) {
  899:       for (i=0;i<=vf.nfields.value;i++) {
  900:          if (eval('vf.f'+i+'.selectedIndex')==2) {
  901:              eval('vf.f'+i+'.selectedIndex=0;')
  902:          }
  903:       }
  904:    }
  905:    $auth_update
  906: }
  907: 
  908: function clearpwd(vf) {
  909:     var i;
  910:     for (i=0;i<=vf.nfields.value;i++) {
  911:         if (eval('vf.f'+i+'.selectedIndex')==9) {
  912:             eval('vf.f'+i+'.selectedIndex=0;')
  913:         }
  914:     }
  915: }
  916: 
  917: ENDPICK
  918: }
  919: 
  920: ###############################################################
  921: ###############################################################
  922: sub upload_manager_javascript_reverse_associate {
  923:     my ($can_assign) = @_;
  924:     my ($auth_update,$numbuttons,$argreset);
  925:     if (ref($can_assign) eq 'HASH') {
  926:         if ($can_assign->{'krb4'} || $can_assign->{'krb5'}) {
  927:             $argreset .= "      vf.krbarg.value='';\n";
  928:             $numbuttons ++ ;
  929:         }
  930:         if ($can_assign->{'int'}) {
  931:             $argreset .= "      vf.intarg.value='';\n";
  932:             $numbuttons ++;
  933:         }
  934:         if ($can_assign->{'loc'}) {
  935:             $argreset .= "      vf.locarg.value='';\n";
  936:             $numbuttons ++;
  937:         }
  938:         if (!$can_assign->{'int'}) {
  939:             my $warning = &mt('You may not specify an initial password, as this is only available when new users use LON-CAPA internal authentication.\n').
  940:                           &mt('Your current role does not have rights to create users with that authentication type.');
  941:             &js_escape(\$warning);
  942:             $auth_update = <<"END";
  943:    // Currently the initial password field is only supported for internal auth
  944:    // (see bug 6368).
  945:    if (tf==8 && nw!=0) {
  946:        eval('vf.f'+tf+'.selectedIndex=0;')
  947:        alert('$warning');
  948:    }
  949: END
  950:         } elsif ($numbuttons > 1) {
  951:             $auth_update = <<"END";
  952:    // initial password specified, pick internal authentication
  953:    if (tf==8 && nw!=0) {
  954:       changed_radio('int',document.studentform);
  955:       set_auth_radio_buttons('int',document.studentform);
  956: $argreset
  957:    }
  958: 
  959: END
  960:         }
  961:     }
  962: 
  963:     return(<<ENDPICK);
  964: function verify(vf,sec_caller) {
  965:     var founduname=0;
  966:     var foundpwd=0;
  967:     var foundname=0;
  968:     var foundid=0;
  969:     var foundsec=0;
  970:     var foundemail=0;
  971:     var foundrole=0;
  972:     var founddomain=0;
  973:     var foundinststatus=0;
  974:     var foundcredits=0;
  975:     var tw;
  976:     for (i=0;i<=vf.nfields.value;i++) {
  977:         tw=eval('vf.f'+i+'.selectedIndex');
  978:         if (i==0 && tw!=0) { founduname=1; }
  979:         if (((i>=1) && (i<=5)) && tw!=0 ) { foundname=1; }
  980:         if (i==6 && tw!=0) { foundid=1; }
  981:         if (i==7 && tw!=0) { foundsec=1; }
  982:         if (i==8 && tw!=0) { foundpwd=1; }
  983:         if (i==9 && tw!=0) { foundemail=1; }
  984:         if (i==10 && tw!=0) { foundrole=1; }
  985:         if (i==11 && tw!=0) { founddomain=1; }
  986:         if (i==12 && tw!=0) { foundinstatus=1; }
  987:         if (i==13 && tw!=0) { foundcredits=1; }
  988:     }
  989:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits);
  990: }
  991: 
  992: function flip(vf,tf) {
  993:    var nw=eval('vf.f'+tf+'.selectedIndex');
  994:    var i;
  995:    // picked the all one name field, reset the other name ones to blank
  996:    if (tf==1 && nw!=0) {
  997:       for (i=2;i<=5;i++) {
  998:          eval('vf.f'+i+'.selectedIndex=0;')
  999:       }
 1000:    }
 1001:    //picked one of the piecewise name fields, reset the all in
 1002:    //one field to blank
 1003:    if ((tf>=2) && (tf<=5) && (nw!=0)) {
 1004:       eval('vf.f1.selectedIndex=0;')
 1005:    }
 1006:    $auth_update
 1007: }
 1008: 
 1009: function clearpwd(vf) {
 1010:     var i;
 1011:     if (eval('vf.f8.selectedIndex')!=0) {
 1012:         eval('vf.f8.selectedIndex=0;')
 1013:     }
 1014: }
 1015: ENDPICK
 1016: }
 1017: 
 1018: ###############################################################
 1019: ###############################################################
 1020: sub print_upload_manager_footer {
 1021:     my ($r,$i,$keyfields,$defdom,$today,$halfyear,$context,$permission,$crstype,
 1022:         $showcredits) = @_;
 1023:     my $form = 'document.studentform';
 1024:     my $formname = 'studentform';
 1025:     my ($krbdef,$krbdefdom) =
 1026:         &Apache::loncommon::get_kerberos_defaults($defdom);
 1027:     my %param = ( formname => $form,
 1028:                   kerb_def_dom => $krbdefdom,
 1029:                   kerb_def_auth => $krbdef
 1030:                   );
 1031:     if (exists($env{'form.ipwd_choice'}) &&
 1032:         defined($env{'form.ipwd_choice'}) &&
 1033:         $env{'form.ipwd_choice'} ne '') {
 1034:         $param{'curr_authtype'} = 'int';
 1035:     }
 1036:     my $krbform = &Apache::loncommon::authform_kerberos(%param);
 1037:     my $intform = &Apache::loncommon::authform_internal(%param);
 1038:     my $locform = &Apache::loncommon::authform_local(%param);
 1039:     my $date_table = &date_setting_table(undef,undef,$context,undef,
 1040:                                          $formname,$permission,$crstype);
 1041: 
 1042:     my $Str = "\n".'<div class="LC_left_float">';
 1043:     $Str .= &hidden_input('nfields',$i);
 1044:     $Str .= &hidden_input('keyfields',$keyfields);
 1045: 
 1046:     $Str .= '<h3>'.&mt('Options').'</h3>'
 1047:            .&Apache::lonhtmlcommon::start_pick_box();
 1048: 
 1049:     $Str .= &Apache::lonhtmlcommon::row_title(&mt('Login Type'));
 1050:     if ($context eq 'domain') {
 1051:         $Str .= '<p>'
 1052:                .&mt('Change authentication for existing users in domain "[_1]" to these settings?'
 1053:                    ,$defdom)
 1054:                .'&nbsp;<span class="LC_nobreak"><label>'
 1055:                .'<input type="radio" name="changeauth" value="No" checked="checked" />'
 1056:                .&mt('No').'</label>'
 1057:                .'&nbsp;&nbsp;<label>'
 1058:                .'<input type="radio" name="changeauth" value="Yes" />'
 1059:                .&mt('Yes').'</label>'
 1060:                .'</span></p>'; 
 1061:     } else {
 1062:         $Str .= '<p class="LC_info">'."\n".
 1063:             &mt('This will not take effect if the user already exists.').
 1064:             &Apache::loncommon::help_open_topic('Auth_Options').
 1065:             "</p>\n";
 1066:     }
 1067:     $Str .= &set_login($defdom,$krbform,$intform,$locform);
 1068: 
 1069:     my ($home_server_pick,$numlib) =
 1070:         &Apache::loncommon::home_server_form_item($defdom,'lcserver',
 1071:                                                   'default','hide');
 1072:     if ($numlib > 1) {
 1073:         $Str .= &Apache::lonhtmlcommon::row_closure()
 1074:                .&Apache::lonhtmlcommon::row_title(
 1075:                     &mt('LON-CAPA Home Server for New Users'))
 1076:                .&mt('LON-CAPA domain: [_1] with home server:','"'.$defdom.'"')
 1077:                .$home_server_pick
 1078:                .&Apache::lonhtmlcommon::row_closure();
 1079:     } else {
 1080:         $Str .= $home_server_pick.
 1081:                 &Apache::lonhtmlcommon::row_closure();
 1082:     }
 1083: 
 1084:     $Str .= &Apache::lonhtmlcommon::row_title(&mt('Default domain'))
 1085:            .&Apache::loncommon::select_dom_form($defdom,'defaultdomain',undef,1)
 1086:            .&Apache::lonhtmlcommon::row_closure();
 1087: 
 1088:     $Str .= &Apache::lonhtmlcommon::row_title(&mt('Starting and Ending Dates'))
 1089:            ."<p>\n".$date_table."</p>\n"
 1090:            .&Apache::lonhtmlcommon::row_closure();
 1091: 
 1092:     if ($context eq 'domain') {
 1093:         $Str .= &Apache::lonhtmlcommon::row_title(
 1094:                     &mt('Settings for assigning roles'))
 1095:                .&mt('Pick the action to take on roles for these users:').'<br />'
 1096:                .'<span class="LC_nobreak"><label>'
 1097:                .'<input type="radio" name="roleaction" value="norole" checked="checked" />'
 1098:                .'&nbsp;'.&mt('No role changes').'</label>'
 1099:                .'&nbsp;&nbsp;&nbsp;<label>'
 1100:                .'<input type="radio" name="roleaction" value="domain" />'
 1101:                .'&nbsp;'.&mt('Add a domain role').'</label>'
 1102:                .'&nbsp;&nbsp;&nbsp;<label>'
 1103:                .'<input type="radio" name="roleaction" value="course" />'
 1104:                .'&nbsp;'.&mt('Add a course/community role').'</label>'
 1105:                .'</span>';
 1106:     } elsif ($context eq 'author') {
 1107:         $Str .= &Apache::lonhtmlcommon::row_title(
 1108:                     &mt('Default role'))
 1109:                .&mt('Choose the role to assign to users without a value specified in the uploaded file.')
 1110:     } elsif ($context eq 'course') {
 1111:         if ($showcredits) {
 1112:             $Str .= &Apache::lonhtmlcommon::row_title(
 1113:                     &mt('Default role, section and credits'))
 1114:                    .&mt('Choose the role and/or section(s) and/or credits to assign to users without values specified in the uploaded file.');
 1115:         } else { 
 1116:             $Str .= &Apache::lonhtmlcommon::row_title(
 1117:                     &mt('Default role and section'))
 1118:                    .&mt('Choose the role and/or section(s) to assign to users without values specified in the uploaded file.');
 1119:         }
 1120:     } else {
 1121:         $Str .= &Apache::lonhtmlcommon::row_title(
 1122:                     &mt('Default role and/or section(s)'))
 1123:                .&mt('Role and/or section(s) for users without values specified in the uploaded file.');
 1124:     }
 1125:     if (($context eq 'domain') || ($context eq 'author')) {
 1126:         $Str .= '<br />';
 1127:         my ($options,$cb_script,$coursepick) = 
 1128:             &default_role_selector($context,1,'',$showcredits);
 1129:         if ($context eq 'domain') {
 1130:             $Str .= '<p>'
 1131:                    .'<b>'.&mt('Domain Level').'</b><br />'
 1132:                    .$options
 1133:                    .'</p><p>'
 1134:                    .'<b>'.&mt('Course Level').'</b>'
 1135:                    .'</p>'
 1136:                    .$cb_script.$coursepick
 1137:                    .&Apache::lonhtmlcommon::row_closure();
 1138:         } elsif ($context eq 'author') {
 1139:             $Str .= $options
 1140:                    .&Apache::lonhtmlcommon::row_closure(1); # last row in pick_box
 1141:         }
 1142:     } else {
 1143:         my ($cnum,$cdom) = &get_course_identity();
 1144:         my $rowtitle = &mt('section');
 1145:         my $defaultcredits;
 1146:         if ($showcredits) {
 1147:             $defaultcredits = &get_defaultcredits();
 1148:         }
 1149:         my $secbox = &section_picker($cdom,$cnum,'Any',$rowtitle,$permission,
 1150:                                      $context,'upload',$crstype,$showcredits,
 1151:                                      $defaultcredits);
 1152:         $Str .= $secbox
 1153:                .&Apache::lonhtmlcommon::row_closure();
 1154:         my %lt;
 1155:         if ($crstype eq 'Community') {
 1156:             %lt = &Apache::lonlocal::texthash (
 1157:                     disp => 'Display members with current/future access who are not in the uploaded file',
 1158:                     stus => 'Members selected from this list can be dropped.'
 1159:             );
 1160:         } else {
 1161:             %lt = &Apache::lonlocal::texthash (
 1162:                     disp => 'Display students with current/future access who are not in the uploaded file',
 1163:                     stus => 'Students selected from this list can be dropped.'
 1164:             );
 1165:         }
 1166:         $Str .= &Apache::lonhtmlcommon::row_title(&mt('Full Update'))
 1167:                .'<label><input type="checkbox" name="fullup" value="yes" />'
 1168:                .' '.$lt{'disp'}
 1169:                .'</label><br />'
 1170:                .$lt{'stus'}
 1171:                .&Apache::lonhtmlcommon::row_closure();
 1172:     }
 1173:     if ($context eq 'course' || $context eq 'domain') {
 1174:         $Str .= &Apache::lonhtmlcommon::row_title(&mt('Student/Employee ID'))
 1175:                .&forceid_change($context)
 1176:                .&Apache::lonhtmlcommon::row_closure(1); # last row in pick_box
 1177:     }
 1178: 
 1179:     $Str .= &Apache::lonhtmlcommon::end_pick_box();
 1180:     $Str .= '</div>';
 1181: 
 1182:     # Footer
 1183:     $Str .= '<div class="LC_clear_float_footer">'
 1184:            .'<hr />';
 1185:     if ($context eq 'course') {
 1186:         $Str .= '<p class="LC_info">'
 1187:                .&mt('Note: This operation may be time consuming when adding several users.')
 1188:                .'</p>';
 1189:     }
 1190:     $Str .= '<p><input type="button"'
 1191:            .' onclick="javascript:verify(this.form,this.form.csec)"'
 1192:            .' value="'.&mt('Update Users').'" />'
 1193:            .'</p>'."\n"
 1194:            .'</div>';
 1195:     $r->print($Str);
 1196:     return;
 1197: }
 1198: 
 1199: sub get_defaultcredits {
 1200:     my ($cdom,$cnum) = @_;
 1201:      
 1202:     if ($cdom eq '' || $cnum eq '') {
 1203:         return unless ($env{'request.course.id'});
 1204:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1205:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1206:     }
 1207:     return unless(($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)); 
 1208:     my ($defaultcredits,$domdefcredits);
 1209:     my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 1210:     if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'} || $domdefaults{'textbookcredits'}) {
 1211:         my $instcode = $env{'course.'.$cdom.'_'.$cnum.'.internal.coursecode'};
 1212:         if ($instcode) {
 1213:             $domdefcredits = $domdefaults{'officialcredits'};
 1214:         } elsif ($env{'course.'.$cdom.'_'.$cnum.'.internal.textbook'}) {
 1215:             $domdefcredits = $domdefaults{'textbookcredits'};
 1216:         } else {
 1217:             $domdefcredits = $domdefaults{'unofficialcredits'};
 1218:         }
 1219:     } else {
 1220:         return;
 1221:     }
 1222: 
 1223:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
 1224:         $defaultcredits = $env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'};
 1225:     } elsif (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'})) {
 1226:         $defaultcredits = $env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'};
 1227:     } else {
 1228:         my %crsinfo =
 1229:             &Apache::lonnet::coursedescription("$cdom/$cnum",{'one_time' => 1});
 1230:         $defaultcredits = $crsinfo{'internal.defaultcredits'};
 1231:     }
 1232:     if ($defaultcredits eq '') {
 1233:         $defaultcredits = $domdefcredits;
 1234:     }
 1235:     return $defaultcredits;
 1236: }
 1237: 
 1238: sub forceid_change {
 1239:     my ($context) = @_;
 1240:     my $output = 
 1241:         '<label><input type="checkbox" name="forceid" value="yes" />'
 1242:        .&mt('Force change of existing ID')
 1243:        .'</label>'.&Apache::loncommon::help_open_topic('ForceIDChange')."\n";
 1244:     if ($context eq 'domain') {
 1245:         $output .= 
 1246:             '<br />'
 1247:            .'<label><input type="checkbox" name="recurseid" value="yes" />'
 1248:            .&mt("Update ID in user's course(s).").'</label>'."\n";
 1249:     }
 1250:     return $output;
 1251: }
 1252: 
 1253: ###############################################################
 1254: ###############################################################
 1255: sub print_upload_manager_form {
 1256:     my ($r,$context,$permission,$crstype,$showcredits) = @_;
 1257:     my $firstLine;
 1258:     my $datatoken;
 1259:     if (!$env{'form.datatoken'}) {
 1260:         $datatoken=&Apache::loncommon::upfile_store($r);
 1261:     } else {
 1262:         $datatoken=&Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 1263:         if ($datatoken ne '') {
 1264:             &Apache::loncommon::load_tmp_file($r,$datatoken);
 1265:         }
 1266:     }
 1267:     if ($datatoken eq '') {
 1268:         $r->print('<p class="LC_error">'.&mt('Error').': '.
 1269:                   &mt('Invalid datatoken').'</p>');
 1270:         return 'missingdata';
 1271:     }
 1272:     my @records=&Apache::loncommon::upfile_record_sep();
 1273:     if($env{'form.noFirstLine'}){
 1274:         $firstLine=shift(@records);
 1275:     }
 1276:     my $total=$#records;
 1277:     my $distotal=$total+1;
 1278:     my $today=time;
 1279:     my $halfyear=$today+15552000;
 1280:     #
 1281:     # Restore memorized settings
 1282:     my $col_setting_names =  { 'username_choice' => 'scalar', # column settings
 1283:                                'names_choice' => 'scalar',
 1284:                                'fname_choice' => 'scalar',
 1285:                                'mname_choice' => 'scalar',
 1286:                                'lname_choice' => 'scalar',
 1287:                                'gen_choice' => 'scalar',
 1288:                                'id_choice' => 'scalar',
 1289:                                'sec_choice' => 'scalar',
 1290:                                'ipwd_choice' => 'scalar',
 1291:                                'email_choice' => 'scalar',
 1292:                                'role_choice' => 'scalar',
 1293:                                'domain_choice' => 'scalar',
 1294:                                'inststatus_choice' => 'scalar',
 1295:                              };
 1296:     if ($showcredits) {
 1297:         $col_setting_names->{'credits_choice'} = 'scalar';
 1298:     }
 1299:     if ($context eq 'course') {
 1300:         &Apache::loncommon::restore_course_settings('enrollment_upload',
 1301:                                                     $col_setting_names);
 1302:     } else {
 1303:         &Apache::loncommon::restore_settings($context,'user_upload',
 1304:                                              $col_setting_names);
 1305:     }
 1306:     my $defdom = $env{'request.role.domain'};
 1307:     #
 1308:     # Determine kerberos parameters as appropriate
 1309:     my ($krbdef,$krbdefdom) =
 1310:         &Apache::loncommon::get_kerberos_defaults($defdom);
 1311:     #
 1312:     my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($defdom);
 1313:     &print_upload_manager_header($r,$datatoken,$distotal,$krbdefdom,$context,
 1314:                                  $permission,$crstype,\%can_assign);
 1315:     my $i;
 1316:     my $keyfields;
 1317:     if ($total>=0) {
 1318:         my @field=
 1319:             (['username',&mt('Username'),     $env{'form.username_choice'}],
 1320:              ['names',&mt('Last Name, First Names'),$env{'form.names_choice'}],
 1321:              ['fname',&mt('First Name'),      $env{'form.fname_choice'}],
 1322:              ['mname',&mt('Middle Names/Initials'),$env{'form.mname_choice'}],
 1323:              ['lname',&mt('Last Name'),       $env{'form.lname_choice'}],
 1324:              ['gen',  &mt('Generation'),      $env{'form.gen_choice'}],
 1325:              ['id',   &mt('Student/Employee ID'),$env{'form.id_choice'}],
 1326:              ['sec',  &mt('Section'),          $env{'form.sec_choice'}],
 1327:              ['ipwd', &mt('Initial Password'),$env{'form.ipwd_choice'}],
 1328:              ['email',&mt('E-mail Address'),   $env{'form.email_choice'}],
 1329:              ['role',&mt('Role'),             $env{'form.role_choice'}],
 1330:              ['domain',&mt('Domain'),         $env{'form.domain_choice'}],
 1331:              ['inststatus',&mt('Affiliation'), $env{'form.inststatus_choice'}]);
 1332:         if ($showcredits) {     
 1333:             push(@field,
 1334:                  ['credits',&mt('Student Credits'), $env{'form.credits_choice'}]);
 1335:         }
 1336:         if ($env{'form.upfile_associate'} eq 'reverse') {
 1337:             &Apache::loncommon::csv_print_samples($r,\@records);
 1338:             $i=&Apache::loncommon::csv_print_select_table($r,\@records,
 1339:                                                           \@field);
 1340:             foreach (@field) {
 1341:                 $keyfields.=$_->[0].',';
 1342:             }
 1343:             chop($keyfields);
 1344:         } else {
 1345:             unshift(@field,['none','']);
 1346:             $i=&Apache::loncommon::csv_samples_select_table($r,\@records,
 1347:                                                             \@field);
 1348:             my %sone=&Apache::loncommon::record_sep($records[0]);
 1349:             $keyfields=join(',',sort(keys(%sone)));
 1350:         }
 1351:     }
 1352:     &print_upload_manager_footer($r,$i,$keyfields,$defdom,$today,$halfyear,
 1353:                                  $context,$permission,$crstype,$showcredits);
 1354:     return 'ok';
 1355: }
 1356: 
 1357: sub setup_date_selectors {
 1358:     my ($starttime,$endtime,$mode,$nolink,$formname) = @_;
 1359:     if ($formname eq '') {
 1360:         $formname = 'studentform';
 1361:     }
 1362:     if (! defined($starttime)) {
 1363:         $starttime = time;
 1364:         unless ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
 1365:             if (exists($env{'course.'.$env{'request.course.id'}.
 1366:                             '.default_enrollment_start_date'})) {
 1367:                 $starttime = $env{'course.'.$env{'request.course.id'}.
 1368:                                   '.default_enrollment_start_date'};
 1369:             }
 1370:         }
 1371:     }
 1372:     if (! defined($endtime)) {
 1373:         $endtime = time+(6*30*24*60*60); # 6 months from now, approx
 1374:         unless ($mode eq 'createcourse') {
 1375:             if (exists($env{'course.'.$env{'request.course.id'}.
 1376:                             '.default_enrollment_end_date'})) {
 1377:                 $endtime = $env{'course.'.$env{'request.course.id'}.
 1378:                                 '.default_enrollment_end_date'};
 1379:             }
 1380:         }
 1381:     }
 1382: 
 1383:     my $startdateform = 
 1384:         &Apache::lonhtmlcommon::date_setter($formname,'startdate',$starttime,
 1385:             undef,undef,undef,undef,undef,undef,undef,$nolink);
 1386: 
 1387:     my $enddateform = 
 1388:         &Apache::lonhtmlcommon::date_setter($formname,'enddate',$endtime,
 1389:             undef,undef,undef,undef,undef,undef,undef,$nolink);
 1390: 
 1391:     if ($mode eq 'create_enrolldates') {
 1392:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
 1393:                                                             'startenroll',
 1394:                                                             $starttime);
 1395:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
 1396:                                                           'endenroll',
 1397:                                                           $endtime);
 1398:     }
 1399:     if ($mode eq 'create_defaultdates') {
 1400:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
 1401:                                                             'startaccess',
 1402:                                                             $starttime);
 1403:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
 1404:                                                           'endaccess',
 1405:                                                           $endtime);
 1406:     }
 1407:     return ($startdateform,$enddateform);
 1408: }
 1409: 
 1410: 
 1411: sub get_dates_from_form {
 1412:     my ($startname,$endname) = @_;
 1413:     if ($startname eq '') {
 1414:         $startname = 'startdate';
 1415:     }
 1416:     if ($endname eq '') {
 1417:         $endname = 'enddate';
 1418:     }
 1419:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form($startname);
 1420:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form($endname);
 1421:     if ($env{'form.no_end_date'}) {
 1422:         $enddate = 0;
 1423:     }
 1424:     return ($startdate,$enddate);
 1425: }
 1426: 
 1427: sub date_setting_table {
 1428:     my ($starttime,$endtime,$mode,$bulkaction,$formname,$permission,$crstype) = @_;
 1429:     my $nolink;
 1430:     if ($bulkaction) {
 1431:         $nolink = 1;
 1432:     }
 1433:     my ($startform,$endform) = 
 1434:         &setup_date_selectors($starttime,$endtime,$mode,$nolink,$formname);
 1435:     my $dateDefault;
 1436:     if ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
 1437:         $dateDefault = '&nbsp;';
 1438:     } elsif ($mode ne 'author' && $mode ne 'domain') {
 1439:         if (($bulkaction eq 'reenable') || 
 1440:             ($bulkaction eq 'activate') || 
 1441:             ($bulkaction eq 'chgdates') ||
 1442:             ($env{'form.action'} eq 'upload')) {
 1443:             if ($env{'request.course.sec'} eq '') {
 1444:                 $dateDefault = '<span class="LC_nobreak">'.
 1445:                     '<label><input type="checkbox" name="makedatesdefault" value="1" /> ';
 1446:                 if ($crstype eq 'Community') {
 1447:                     $dateDefault .= &mt("make these dates the default access dates for future community enrollment");
 1448:                 } else {
 1449:                     $dateDefault .= &mt("make these dates the default access dates for future course enrollment");
 1450:                 }
 1451:                 $dateDefault .= '</label></span>';
 1452:             }
 1453:         }
 1454:     }
 1455:     my $perpetual = '<span class="LC_nobreak"><label><input type="checkbox" name="no_end_date"';
 1456:     if (defined($endtime) && $endtime == 0) {
 1457:         $perpetual .= ' checked="checked"';
 1458:     }
 1459:     $perpetual.= ' /> '.&mt('no ending date').'</label></span>';
 1460:     if ($mode eq 'create_enrolldates') {
 1461:         $perpetual = '&nbsp;';
 1462:     }
 1463:     my $result = &Apache::lonhtmlcommon::start_pick_box()."\n";
 1464:     $result .= &Apache::lonhtmlcommon::row_title(&mt('Starting Date'),
 1465:                                                      'LC_oddrow_value')."\n".
 1466:                $startform."\n".
 1467:                &Apache::lonhtmlcommon::row_closure(1).
 1468:                &Apache::lonhtmlcommon::row_title(&mt('Ending Date'), 
 1469:                                                      'LC_oddrow_value')."\n".
 1470:                $endform.'&nbsp;'.$perpetual.
 1471:                &Apache::lonhtmlcommon::row_closure(1).
 1472:                &Apache::lonhtmlcommon::end_pick_box();
 1473:     if ($dateDefault) {
 1474:         $result .=  $dateDefault.'<br />'."\n";
 1475:     }
 1476:     return $result;
 1477: }
 1478: 
 1479: sub make_dates_default {
 1480:     my ($startdate,$enddate,$context,$crstype) = @_;
 1481:     my $result = '';
 1482:     if ($context eq 'course') {
 1483:         my ($cnum,$cdom) = &get_course_identity();
 1484:         my $put_result = &Apache::lonnet::put('environment',
 1485:                 {'default_enrollment_start_date'=>$startdate,
 1486:                  'default_enrollment_end_date'  =>$enddate},$cdom,$cnum);
 1487:         if ($put_result eq 'ok') {
 1488:             if ($crstype eq 'Community') {
 1489:                 $result .= &mt('Set default start and end access dates for community.');
 1490:             } else {
 1491:                 $result .= &mt('Set default start and end access dates for course.');
 1492:             }
 1493:             $result .= '<br />'."\n";
 1494:             #
 1495:             # Refresh the course environment
 1496:             &Apache::lonnet::coursedescription($env{'request.course.id'},
 1497:                                                {'freshen_cache' => 1});
 1498:         } else {
 1499:             if ($crstype eq 'Community') {
 1500:                 $result .= &mt('Unable to set default access dates for community');
 1501:             } else {
 1502:                 $result .= &mt('Unable to set default access dates for course');
 1503:             }
 1504:             $result .= ':'.$put_result.'<br />';
 1505:         }
 1506:     }
 1507:     return $result;
 1508: }
 1509: 
 1510: sub default_role_selector {
 1511:     my ($context,$checkpriv,$crstype,$showcredits) = @_;
 1512:     my %customroles;
 1513:     my ($options,$coursepick,$cb_jscript);
 1514:     if ($context ne 'author') {
 1515:         %customroles = &my_custom_roles($crstype);
 1516:     }
 1517: 
 1518:     my %lt=&Apache::lonlocal::texthash(
 1519:                     'rol'  => "Role",
 1520:                     'grs'  => "Section",
 1521:                     'exs'  => "Existing sections",
 1522:                     'new'  => "New section",
 1523:                     'crd'  => "Credits",
 1524:                   );
 1525:     $options = '<select name="defaultrole">'."\n".
 1526:                ' <option value="">'.&mt('Please select').'</option>'."\n"; 
 1527:     if ($context eq 'course') {
 1528:         $options .= &default_course_roles($context,$checkpriv,$crstype,%customroles);
 1529:     } elsif ($context eq 'author') {
 1530:         my @roles = &construction_space_roles($checkpriv);
 1531:         foreach my $role (@roles) {
 1532:            my $plrole=&Apache::lonnet::plaintext($role);
 1533:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>'."\n";
 1534:         }
 1535:     } elsif ($context eq 'domain') {
 1536:         my @roles = &domain_roles($checkpriv);
 1537:         foreach my $role (@roles) {
 1538:            my $plrole=&Apache::lonnet::plaintext($role);
 1539:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>';
 1540:         }
 1541:         my $courseform = &Apache::loncommon::selectcourse_link
 1542:             ('studentform','dccourse','dcdomain','coursedesc',"$env{'request.role.domain'}",undef,'Course/Community');
 1543:         my ($credit_elem,$creditsinput);
 1544:         if ($showcredits) {
 1545:             $credit_elem = 'credits';
 1546:             $creditsinput = '<td><input type="text" name="credits" value="" /></td>';
 1547:         }
 1548:         $cb_jscript = 
 1549:             &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'},'currsec','studentform','courserole','Course/Community',$credit_elem);
 1550:         $coursepick = &Apache::loncommon::start_data_table().
 1551:                       &Apache::loncommon::start_data_table_header_row().
 1552:                       '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th>'.
 1553:                       '<th>'.$lt{'grs'}.'</th>'.
 1554:                       '<th>'.$lt{'crd'}.'</th>'.
 1555:                       &Apache::loncommon::end_data_table_header_row().
 1556:                       &Apache::loncommon::start_data_table_row()."\n".
 1557:                       '<td><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'studentform','dccourse','dcdomain','coursedesc','','','','crstype'".')" /></td>'."\n".
 1558:                       '<td><select name="courserole">'."\n".
 1559:                       &default_course_roles($context,$checkpriv,'Course',%customroles)."\n".
 1560:                       '</select></td><td>'.
 1561:                       '<table class="LC_createuser">'.
 1562:                       '<tr class="LC_section_row"><td valign="top">'.
 1563:                       $lt{'exs'}.'<br /><select name="currsec">'.
 1564:                       ' <option value="">&lt;--'.&mt('Pick course first').
 1565:                       '</select></td>'.
 1566:                       '<td>&nbsp;&nbsp;</td>'.
 1567:                       '<td valign="top">'.$lt{'new'}.'<br />'.
 1568:                       '<input type="text" name="newsec" value="" size="5" />'.
 1569:                       '<input type="hidden" name="groups" value="" />'.
 1570:                       '<input type="hidden" name="sections" value="" />'.
 1571:                       '<input type="hidden" name="origdom" value="'.
 1572:                       $env{'request.role.domain'}.'" />'.
 1573:                       '<input type="hidden" name="dccourse" value="" />'.
 1574:                       '<input type="hidden" name="dcdomain" value="" />'.
 1575:                       '<input type="hidden" name="crstype" value="" />'.
 1576:                       '</td></tr></table></td>'.$creditsinput.
 1577:                       &Apache::loncommon::end_data_table_row().
 1578:                       &Apache::loncommon::end_data_table()."\n";
 1579:     }
 1580:     $options .= '</select>';
 1581:     return ($options,$cb_jscript,$coursepick);
 1582: }
 1583: 
 1584: sub default_course_roles {
 1585:     my ($context,$checkpriv,$crstype,%customroles) = @_;
 1586:     my $output;
 1587:     my $custom = 1;
 1588:     my @roles = &course_roles($context,$checkpriv,$custom,lc($crstype));
 1589:     foreach my $role (@roles) {
 1590:         if ($role ne 'cr') {
 1591:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 1592:             $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
 1593:         }
 1594:     }
 1595:     if (keys(%customroles) > 0) {
 1596:         if (grep(/^cr$/,@roles)) {
 1597:             foreach my $cust (sort(keys(%customroles))) {
 1598:                 my $custrole='cr_'.$env{'user.domain'}.
 1599:                              '_'.$env{'user.name'}.'_'.$cust;
 1600:                 $output .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 1601:             }
 1602:         }
 1603:     }
 1604:     return $output;
 1605: }
 1606: 
 1607: sub construction_space_roles {
 1608:     my ($checkpriv) = @_;
 1609:     my @allroles = &roles_by_context('author');
 1610:     my @roles;
 1611:     if ($checkpriv) {
 1612:         foreach my $role (@allroles) {
 1613:             if (&Apache::lonnet::allowed('c'.$role,$env{'user.domain'}.'/'.$env{'user.name'})) { 
 1614:                 push(@roles,$role); 
 1615:             }
 1616:         }
 1617:         return @roles;
 1618:     } else {
 1619:         return @allroles;
 1620:     }
 1621: }
 1622: 
 1623: sub domain_roles {
 1624:     my ($checkpriv) = @_;
 1625:     my @allroles = &roles_by_context('domain');
 1626:     my @roles;
 1627:     if ($checkpriv) {
 1628:         foreach my $role (@allroles) {
 1629:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
 1630:                 push(@roles,$role);
 1631:             }
 1632:         }
 1633:         return @roles;
 1634:     } else {
 1635:         return @allroles;
 1636:     }
 1637: }
 1638: 
 1639: sub course_roles {
 1640:     my ($context,$checkpriv,$custom,$roletype) = @_;
 1641:     my $crstype;
 1642:     if ($roletype eq 'community') {
 1643:         $crstype = 'Community' ;
 1644:     } else {
 1645:         $crstype = 'Course';
 1646:     }
 1647:     my @allroles = &roles_by_context('course',$custom,$crstype);
 1648:     my @roles;
 1649:     if ($context eq 'domain') {
 1650:         @roles = @allroles;
 1651:     } elsif ($context eq 'course') {
 1652:         if ($env{'request.course.id'}) {
 1653:             if ($checkpriv) { 
 1654:                 foreach my $role (@allroles) {
 1655:                     if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
 1656:                         push(@roles,$role);
 1657:                     } else {
 1658:                         if ((($role ne 'cc') && ($role ne 'co')) && ($env{'request.course.sec'} ne '')) {
 1659:                             if (&Apache::lonnet::allowed('c'.$role,
 1660:                                              $env{'request.course.id'}.'/'.
 1661:                                              $env{'request.course.sec'})) {
 1662:                                 push(@roles,$role);
 1663:                             }
 1664:                         }
 1665:                     }
 1666:                 }
 1667:             } else {
 1668:                 @roles = @allroles;
 1669:             }
 1670:         }
 1671:     }
 1672:     return @roles;
 1673: }
 1674: 
 1675: sub curr_role_permissions {
 1676:     my ($context,$setting,$checkpriv,$type) = @_; 
 1677:     my $custom = 1;
 1678:     my @roles;
 1679:     if ($context eq 'author') {
 1680:         @roles = &construction_space_roles($checkpriv);
 1681:     } elsif ($context eq 'domain') {
 1682:         if ($setting eq 'course') {
 1683:             @roles = &course_roles($context,$checkpriv,$custom,$type); 
 1684:         } else {
 1685:             @roles = &domain_roles($checkpriv);
 1686:         }
 1687:     } elsif ($context eq 'course') {
 1688:         @roles = &course_roles($context,$checkpriv,$custom,$type);
 1689:     }
 1690:     return @roles;
 1691: }
 1692: 
 1693: # ======================================================= Existing Custom Roles
 1694: 
 1695: sub my_custom_roles {
 1696:     my ($crstype,$udom,$uname) = @_;
 1697:     my %returnhash=();
 1698:     my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
 1699:     my %rolehash=&Apache::lonnet::dump('roles',$udom,$uname);
 1700:     foreach my $key (keys(%rolehash)) {
 1701:         if ($key=~/^rolesdef\_(\w+)$/) {
 1702:             if ($crstype eq 'Community') {
 1703:                 next if ($rolehash{$key} =~ /bre\&S/); 
 1704:             }
 1705:             $returnhash{$1}=$1;
 1706:         }
 1707:     }
 1708:     return %returnhash;
 1709: }
 1710: 
 1711: sub print_userlist {
 1712:     my ($r,$mode,$permission,$context,$formname,$totcodes,$codetitles,
 1713:         $idlist,$idlist_titles,$showcredits) = @_;
 1714:     my $format = $env{'form.output'};
 1715:     if (! exists($env{'form.sortby'})) {
 1716:         $env{'form.sortby'} = 'username';
 1717:     }
 1718:     if ($env{'form.Status'} !~ /^(Any|Expired|Active|Future)$/) {
 1719:         $env{'form.Status'} = 'Active';
 1720:     }
 1721:     my $onchange = "javascript:updateCols('Status');";
 1722:     my $status_select = &Apache::lonhtmlcommon::StatusOptions
 1723:         ($env{'form.Status'},undef,undef,$onchange);
 1724: 
 1725:     if ($env{'form.showrole'} eq '') {
 1726:         if ($context eq 'course') {
 1727:             $env{'form.showrole'} = 'st';
 1728:         } else {
 1729:             $env{'form.showrole'} = 'Any';            
 1730:         }
 1731:     }
 1732:     if (! defined($env{'form.output'}) ||
 1733:         $env{'form.output'} !~ /^(csv|excel|html)$/ ) {
 1734:         $env{'form.output'} = 'html';
 1735:     }
 1736: 
 1737:     my @statuses;
 1738:     if ($env{'form.Status'} eq 'Any') {
 1739:         @statuses = ('previous','active','future');
 1740:     } elsif ($env{'form.Status'} eq 'Expired') {
 1741:         @statuses = ('previous');
 1742:     } elsif ($env{'form.Status'} eq 'Active') {
 1743:         @statuses = ('active');
 1744:     } elsif ($env{'form.Status'} eq 'Future') {
 1745:         @statuses = ('future');
 1746:     }
 1747: 
 1748:     # Interface output
 1749:     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n".
 1750:               '<input type="hidden" name="action" value="'.
 1751:               $env{'form.action'}.'" />');
 1752:     $r->print('<div>'."\n");
 1753:     if ($env{'form.action'} ne 'modifystudent') {
 1754:         my %lt=&Apache::lonlocal::texthash('csv' => "CSV",
 1755:                                            'excel' => "Excel",
 1756:                                            'html'  => 'HTML');
 1757:         my $output_selector = '<select size="1" name="output" onchange="javascript:updateCols('."'output'".');" >';
 1758:         foreach my $outputformat ('html','csv','excel') {
 1759:             my $option = '<option value="'.$outputformat.'"';
 1760:             if ($outputformat eq $env{'form.output'}) {
 1761:                 $option .= ' selected="selected"';
 1762:             }
 1763:             $option .='>'.$lt{$outputformat}.'</option>';
 1764:             $output_selector .= "\n".$option;
 1765:         }
 1766:         $output_selector .= '</select>';
 1767:         $r->print('<span class="LC_nobreak">'
 1768:                  .&mt('Output Format: [_1]',$output_selector)
 1769:                  .'</span>'.('&nbsp;'x3));
 1770:     }
 1771:     $r->print('<span class="LC_nobreak">'
 1772:              .&mt('User Status: [_1]',$status_select)
 1773:              .'</span>'.('&nbsp;'x3)."\n");
 1774:     my $roleselected = '';
 1775:     if ($env{'form.showrole'} eq 'Any') {
 1776:        $roleselected = ' selected="selected"'; 
 1777:     }
 1778:     my ($cnum,$cdom);
 1779:     $r->print(&role_filter($context));
 1780:     if ($context eq 'course') {
 1781:         ($cnum,$cdom) = &get_course_identity();
 1782:         $r->print(&section_group_filter($cnum,$cdom));
 1783:     }
 1784:     $r->print('</div><div class="LC_left_float">'.
 1785:               &column_checkboxes($context,$mode,$formname,$showcredits).
 1786:               '</div>');
 1787:     if ($env{'form.phase'} eq '') {
 1788:         $r->print('<br clear="all" />'.
 1789:                   &list_submit_button(&mt('Display List of Users'))."\n".
 1790:                   '<input type="hidden" name="phase" value="" /></form>');
 1791:         return;
 1792:     }
 1793:     if (!(($context eq 'domain') && 
 1794:           (($env{'form.roletype'} eq 'course') || ($env{'form.roletype'} eq 'community')))) {
 1795:         $r->print('<br clear="all" />'.
 1796:                   &list_submit_button(&mt('Update Display'))."\n");
 1797:     }
 1798: 
 1799:     my @cols = &infocolumns($context,$mode,$showcredits);  
 1800:     if (!@cols) {
 1801:          $r->print('<hr style="clear:both;" /><span class="LC_warning">'.
 1802:                    &mt('No user information selected for display.').'</span>'.
 1803:                    '<input type="hidden" name="phase" value="display" /></form>'."\n");
 1804:          return;
 1805:     }
 1806:     my ($indexhash,$keylist) = &make_keylist_array();
 1807:     my (%userlist,%userinfo,$clearcoursepick,$needauthorquota,$needauthorusage);
 1808:     if (($context eq 'domain') && 
 1809:         ($env{'form.roletype'} eq 'course') || 
 1810:         ($env{'form.roletype'} eq 'community')) {
 1811:         my ($crstype,$numcodes,$title,$warning);
 1812:         if ($env{'form.roletype'} eq 'course') {
 1813:             $crstype = 'Course';
 1814:             $numcodes = $totcodes;
 1815:             $title = &mt('Select Courses');
 1816:             $warning = &mt('Warning: data retrieval for multiple courses can take considerable time, as this operation is not currently optimized.');
 1817:         } elsif ($env{'form.roletype'} eq 'community') {
 1818:             $crstype = 'Community';
 1819:             $numcodes = 0;
 1820:             $title = &mt('Select Communities');
 1821:             $warning = &mt('Warning: data retrieval for multiple communities can take considerable time, as this operation is not currently optimized.');
 1822:         }
 1823:         my @standardnames = &Apache::loncommon::get_standard_codeitems();
 1824:         my $courseform =
 1825:             &Apache::lonhtmlcommon::course_selection($formname,$numcodes,
 1826:                             $codetitles,$idlist,$idlist_titles,$crstype,
 1827:                             \@standardnames);
 1828:         $r->print('<div class="LC_left_float">'.
 1829:                   '<fieldset><legend>'.$title.'</legend>'."\n".
 1830:                   $courseform."\n".
 1831:                   '</fieldset></div><br clear="all" />'.
 1832:                   '<p><input type="hidden" name="origroletype" value="'.$env{'form.roletype'}.'" />'.
 1833:                   &list_submit_button(&mt('Update Display')).
 1834:                   "\n".'</p><span class="LC_warning">'.$warning.'</span>'."\n");
 1835:         $clearcoursepick = 0;
 1836:         if (($env{'form.origroletype'} ne '') &&
 1837:             ($env{'form.origroletype'} ne $env{'form.roletype'})) {
 1838:             $clearcoursepick = 1;
 1839:         }
 1840:         if (($env{'form.coursepick'}) && (!$clearcoursepick)) {
 1841:             $r->print('<hr />'.&mt('Searching ...').'<br />&nbsp;<br />');
 1842:         }
 1843:     } else {
 1844:         $r->print('<hr style="clear:both;" /><div id="searching">'.&mt('Searching ...').'</div>');
 1845:     }
 1846:     $r->rflush();
 1847:     if ($context eq 'course') {
 1848:         if (($env{'form.showrole'} eq 'st') || ($env{'form.showrole'} eq 'Any')) { 
 1849:             my $classlist = &Apache::loncoursedata::get_classlist();
 1850:             if (ref($classlist) eq 'HASH') {
 1851:                 %userlist = %{$classlist};
 1852:             }
 1853:         }
 1854:         if ($env{'form.showrole'} ne 'st') {
 1855:             my $showroles;
 1856:             if ($env{'form.showrole'} ne 'Any') {
 1857:                 $showroles = [$env{'form.showrole'}];
 1858:             } else {
 1859:                 $showroles = undef;
 1860:             }
 1861:             my $withsec = 1;
 1862:             my $hidepriv = 1;
 1863:             my %advrolehash = &Apache::lonnet::get_my_roles($cnum,$cdom,undef,
 1864:                               \@statuses,$showroles,undef,$withsec,$hidepriv);
 1865:             &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
 1866:                              \%advrolehash,$permission);
 1867:         }
 1868:     } else {
 1869:         my (%cstr_roles,%dom_roles);
 1870:         if ($context eq 'author') {
 1871:             # List co-authors and assistant co-authors
 1872:             my @possroles = &roles_by_context($context);
 1873:             %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 1874:                                               \@statuses,\@possroles);
 1875:             &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
 1876:                              \%cstr_roles,$permission);
 1877:         } elsif ($context eq 'domain') {
 1878:             if ($env{'form.roletype'} eq 'domain') {
 1879:                 if (grep(/^authorusage$/,@cols)) {
 1880:                     $needauthorusage = 1;
 1881:                 }
 1882:                 if (grep(/^authorquota$/,@cols)) {
 1883:                     $needauthorquota = 1;
 1884:                 }
 1885:                 %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'});
 1886:                 foreach my $key (keys(%dom_roles)) {
 1887:                     if (ref($dom_roles{$key}) eq 'HASH') {
 1888:                         &gather_userinfo($context,$format,\%userlist,$indexhash,
 1889:                                          \%userinfo,$dom_roles{$key},$permission);
 1890:                     }
 1891:                 }
 1892:             } elsif ($env{'form.roletype'} eq 'author') {
 1893:                 my %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'},['au']);
 1894:                 my %coauthors;
 1895:                 foreach my $key (keys(%dom_roles)) {
 1896:                     if (ref($dom_roles{$key}) eq 'HASH') {
 1897:                         if ($env{'form.showrole'} eq 'au') {
 1898:                             &gather_userinfo($context,$format,\%userlist,$indexhash,
 1899:                                              \%userinfo,$dom_roles{$key},$permission);
 1900:                         } else {
 1901:                             my @possroles;
 1902:                             if ($env{'form.showrole'} eq 'Any') {
 1903:                                 @possroles = &roles_by_context('author');
 1904:                             } else {
 1905:                                 @possroles = ($env{'form.showrole'}); 
 1906:                             }
 1907:                             foreach my $author (sort(keys(%{$dom_roles{$key}}))) {
 1908:                                 my ($role,$authorname,$authordom) = split(/:/,$author,-1);
 1909:                                 my $extent = '/'.$authordom.'/'.$authorname;
 1910:                                 %{$coauthors{$extent}} =
 1911:                                     &Apache::lonnet::get_my_roles($authorname,
 1912:                                        $authordom,undef,\@statuses,\@possroles);
 1913:                             }
 1914:                             &gather_userinfo($context,$format,\%userlist,
 1915:                                      $indexhash,\%userinfo,\%coauthors,$permission);
 1916:                         }
 1917:                     }
 1918:                 }
 1919:             } elsif (($env{'form.roletype'} eq 'course') ||
 1920:                      ($env{'form.roletype'} eq 'community')) {
 1921:                 if (($env{'form.coursepick'}) && (!$clearcoursepick)) {
 1922:                     my %courses = &process_coursepick();
 1923:                     my %allusers;
 1924:                     my $hidepriv = 1;
 1925:                     foreach my $cid (keys(%courses)) {
 1926:                         my ($cnum,$cdom,$cdesc) = &get_course_identity($cid);
 1927:                         next if ($cnum eq '' || $cdom eq '');
 1928:                         my $custom = 1;
 1929:                         my (@roles,@sections,%access,%users,%userdata,
 1930:                             %statushash);
 1931:                         if ($env{'form.showrole'} eq 'Any') {
 1932:                             @roles = &course_roles($context,undef,$custom,
 1933:                                                    $env{'form.roletype'});
 1934:                         } else {
 1935:                             @roles = ($env{'form.showrole'});
 1936:                         }
 1937:                         foreach my $role (@roles) {
 1938:                             %{$users{$role}} = ();
 1939:                         }
 1940:                         foreach my $type (@statuses) {
 1941:                             $access{$type} = $type;
 1942:                         }
 1943:                         &Apache::loncommon::get_course_users($cdom,$cnum,\%access,\@roles,\@sections,\%users,\%userdata,\%statushash,$hidepriv);
 1944:                         foreach my $user (keys(%userdata)) {
 1945:                             next if (ref($userinfo{$user}) eq 'HASH');
 1946:                             foreach my $item ('fullname','id') {
 1947:                                 $userinfo{$user}{$item} = $userdata{$user}[$indexhash->{$item}];
 1948:                             }
 1949:                         }
 1950:                         foreach my $role (keys(%users)) {
 1951:                             foreach my $user (keys(%{$users{$role}})) {
 1952:                                 my $uniqid = $user.':'.$role;
 1953:                                 $allusers{$uniqid}{$cid} = { desc => $cdesc,
 1954:                                                              secs  => $statushash{$user}{$role},
 1955:                                                            };
 1956:                             }
 1957:                         }
 1958:                     }
 1959:                     &gather_userinfo($context,$format,\%userlist,$indexhash,
 1960:                                      \%userinfo,\%allusers,$permission);
 1961:                 } else {
 1962:                     $r->print('<input type="hidden" name="phase" value="'.
 1963:                               $env{'form.phase'}.'" /></form>');
 1964:                     return;
 1965:                 }
 1966:             }
 1967:         }
 1968:     }
 1969:     if (keys(%userlist) == 0) {
 1970:         my $msg = '';
 1971:         if ($context eq 'author') {
 1972:             $msg = &mt('There are no co-authors to display.');
 1973:         } elsif ($context eq 'domain') {
 1974:             if ($env{'form.roletype'} eq 'domain') {
 1975:                 $msg = &mt('There are no users with domain roles to display.');
 1976:             } elsif ($env{'form.roletype'} eq 'author') {
 1977:                 $msg = &mt('There are no authors or co-authors to display.');
 1978:             } elsif ($env{'form.roletype'} eq 'course') {
 1979:                 $msg = &mt('There are no course users to display');
 1980:             } elsif ($env{'form.roletype'} eq 'community') {
 1981:                 $msg = &mt('There are no community users to display');
 1982:             }
 1983:         } elsif ($context eq 'course') {
 1984:             $r->print(&mt('There are no course users to display.')."\n");
 1985:         }
 1986:         $r->print('<p class="LC_info">'.$msg.'</p>'."\n") if $msg;
 1987:     } else {
 1988:         # Print out the available choices
 1989:         my $usercount;
 1990:         if ($env{'form.action'} eq 'modifystudent') {
 1991:             ($usercount) = &show_users_list($r,$context,'view',$permission,
 1992:                                  $env{'form.Status'},\%userlist,$keylist,'',
 1993:                                  $showcredits);
 1994:         } else {
 1995:             ($usercount) = &show_users_list($r,$context,$env{'form.output'},
 1996:                                $permission,$env{'form.Status'},\%userlist,
 1997:                                $keylist,'',$showcredits,$needauthorquota,$needauthorusage);
 1998:         }
 1999:         if (!$usercount) {
 2000:             $r->print('<br /><span class="LC_info">'
 2001:                      .&mt('There are no users matching the search criteria.')
 2002:                      .'</span>'
 2003:             ); 
 2004:         }
 2005:     }
 2006:     $r->print('<input type="hidden" name="phase" value="'.
 2007:               $env{'form.phase'}.'" /></form>');
 2008:     return;
 2009: }
 2010: 
 2011: sub role_filter {
 2012:     my ($context) = @_;
 2013:     my $output;
 2014:     my $roleselected = '';
 2015:     if ($env{'form.showrole'} eq 'Any') {
 2016:        $roleselected = ' selected="selected"';
 2017:     }
 2018:     my ($role_select);
 2019:     if ($context eq 'domain') {
 2020:         $role_select = &domain_roles_select();
 2021:         $output = '<span class="LC_nobreak">'
 2022:                  .&mt('Role Type: [_1]',$role_select)
 2023:                  .'</span>';
 2024:     } else {
 2025:         $role_select = '<select name="showrole" onchange="javascript:updateCols('."'showrole'".');">'."\n".
 2026:                        '<option value="Any" '.$roleselected.'>'.
 2027:                        &mt('Any role').'</option>';
 2028:         my ($roletype,$crstype);
 2029:         if ($context eq 'course') {
 2030:             $crstype = &Apache::loncommon::course_type();
 2031:             if ($crstype eq 'Community') {
 2032:                 $roletype = 'community';
 2033:             } else {
 2034:                 $roletype = 'course';
 2035:             } 
 2036:         }
 2037:         my @poss_roles = &curr_role_permissions($context,'','',$roletype);
 2038:         foreach my $role (@poss_roles) {
 2039:             $roleselected = '';
 2040:             if ($role eq $env{'form.showrole'}) {
 2041:                 $roleselected = ' selected="selected"';
 2042:             }
 2043:             my $plrole;
 2044:             if ($role eq 'cr') {
 2045:                 $plrole = &mt('Custom role');
 2046:             } else {
 2047:                 $plrole=&Apache::lonnet::plaintext($role,$crstype);
 2048:             }
 2049:             $role_select .= '<option value="'.$role.'"'.$roleselected.'>'.$plrole.'</option>';
 2050:         }
 2051:         $role_select .= '</select>';
 2052:         $output = '<span class="LC_nobreak">'
 2053:                  .&mt('Role: [_1]',$role_select)
 2054:                  .'</span>';
 2055:     }
 2056:     return $output;
 2057: }
 2058: 
 2059: sub section_group_filter {
 2060:     my ($cnum,$cdom) = @_;
 2061:     my @filters;
 2062:     if ($env{'request.course.sec'} eq '') {
 2063:         @filters = ('sec');
 2064:     }
 2065:     push(@filters,'grp');
 2066:     my %name = (
 2067:                  sec => 'secfilter',
 2068:                  grp => 'grpfilter',
 2069:                );
 2070:     my %title = &Apache::lonlocal::texthash (
 2071:                                               sec  => 'Section(s)',
 2072:                                               grp  => 'Group(s)',
 2073:                                               all  => 'all',
 2074:                                               none => 'none',
 2075:                                             );
 2076:     my $output;
 2077:     foreach my $item (@filters) {
 2078:         my ($markup,@options); 
 2079:         if ($env{'form.'.$name{$item}} eq '') {
 2080:             $env{'form.'.$name{$item}} = 'all';
 2081:         }
 2082:         if ($item eq 'sec') {
 2083:             if (($env{'form.showrole'} eq 'cc') || ($env{'form.showrole'} eq 'co')) {
 2084:                 $env{'form.'.$name{$item}} = 'none';
 2085:             }
 2086:             my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 2087:             @options = sort(keys(%sections_count));
 2088:         } elsif ($item eq 'grp') {
 2089:             my %curr_groups = &Apache::longroup::coursegroups();
 2090:             @options = sort(keys(%curr_groups));
 2091:         }
 2092:         if (@options > 0) {
 2093:             my $currsel;
 2094:             $markup = '<select name="'.$name{$item}.'">'."\n";
 2095:             foreach my $option ('all','none',@options) { 
 2096:                 $currsel = '';
 2097:                 if ($env{'form.'.$name{$item}} eq $option) {
 2098:                     $currsel = ' selected="selected"';
 2099:                 }
 2100:                 $markup .= ' <option value="'.$option.'"'.$currsel.'>';
 2101:                 if (($option eq 'all') || ($option eq 'none')) {
 2102:                     $markup .= $title{$option};
 2103:                 } else {
 2104:                     $markup .= $option;
 2105:                 }   
 2106:                 $markup .= '</option>'."\n";
 2107:             }
 2108:             $markup .= '</select>'."\n";
 2109:             $output .= ('&nbsp;'x3).'<span class="LC_nobreak">'
 2110:                       .'<label>'.$title{$item}.': '.$markup.'</label>'
 2111:                       .'</span> ';
 2112:         }
 2113:     }
 2114:     return $output;
 2115: }
 2116: 
 2117: sub infocolumns {
 2118:     my ($context,$mode,$showcredits) = @_;
 2119:     my @cols;
 2120:     if (($mode eq 'pickauthor') || ($mode eq 'autoenroll')) {
 2121:         @cols = &get_cols_array($context,$mode,$showcredits);
 2122:     } else {
 2123:         my @posscols = &get_cols_array($context,$mode,$showcredits);
 2124:         if ($env{'form.phase'} ne '') {
 2125:             my @checkedcols = &Apache::loncommon::get_env_multiple('form.showcol');
 2126:             foreach my $col (@checkedcols) {
 2127:                 if (grep(/^$col$/,@posscols)) {
 2128:                     push(@cols,$col);
 2129:                 }
 2130:             }
 2131:         } else {
 2132:             @cols = @posscols;
 2133:         }
 2134:     }
 2135:     return @cols;
 2136: }
 2137: 
 2138: sub get_cols_array {
 2139:     my ($context,$mode,$showcredits) = @_;
 2140:     my @cols;
 2141:     if ($mode eq 'pickauthor') {
 2142:         @cols = ('username','fullname','status','email');
 2143:     } else {
 2144:         @cols = ('username','domain','id','fullname');
 2145:         if ($context eq 'course') {
 2146:             push(@cols,'section');
 2147:         }
 2148:         push(@cols,('start','end','role'));
 2149:         unless (($mode eq 'autoenroll') && ($env{'form.Status'} ne 'Any')) {
 2150:             push(@cols,'status');
 2151:         }
 2152:         if ($context eq 'course') {
 2153:             push(@cols,'groups');
 2154:         }
 2155:         push(@cols,'email');
 2156:         if (($context eq 'course') && ($mode ne 'autoenroll')) {
 2157:             if ($showcredits) {
 2158:                 push(@cols,'credits');
 2159:             }
 2160:             push(@cols,'lastlogin','clicker');
 2161:         }
 2162:         if (($context eq 'course') && ($mode ne 'autoenroll') &&
 2163:             ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'})) {
 2164:             push(@cols,'photo');
 2165:         }
 2166:         if ($context eq 'domain') {
 2167:             push (@cols,('authorusage','authorquota','extent'));
 2168:         }
 2169:     }
 2170:     return @cols;
 2171: }
 2172: 
 2173: sub column_checkboxes {
 2174:     my ($context,$mode,$formname,$showcredits) = @_;
 2175:     my @cols = &get_cols_array($context,$mode,$showcredits);
 2176:     my @showncols = &Apache::loncommon::get_env_multiple('form.showcol');
 2177:     my (%disabledchk,%unchecked);
 2178:     if ($env{'form.phase'} eq '') {
 2179:         $disabledchk{'status'} = 1;
 2180:         if ($context eq 'course') {
 2181:             $disabledchk{'role'} = 1;
 2182:             $unchecked{'photo'} = 1;
 2183:             $unchecked{'clicker'} = 1;
 2184:             if ($showcredits) {
 2185:                 $unchecked{'credits'} = 1;
 2186:             }
 2187:         } elsif ($context eq 'domain') { 
 2188:             $unchecked{'extent'} = 1; 
 2189:         }
 2190:         $unchecked{'start'} = 1;
 2191:         $unchecked{'end'} = 1;
 2192:     } else {
 2193:         if ($env{'form.Status'} ne 'Any') {
 2194:             $disabledchk{'status'} = 1;
 2195:         }
 2196:         if (($env{'form.showrole'} ne 'Any') && ($env{'form.showrole'} ne 'cr')) {
 2197:             $disabledchk{'role'} = 1;
 2198:         }
 2199:         if ($context eq 'domain') {
 2200:             if (($env{'form.roletype'} eq 'course') || 
 2201:                 ($env{'form.roletype'} eq 'community')) {
 2202:                 $disabledchk{'status'} = 1;
 2203:                 $disabledchk{'authorusage'} = 1;
 2204:                 $disabledchk{'authorquota'} = 1;
 2205:             } elsif ($env{'form.roletype'} eq 'domain') {
 2206:                 $disabledchk{'extent'} = 1; 
 2207:             }
 2208:         }
 2209:     }
 2210:     my $numposs = scalar(@cols);
 2211:     my $numinrow = 7;
 2212:     my %lt = &get_column_names($context);
 2213:     my $output = '<fieldset><legend>'.&mt('Information to show').'</legend>'."\n".'<span class="LC_nobreak">'.
 2214:                  '<input type="button" onclick="javascript:checkAll(document.'.$formname.'.showcol);" value="'.&mt('check all').'" />'.
 2215:                  ('&nbsp;'x3).
 2216:                  '<input type="button" onclick="javascript:uncheckAll(document.'.$formname.'.showcol);" value="'.&mt('uncheck all').'" />'.
 2217:                  '</span><table>';
 2218:     
 2219:     for (my $i=0; $i<$numposs; $i++) {
 2220:         my $rem = $i%($numinrow);
 2221:         if ($rem == 0) {
 2222:             if ($i > 0) {
 2223:                 $output .= '</tr>';
 2224:             }
 2225:             $output .= '<tr>';
 2226:         }
 2227:         my $checked;
 2228:         if ($env{'form.phase'} eq '') {
 2229:             $checked = ' checked="checked"';
 2230:             if ($unchecked{$cols[$i]}) { 
 2231:                $checked = '';
 2232:             }
 2233:             if ($disabledchk{$cols[$i]}) {
 2234:                 $checked = ' disabled="disabled"';
 2235:             }
 2236:         } elsif (grep(/^\Q$cols[$i]\E$/,@showncols)) {
 2237:             $checked = ' checked="checked"';
 2238:         } elsif ($disabledchk{$cols[$i]}) {
 2239:             $checked = ' disabled="disabled"';
 2240:         }
 2241:         if ($i == $numposs-1) {
 2242:             my $colsleft = $numinrow-$rem;
 2243:             if ($colsleft > 1) {
 2244:                 $output .= '<td colspan="'.$colsleft.'">';
 2245:             } else {
 2246:                 $output .= '<td>';
 2247:             }
 2248:         } else {
 2249:             $output .= '<td>';
 2250:         }
 2251:         my $style;
 2252:         if ($cols[$i] eq 'extent') {
 2253:             if (($env{'form.roletype'} eq 'domain') || ($env{'form.roletype'} eq '')) {
 2254:                 $style = ' style="display: none;"';
 2255:             } 
 2256:         } elsif (($cols[$i] eq 'authorusage') || ($cols[$i] eq 'authorquota')) {
 2257:             if ($env{'form.roletype'} ne 'domain') {
 2258:                 $style = ' style="display: none;"';
 2259:             }
 2260:         }
 2261:         $output .= '<span id="show'.$cols[$i].'"'.$style.'><label>'.
 2262:                    '<input id="showcol'.$cols[$i].'" type="checkbox" name="showcol" value="'.$cols[$i].'"'.$checked.' /><span id="showcoltext'.$cols[$i].'">'.
 2263:                    $lt{$cols[$i]}.'</span>'.
 2264:                    '</label></span></td>';
 2265:     }
 2266:     $output .= '</tr></table></fieldset>';
 2267:     return $output;
 2268: }
 2269: 
 2270: sub list_submit_button {
 2271:     my ($text) = @_;
 2272:     return '<input type="button" name="updatedisplay" value="'.$text.'" onclick="javascript:display_update()" />';
 2273: }
 2274: 
 2275: sub get_column_names {
 2276:     my ($context) = @_;
 2277:     my %lt = &Apache::lonlocal::texthash(
 2278:         'username'   => "username",
 2279:         'domain'     => "domain",
 2280:         'id'         => 'ID',
 2281:         'fullname'   => "name",
 2282:         'section'    => "section",
 2283:         'groups'     => "active groups",
 2284:         'start'      => "start date",
 2285:         'end'        => "end date",
 2286:         'status'     => "status",
 2287:         'role'       => "role",
 2288:         'credits'    => "credits",
 2289:         'type'       => "enroll type/action",
 2290:         'email'      => "e-mail address",
 2291:         'photo'      => "photo",
 2292:         'lastlogin'  => "last login",
 2293:         'extent'     => "extent",
 2294:         'authorusage' => "disk usage (%)",
 2295:         'authorquota' => "disk quota (MB)",
 2296:         'ca'         => "check all",
 2297:         'ua'         => "uncheck all",
 2298:         'clicker'    => "clicker-ID",
 2299:     );
 2300:     if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
 2301:         $lt{'extent'} = &mt('course(s): description, section(s), status');
 2302:     } elsif ($context eq 'domain' && $env{'form.roletype'} eq 'community') {
 2303:         $lt{'extent'} = &mt('community(s): description, section(s), status');
 2304:     } elsif (($context eq 'author') || 
 2305:              ($context eq 'domain' && $env{'form.roletype'} eq 'author')) {
 2306:         $lt{'extent'} = &mt('author');
 2307:     }
 2308:     return %lt;
 2309: }
 2310: 
 2311: sub gather_userinfo {
 2312:     my ($context,$format,$userlist,$indexhash,$userinfo,$rolehash,$permission) = @_;
 2313:     my $viewablesec;
 2314:     if ($context eq 'course') {
 2315:         $viewablesec = &viewable_section($permission);
 2316:     }
 2317:     foreach my $item (keys(%{$rolehash})) {
 2318:         my %userdata;
 2319:         if ($context eq 'author') { 
 2320:             ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
 2321:                 split(/:/,$item);
 2322:             ($userdata{'start'},$userdata{'end'})=split(/:/,$rolehash->{$item});
 2323:             &build_user_record($context,\%userdata,$userinfo,$indexhash,
 2324:                                $item,$userlist);
 2325:         } elsif ($context eq 'course') {
 2326:             ($userdata{'username'},$userdata{'domain'},$userdata{'role'},
 2327:              $userdata{'section'}) = split(/:/,$item,-1);
 2328:             ($userdata{'start'},$userdata{'end'})=split(/:/,$rolehash->{$item});
 2329:             if (($viewablesec ne '') && ($userdata{'section'} ne '')) {
 2330:                 next if ($viewablesec ne $userdata{'section'});
 2331:             }
 2332:             &build_user_record($context,\%userdata,$userinfo,$indexhash,
 2333:                                $item,$userlist);
 2334:         } elsif ($context eq 'domain') {
 2335:             if ($env{'form.roletype'} eq 'domain') {
 2336:                 ($userdata{'role'},$userdata{'username'},$userdata{'domain'}) =
 2337:                     split(/:/,$item);
 2338:                 ($userdata{'end'},$userdata{'start'})=split(/:/,$rolehash->{$item});
 2339:                 &build_user_record($context,\%userdata,$userinfo,$indexhash,
 2340:                                    $item,$userlist);
 2341:             } elsif ($env{'form.roletype'} eq 'author') {
 2342:                 if (ref($rolehash->{$item}) eq 'HASH') {
 2343:                     $userdata{'extent'} = $item;
 2344:                     foreach my $key (keys(%{$rolehash->{$item}})) {
 2345:                         ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =  split(/:/,$key);
 2346:                         ($userdata{'start'},$userdata{'end'}) = 
 2347:                             split(/:/,$rolehash->{$item}{$key});
 2348:                         my $uniqid = $key.':'.$item;
 2349:                         &build_user_record($context,\%userdata,$userinfo,
 2350:                                            $indexhash,$uniqid,$userlist);
 2351:                     }
 2352:                 }
 2353:             } elsif (($env{'form.roletype'} eq 'course') || 
 2354:                      ($env{'form.roletype'} eq 'community')) {
 2355:                 ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
 2356:                     split(/:/,$item);
 2357:                 if (ref($rolehash->{$item}) eq 'HASH') {
 2358:                     my $numcids = keys(%{$rolehash->{$item}});
 2359:                     foreach my $cid (sort(keys(%{$rolehash->{$item}}))) {
 2360:                         if (ref($rolehash->{$item}{$cid}) eq 'HASH') {
 2361:                             my $spanstart = '';
 2362:                             my $spanend = '; ';
 2363:                             my $space = ', ';
 2364:                             if ($format eq 'html' || $format eq 'view') {
 2365:                                 $spanstart = '<span class="LC_nobreak">';
 2366:                                 # FIXME: actions on courses disabled for now
 2367: #                                if ($permission->{'cusr'}) {
 2368: #                                    if ($numcids > 1) {
 2369: #                                        $spanstart .= '<input type="radio" name="'.$item.'" value="'.$cid.'" />&nbsp;';
 2370: #                                    } else {
 2371: #                                        $spanstart .= '<input type="hidden" name="'.$item.'" value="'.$cid.'" />&nbsp;';
 2372: #                                    }
 2373: #                                }
 2374:                                 $spanend = '</span><br />';
 2375:                                 $space = ',&nbsp;';
 2376:                             }
 2377:                             $userdata{'extent'} .= $spanstart.
 2378:                                     $rolehash->{$item}{$cid}{'desc'}.$space;
 2379:                             if (ref($rolehash->{$item}{$cid}{'secs'}) eq 'HASH') { 
 2380:                                 foreach my $sec (sort(keys(%{$rolehash->{$item}{$cid}{'secs'}}))) {
 2381:                                     if (($env{'form.Status'} eq 'Any') ||
 2382:                                         ($env{'form.Status'} eq $rolehash->{$item}{$cid}{'secs'}{$sec})) {
 2383:                                         $userdata{'extent'} .= $sec.$space.$rolehash->{$item}{$cid}{'secs'}{$sec}.$spanend;
 2384:                                         $userdata{'status'} = $rolehash->{$item}{$cid}{'secs'}{$sec};
 2385:                                     }
 2386:                                 }
 2387:                             }
 2388:                         }
 2389:                     }
 2390:                 }
 2391:                 if ($userdata{'status'} ne '') {
 2392:                     &build_user_record($context,\%userdata,$userinfo,
 2393:                                        $indexhash,$item,$userlist);
 2394:                 }
 2395:             }
 2396:         }
 2397:     }
 2398:     return;
 2399: }
 2400: 
 2401: sub build_user_record {
 2402:     my ($context,$userdata,$userinfo,$indexhash,$record_key,$userlist) = @_;
 2403:     next if ($userdata->{'start'} eq '-1' && $userdata->{'end'} eq '-1');
 2404:     if (!(($context eq 'domain') && (($env{'form.roletype'} eq 'course')
 2405:                              && ($env{'form.roletype'} eq 'community')))) {
 2406:         &process_date_info($userdata);
 2407:     }
 2408:     my $username = $userdata->{'username'};
 2409:     my $domain = $userdata->{'domain'};
 2410:     if (ref($userinfo->{$username.':'.$domain}) eq 'HASH') {
 2411:         $userdata->{'fullname'} = $userinfo->{$username.':'.$domain}{'fullname'};
 2412:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
 2413:     } else {
 2414:         &aggregate_user_info($domain,$username,$userinfo);
 2415:         $userdata->{'fullname'} = $userinfo->{$username.':'.$domain}{'fullname'};
 2416:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
 2417:     }
 2418:     foreach my $key (keys(%{$indexhash})) {
 2419:         if (defined($userdata->{$key})) {
 2420:             $userlist->{$record_key}[$indexhash->{$key}] = $userdata->{$key};
 2421:         }
 2422:     }
 2423:     return;
 2424: }
 2425: 
 2426: sub courses_selector {
 2427:     my ($cdom,$formname) = @_;
 2428:     my %codes = ();
 2429:     my @codetitles = ();
 2430:     my %cat_titles = ();
 2431:     my %cat_order = ();
 2432:     my %idlist = ();
 2433:     my %idnums = ();
 2434:     my %idlist_titles = ();
 2435:     my $caller = 'global';
 2436:     my $format_reply;
 2437:     my $jscript = '';
 2438: 
 2439:     my $totcodes = 0;
 2440:     my $instcats = &Apache::lonnet::get_dom_instcats($cdom);
 2441:     if (ref($instcats) eq 'HASH') {
 2442:         if ((ref($instcats->{'codetitles'}) eq 'ARRAY') && (ref($instcats->{'codes'}) eq 'HASH') &&
 2443:             (ref($instcats->{'cat_titles'}) eq 'HASH') && (ref($instcats->{'cat_order'}) eq 'HASH')) {
 2444:             %codes = %{$instcats->{'codes'}};
 2445:             @codetitles = @{$instcats->{'codetitles'}};
 2446:             %cat_titles = %{$instcats->{'cat_titles'}};
 2447:             %cat_order = %{$instcats->{'cat_order'}};
 2448:             $totcodes = scalar(keys(%codes));
 2449:             my $numtypes = @codetitles;
 2450:             &Apache::courseclassifier::build_code_selections(\%codes,\@codetitles,\%cat_titles,\%cat_order,\%idlist,\%idnums,\%idlist_titles);
 2451:             my ($scripttext,$longtitles) = &Apache::courseclassifier::javascript_definitions(\@codetitles,\%idlist,\%idlist_titles,\%idnums,\%cat_titles);
 2452:             my $longtitles_str = join('","',@{$longtitles});
 2453:             my $allidlist = $idlist{$codetitles[0]};
 2454:             $jscript .= &Apache::courseclassifier::courseset_js_start($formname,$longtitles_str,$allidlist);
 2455:             $jscript .= $scripttext;
 2456:             $jscript .= &Apache::courseclassifier::javascript_code_selections($formname,\@codetitles);
 2457:         }
 2458:     }
 2459:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($cdom);
 2460: 
 2461:     my %elements = (
 2462:                      Year => 'selectbox',
 2463:                      coursepick => 'radio',
 2464:                      coursetotal => 'text',
 2465:                      courselist => 'text',
 2466:                    );
 2467:     $jscript .= &Apache::lonhtmlcommon::set_form_elements(\%elements);
 2468:     if ($env{'form.coursepick'} eq 'category') {
 2469:         $jscript .= qq|
 2470: function setCourseCat(formname) {
 2471:     if (formname.Year.options[formname.Year.selectedIndex].value == -1) {
 2472:         return;
 2473:     }
 2474:     courseSet('$codetitles[0]');
 2475:     for (var j=0; j<formname.Semester.length; j++) {
 2476:         if (formname.Semester.options[j].value == "$env{'form.Semester'}") {
 2477:             formname.Semester.options[j].selected = true;
 2478:         }
 2479:     }
 2480:     if (formname.Semester.options[formname.Semester.selectedIndex].value == -1) {
 2481:         return;
 2482:     }
 2483:     courseSet('$codetitles[1]');
 2484:     for (var j=0; j<formname.Department.length; j++) {
 2485:         if (formname.Department.options[j].value == "$env{'form.Department'}") {
 2486:             formname.Department.options[j].selected = true;
 2487:         }
 2488:     }
 2489:     if (formname.Department.options[formname.Department.selectedIndex].value == -1) {
 2490:         return;
 2491:     }
 2492:     courseSet('$codetitles[2]');
 2493:     for (var j=0; j<formname.Number.length; j++) {
 2494:         if (formname.Number.options[j].value == "$env{'form.Number'}") {
 2495:             formname.Number.options[j].selected = true;
 2496:         }
 2497:     }
 2498: }
 2499: |;
 2500:     }
 2501:     return ($cb_jscript,$jscript,$totcodes,\@codetitles,\%idlist,
 2502:             \%idlist_titles);
 2503: }
 2504: 
 2505: sub course_selector_loadcode {
 2506:     my ($formname) = @_;
 2507:     my $loadcode;
 2508:     if ($env{'form.coursepick'} ne '') {
 2509:         $loadcode = 'javascript:setFormElements(document.'.$formname.')';
 2510:         if ($env{'form.coursepick'} eq 'category') {
 2511:             $loadcode .= ';javascript:setCourseCat(document.'.$formname.')';
 2512:         }
 2513:     }
 2514:     return $loadcode;
 2515: }
 2516: 
 2517: sub process_coursepick {
 2518:     my $coursefilter = $env{'form.coursepick'};
 2519:     my $cdom = $env{'request.role.domain'};
 2520:     my %courses;
 2521:     my $crssrch = 'Course';
 2522:     if ($env{'form.roletype'} eq 'community') {
 2523:         $crssrch = 'Community';
 2524:     }
 2525:     if ($coursefilter eq 'all') {
 2526:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.','.','.','.',
 2527:                                                  undef,undef,$crssrch);
 2528:     } elsif ($coursefilter eq 'category') {
 2529:         my $instcode = &instcode_from_coursefilter();
 2530:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.',$instcode,'.','.',
 2531:                                                  undef,undef,$crssrch);
 2532:     } elsif ($coursefilter eq 'specific') {
 2533:         if ($env{'form.coursetotal'} > 1) {
 2534:             my @course_ids = split(/&&/,$env{'form.courselist'});
 2535:             foreach my $cid (@course_ids) {
 2536:                 $courses{$cid} = '';
 2537:             }
 2538:         } else {
 2539:             $courses{$env{'form.courselist'}} = '';
 2540:         }
 2541:     }
 2542:     return %courses;
 2543: }
 2544: 
 2545: sub instcode_from_coursefilter {
 2546:     my $instcode = '';
 2547:     my @cats = ('Semester','Year','Department','Number');
 2548:     foreach my $category (@cats) {
 2549:         if (defined($env{'form.'.$category})) {
 2550:             unless ($env{'form.'.$category} eq '-1') {
 2551:                 $instcode .= $env{'form.'.$category};
 2552:            }
 2553:         }
 2554:     }
 2555:     if ($instcode eq '') {
 2556:         $instcode = '.';
 2557:     }
 2558:     return $instcode;
 2559: }
 2560: 
 2561: sub make_keylist_array {
 2562:     my ($index,$keylist);
 2563:     $index->{'domain'} = &Apache::loncoursedata::CL_SDOM();
 2564:     $index->{'username'} = &Apache::loncoursedata::CL_SNAME();
 2565:     $index->{'end'} = &Apache::loncoursedata::CL_END();
 2566:     $index->{'start'} = &Apache::loncoursedata::CL_START();
 2567:     $index->{'id'} = &Apache::loncoursedata::CL_ID();
 2568:     $index->{'section'} = &Apache::loncoursedata::CL_SECTION();
 2569:     $index->{'fullname'} = &Apache::loncoursedata::CL_FULLNAME();
 2570:     $index->{'status'} = &Apache::loncoursedata::CL_STATUS();
 2571:     $index->{'type'} = &Apache::loncoursedata::CL_TYPE();
 2572:     $index->{'lockedtype'} = &Apache::loncoursedata::CL_LOCKEDTYPE();
 2573:     $index->{'groups'} = &Apache::loncoursedata::CL_GROUP();
 2574:     $index->{'email'} = &Apache::loncoursedata::CL_PERMANENTEMAIL();
 2575:     $index->{'role'} = &Apache::loncoursedata::CL_ROLE();
 2576:     $index->{'extent'} = &Apache::loncoursedata::CL_EXTENT();
 2577:     $index->{'photo'} = &Apache::loncoursedata::CL_PHOTO();
 2578:     $index->{'thumbnail'} = &Apache::loncoursedata::CL_THUMBNAIL();
 2579:     $index->{'credits'} = &Apache::loncoursedata::CL_CREDITS();
 2580:     $index->{'instsec'} = &Apache::loncoursedata::CL_INSTSEC();
 2581:     $index->{'authorquota'} = &Apache::loncoursedata::CL_AUTHORQUOTA();
 2582:     $index->{'authorusage'} = &Apache::loncoursedata::CL_AUTHORUSAGE();
 2583:     foreach my $key (keys(%{$index})) {
 2584:         $keylist->[$index->{$key}] = $key;
 2585:     }
 2586:     return ($index,$keylist);
 2587: }
 2588: 
 2589: sub aggregate_user_info {
 2590:     my ($udom,$uname,$userinfo) = @_;
 2591:     my %info=&Apache::lonnet::get('environment',
 2592:                                   ['firstname','middlename',
 2593:                                    'lastname','generation','id'],
 2594:                                    $udom,$uname);
 2595:     my ($tmp) = keys(%info);
 2596:     my ($fullname,$id);
 2597:     if ($tmp =~/^(con_lost|error|no_such_host)/i) {
 2598:         $fullname = 'not available';
 2599:         $id = 'not available';
 2600:         &Apache::lonnet::logthis('unable to retrieve environment '.
 2601:                                  'for '.$uname.':'.$udom);
 2602:     } else {
 2603:         $fullname = &Apache::lonnet::format_name(@info{qw/firstname middlename lastname generation/},'lastname');
 2604:         $id = $info{'id'};
 2605:     }
 2606:     $userinfo->{$uname.':'.$udom} = { 
 2607:                                       fullname => $fullname,
 2608:                                       id       => $id,
 2609:                                     };
 2610:     return;
 2611: }
 2612: 
 2613: sub process_date_info {
 2614:     my ($userdata) = @_;
 2615:     my $now = time;
 2616:     $userdata->{'status'} = 'Active';
 2617:     if ($userdata->{'start'} > 0) {
 2618:         if ($now < $userdata->{'start'}) {
 2619:             $userdata->{'status'} = 'Future';
 2620:         }
 2621:     }
 2622:     if ($userdata->{'end'} > 0) {
 2623:         if ($now > $userdata->{'end'}) {
 2624:             $userdata->{'status'} = 'Expired';
 2625:         }
 2626:     }
 2627:     return;
 2628: }
 2629: 
 2630: sub show_users_list {
 2631:     my ($r,$context,$mode,$permission,$statusmode,$userlist,$keylist,$formname,
 2632:         $showcredits,$needauthorquota,$needauthorusage)=@_;
 2633:     if ($formname eq '') {
 2634:         $formname = 'studentform';
 2635:     }
 2636:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2637:     #
 2638:     # Variables for excel output
 2639:     my ($excel_workbook, $excel_sheet, $excel_filename,$row,$format);
 2640:     #
 2641:     # Variables for csv output
 2642:     my ($CSVfile,$CSVfilename);
 2643:     #
 2644:     my $sortby = $env{'form.sortby'};
 2645:     my @sortable = ('username','domain','id','fullname','start','end','email','role');
 2646:     if ($context eq 'course') {
 2647:         push(@sortable,('section','groups','type'));
 2648:         if ($showcredits) {
 2649:             push(@sortable,'credits');
 2650:         }
 2651:     } else {
 2652:         push(@sortable,'extent');
 2653:         if (($context eq 'domain') && ($env{'form.roletype'} eq 'domain') &&
 2654:             (($env{'form.showrole'} eq 'Any') || ($env{'form.showrole'} eq 'au'))) {
 2655:             push(@sortable,('authorusage','authorquota'));
 2656:         }
 2657:     }
 2658:     if ($mode eq 'pickauthor') {
 2659:         @sortable = ('username','fullname','email','status');
 2660:     }
 2661:     my %is_sortable;
 2662:     map { $is_sortable{$_} = 1; } @sortable;
 2663:     unless ($is_sortable{$sortby}) {
 2664:         $sortby = 'username';
 2665:     }
 2666:     my $setting = $env{'form.roletype'};
 2667:     my ($cid,$cdom,$cnum,$classgroups,$crstype,$defaultcredits);
 2668:     if ($context eq 'course') {
 2669:         $cid = $env{'request.course.id'};
 2670:         $crstype = &Apache::loncommon::course_type();
 2671:         ($cnum,$cdom) = &get_course_identity($cid);
 2672:         $defaultcredits = $env{'course.'.$cid.'.internal.defaultcredits'};
 2673:         ($classgroups) = &Apache::loncoursedata::get_group_memberships(
 2674:                                      $userlist,$keylist,$cdom,$cnum);
 2675:         if ($mode eq 'autoenroll') {
 2676:             $env{'form.showrole'} = 'st';
 2677:         } else {
 2678:             if ($env{'course.'.$cid.'.internal.showphoto'}) {
 2679:                 $r->print('
 2680: <script type="text/javascript">
 2681: // <![CDATA[
 2682: function photowindow(photolink) {
 2683:     var title = "Photo_Viewer";
 2684:     var options = "scrollbars=1,resizable=1,menubar=0";
 2685:     options += ",width=240,height=240";
 2686:     stdeditbrowser = open(photolink,title,options,"1");
 2687:     stdeditbrowser.focus();
 2688: }
 2689: // ]]>
 2690: </script>
 2691:                ');
 2692:             }
 2693:         }
 2694:     } elsif ($context eq 'domain') {
 2695:         if ($setting eq 'community') {
 2696:             $crstype = 'Community';
 2697:         } elsif ($setting eq 'course') {
 2698:             $crstype = 'Course';
 2699:         }
 2700:     }
 2701:     if ($mode ne 'autoenroll' && $mode ne 'pickauthor') {
 2702:         my $date_sec_selector = &date_section_javascript($context,$setting,$statusmode);
 2703:         my $verify_action_js = &bulkaction_javascript($formname);
 2704:         $r->print(<<END);
 2705: 
 2706: <script type="text/javascript" language="Javascript">
 2707: // <![CDATA[
 2708: 
 2709: $verify_action_js
 2710: 
 2711: function username_display_launch(username,domain) {
 2712:     var target;
 2713:     if (!document.$formname.usernamelink.length) {
 2714:         target = document.$formname.usernamelink.value;
 2715:     } else {
 2716:         for (var i=0; i<document.$formname.usernamelink.length; i++) {
 2717:             if (document.$formname.usernamelink[i].checked) {
 2718:                target = document.$formname.usernamelink[i].value;
 2719:             }
 2720:         }
 2721:     }
 2722:     if ((target == 'modify') || (target == 'activity')) {
 2723:         var nextaction = 'singleuser';
 2724:         if (target == 'activity') {
 2725:             nextaction = 'accesslogs';
 2726:         }
 2727:         if (document.$formname.userwin.checked == true) {
 2728:             var url = '/adm/createuser?srchterm='+username+'&srchdomain='+domain+'&phase=get_user_info&srchin=dom&srchby=uname&srchtype=exact&popup=1&action='+nextaction;
 2729:             var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2730:             modifywin = window.open(url,'',options,1);
 2731:             modifywin.focus();
 2732:             return;
 2733:         } else {
 2734:             document.$formname.srchterm.value=username;
 2735:             document.$formname.srchdomain.value=domain;
 2736:             document.$formname.phase.value='get_user_info';
 2737:             document.$formname.action.value = nextaction;
 2738:             document.$formname.submit();
 2739:         }
 2740:     }
 2741:     if (target == 'aboutme') {
 2742:         if (document.$formname.userwin.checked == true) {
 2743:             var url = '/adm/'+domain+'/'+username+'/aboutme?popup=1';
 2744:             var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2745:             aboutmewin = window.open(url,'',options,1);
 2746:             aboutmewin.focus();
 2747:             return;
 2748:         } else {
 2749:             document.location.href = '/adm/'+domain+'/'+username+'/aboutme';
 2750:         }
 2751:     }
 2752:     if (target == 'track') {
 2753:         if (document.$formname.userwin.checked == true) {
 2754:             var url = '/adm/trackstudent?selected_student='+username+':'+domain+'&only_body=1';
 2755:             var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
 2756:             var trackwin = window.open(url,'',options,1);
 2757:             trackwin.focus();
 2758:             return;
 2759:         } else {
 2760:             document.location.href = '/adm/trackstudent?selected_student='+username+':'+domain;
 2761:         }
 2762:     }
 2763: }
 2764: // ]]>
 2765: </script>
 2766: $date_sec_selector
 2767: <input type="hidden" name="state" value="$env{'form.state'}" />
 2768: END
 2769:     }
 2770:     $r->print(<<END);
 2771: <input type="hidden" name="sortby" value="$sortby" />
 2772: END
 2773:     my @cols = &infocolumns($context,$mode,$showcredits);
 2774:     my %coltxt = &get_column_names($context);
 2775:     my %acttxt = &Apache::lonlocal::texthash(
 2776:                        'pr'         => "Proceed",
 2777:                        'ac'         => "Action to take for selected users",
 2778:                        'link'       => "Behavior of clickable username link for each user",
 2779:                        'aboutme'    => "Display a user's personal information page",
 2780:                        'owin'       => "Open in a new window",
 2781:                        'modify'     => "Modify a user's information",
 2782:                        'track'      => "View a user's recent activity",
 2783:                        'activity'   => "View a user's access log", 
 2784:                       );
 2785:     my %lt = (%coltxt,%acttxt);
 2786:     my $rolefilter = $env{'form.showrole'};
 2787:     if ($env{'form.showrole'} eq 'cr') {
 2788:         $rolefilter = &mt('custom');  
 2789:     } elsif ($env{'form.showrole'} ne 'Any') {
 2790:         $rolefilter = &Apache::lonnet::plaintext($env{'form.showrole'},$crstype);
 2791:     }
 2792:     my $results_description;
 2793:     if ($mode ne 'autoenroll') {
 2794:         $results_description = &results_header_row($rolefilter,$statusmode,
 2795:                                                    $context,$permission,$mode,$crstype);
 2796:         $r->print('<b>'.$results_description.'</b><br clear="all" />');
 2797:     }
 2798:     my ($output,$actionselect,%canchange,%canchangesec);
 2799:     if ($mode eq 'html' || $mode eq 'view' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
 2800:         if ($mode ne 'autoenroll' && $mode ne 'pickauthor') {
 2801:             if ($permission->{'cusr'}) {
 2802:                 unless (($context eq 'domain') && 
 2803:                         (($setting eq 'course') || ($setting eq 'community'))) {
 2804:                     $actionselect = 
 2805:                         &select_actions($context,$setting,$statusmode,$formname);
 2806:                 }
 2807:             }
 2808:             $r->print(<<END);
 2809: <input type="hidden" name="srchby"  value="uname" />
 2810: <input type="hidden" name="srchin"   value="dom" />
 2811: <input type="hidden" name="srchtype" value="exact" />
 2812: <input type="hidden" name="srchterm" value="" />
 2813: <input type="hidden" name="srchdomain" value="" /> 
 2814: END
 2815:             if ($actionselect) {
 2816:                 $output .= <<"END";
 2817: <div class="LC_left_float"><fieldset><legend>$lt{'ac'}</legend>
 2818: $actionselect
 2819: <br/><br /><input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.$formname.actionlist)" /> &nbsp;
 2820: <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>
 2821: END
 2822:                 my @allroles;
 2823:                 if ($env{'form.showrole'} eq 'Any') {
 2824:                     my $custom = 1;
 2825:                     if ($context eq 'domain') {
 2826:                         @allroles = &roles_by_context($setting,$custom,$crstype);
 2827:                     } else {
 2828:                         @allroles = &roles_by_context($context,$custom,$crstype);
 2829:                     }
 2830:                 } else {
 2831:                     @allroles = ($env{'form.showrole'});
 2832:                 }
 2833:                 foreach my $role (@allroles) {
 2834:                     if ($context eq 'domain') {
 2835:                         if ($setting eq 'domain') {
 2836:                             if (&Apache::lonnet::allowed('c'.$role,
 2837:                                     $env{'request.role.domain'})) {
 2838:                                 $canchange{$role} = 1;
 2839:                             }
 2840:                         } elsif ($setting eq 'author') {
 2841:                             if (&Apache::lonnet::allowed('c'.$role,
 2842:                                     $env{'request.role.domain'})) {
 2843:                                 $canchange{$role} = 1;
 2844:                             }
 2845:                         }
 2846:                     } elsif ($context eq 'author') {
 2847:                         if (&Apache::lonnet::allowed('c'.$role,
 2848:                             $env{'user.domain'}.'/'.$env{'user.name'})) {
 2849:                             $canchange{$role} = 1;
 2850:                         }
 2851:                     } elsif ($context eq 'course') {
 2852:                         if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
 2853:                             $canchange{$role} = 1;
 2854:                         } elsif ($env{'request.course.sec'} ne '') {
 2855:                             if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
 2856:                                 $canchangesec{$role} = $env{'request.course.sec'};
 2857:                             }
 2858:                         } elsif ((($role eq 'co') && ($crstype eq 'Community')) ||
 2859:                                  (($role eq 'cc') && ($crstype eq 'Course'))) {
 2860:                             if (&is_courseowner($env{'request.course.id'},
 2861:                                                 $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'})) {
 2862:                                 $canchange{$role} = 1;
 2863:                             }
 2864:                         }
 2865:                     }
 2866:                 }
 2867:             }
 2868:             $output .= '<div class="LC_left_float"><fieldset><legend>'.$lt{'link'}.'</legend>'.
 2869:                        '<table><tr>';
 2870:             my @linkdests = ('aboutme');
 2871:             if ($permission->{'cusr'}) {
 2872:                 unshift (@linkdests,'modify');
 2873:             }
 2874:             if ($context eq 'course') {
 2875:                 if (&Apache::lonnet::allowed('vsa', $env{'request.course.id'}) ||
 2876:                     &Apache::lonnet::allowed('vsa', $env{'request.course.id'}.'/'.
 2877:                                              $env{'request.course.sec'})) {
 2878:                     push(@linkdests,'track');
 2879:                 }
 2880:             } elsif ($context eq 'domain') {
 2881:                 if (&Apache::lonnet::allowed('vac',$env{'request.role.domain'})) {
 2882:                     push(@linkdests,'activity');
 2883:                 }
 2884:             }
 2885:             $output .= '<td>';
 2886:             my $usernamelink = $env{'form.usernamelink'};
 2887:             if ($usernamelink eq '') {
 2888:                 $usernamelink = 'aboutme';
 2889:             }
 2890:             foreach my $item (@linkdests) {
 2891:                 my $checkedstr = '';
 2892:                 if ($item eq $usernamelink) {
 2893:                     $checkedstr = ' checked="checked"';
 2894:                 }
 2895:                 $output .= '<span class="LC_nobreak"><label><input type="radio" name="usernamelink" value="'.$item.'"'.$checkedstr.' />&nbsp;'.$lt{$item}.'</label></span><br />';
 2896:             }
 2897:             my $checkwin;
 2898:             if ($env{'form.userwin'}) {
 2899:                 $checkwin = ' checked="checked"';
 2900:             }
 2901:             $output .=
 2902:                 '</td><td valign="top"  style="border-left: 1px solid;">'
 2903:                .'<span class="LC_nobreak"><label>'
 2904:                .'<input type="checkbox" name="userwin" value="1"'.$checkwin.' />'.$lt{'owin'}
 2905:                .'</label></span></td></tr></table></fieldset></div>';
 2906:         }
 2907:         $output .= "\n".'<div style="padding:0;clear:both;margin:0;border:0"></div>'."\n".
 2908:                   &Apache::loncommon::start_data_table().
 2909:                   &Apache::loncommon::start_data_table_header_row();
 2910:         if ($mode eq 'autoenroll') {
 2911:             $output .= "
 2912:  <th><a href=\"javascript:document.$formname.sortby.value='type';document.$formname.submit();\">$lt{'type'}</a></th>
 2913:             ";
 2914:         } else {
 2915:             $output .= "\n".'<th>&nbsp;</th>'."\n";
 2916:             if ($actionselect) {
 2917:                 $output .= '<th class="LC_nobreak" valign="top">'.&mt('Select').'</th>'."\n";
 2918:             }
 2919:         }
 2920:         foreach my $item (@cols) {
 2921:             $output .= '<th class="LC_nobreak" valign="top">';
 2922:             if ($is_sortable{$item}) {
 2923:                 $output .= "<a href=\"javascript:document.$formname.sortby.value='$item';document.$formname.submit();\" style=\"text-decoration:none;\">$lt{$item}<span class=\"LC_fontsize_small\"> &#9660;</span></a>";
 2924:             } else {
 2925:                 $output .= $lt{$item};
 2926:             }
 2927:             $output .= "</th>\n";
 2928:         }
 2929:         my %role_types = &role_type_names();
 2930:         $output .= &Apache::loncommon::end_data_table_header_row();
 2931: # Done with the HTML header line
 2932:     } elsif ($mode eq 'csv') {
 2933:         #
 2934:         # Open a file
 2935:         $CSVfilename = '/prtspool/'.
 2936:                        $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2937:                        time.'_'.rand(1000000000).'.csv';
 2938:         unless ($CSVfile = Apache::File->new('>/home/httpd'.$CSVfilename)) {
 2939:             $r->log_error("Couldn't open $CSVfilename for output $!");
 2940:             $r->print(
 2941:                 '<p class="LC_error">'
 2942:                .&mt('Problems occurred in writing the CSV file.')
 2943:                .' '.&mt('This error has been logged.')
 2944:                .' '.&mt('Please alert your LON-CAPA administrator.')
 2945:                .'</p>'
 2946:             );
 2947:             $CSVfile = undef;
 2948:         }
 2949:         #
 2950:         # Write headers and data to file
 2951:         print $CSVfile '"'.$results_description.'"'."\n"; 
 2952:         print $CSVfile '"'.join('","',map {
 2953:             &Apache::loncommon::csv_translate($lt{$_})
 2954:             } (@cols))."\"\n";
 2955:     } elsif ($mode eq 'excel') {
 2956:         # Create the excel spreadsheet
 2957:         ($excel_workbook,$excel_filename,$format) =
 2958:             &Apache::loncommon::create_workbook($r);
 2959:         return if (! defined($excel_workbook));
 2960:         $excel_sheet = $excel_workbook->addworksheet('userlist');
 2961:         $excel_sheet->write($row++,0,$results_description,$format->{'h2'});
 2962:         #
 2963:         my @colnames = map {$lt{$_}} (@cols);
 2964: 
 2965:         $excel_sheet->write($row++,0,\@colnames,$format->{'bold'});
 2966:     }
 2967: 
 2968: # Done with header lines in all formats
 2969:     my %index;
 2970:     my $i;
 2971:     foreach my $idx (@$keylist) {
 2972:         $index{$idx} = $i++;
 2973:     }
 2974:     my $usercount = 0;
 2975:     my ($secfilter,$grpfilter);
 2976:     if ($context eq 'course') {
 2977:         $secfilter = $env{'form.secfilter'};
 2978:         $grpfilter = $env{'form.grpfilter'};
 2979:         if ($secfilter eq '') {
 2980:             $secfilter = 'all';
 2981:         }
 2982:         if ($grpfilter eq '') {
 2983:             $grpfilter = 'all';
 2984:         }
 2985:     }
 2986:     my %ltstatus = &Apache::lonlocal::texthash(
 2987:                                                 Active  => 'Active',
 2988:                                                 Future  => 'Future',
 2989:                                                 Expired => 'Expired',
 2990:                                                );
 2991:     # If this is for a single course get last course "log-in".
 2992:     my %crslogins;
 2993:     if ($context eq 'course') {
 2994:         %crslogins=&Apache::lonnet::dump('nohist_crslastlogin',$cdom,$cnum);
 2995:     }
 2996:     # Get groups, role, permanent e-mail so we can sort on them if
 2997:     # necessary.
 2998:     foreach my $user (keys(%{$userlist})) {
 2999:         if ($user eq '' ) {
 3000:             delete($userlist->{$user});
 3001:             next;
 3002:         }
 3003:         if ($context eq 'domain' &&  $user eq $env{'request.role.domain'}.'-domainconfig:'.$env{'request.role.domain'}) {
 3004:             delete($userlist->{$user});
 3005:             next;
 3006:         }
 3007:         my ($uname,$udom,$role,$groups,$email);
 3008:         if (($statusmode ne 'Any') && 
 3009:                  ($userlist->{$user}->[$index{'status'}] ne $statusmode)) {
 3010:             delete($userlist->{$user});
 3011:             next;
 3012:         }
 3013:         if ($context eq 'domain') {
 3014:             if ($env{'form.roletype'} eq 'domain') {
 3015:                 ($role,$uname,$udom) = split(/:/,$user);
 3016:                 if (($uname eq $env{'request.role.domain'}.'-domainconfig') &&
 3017:                     ($udom eq $env{'request.role.domain'})) {
 3018:                     delete($userlist->{$user});
 3019:                     next;
 3020:                 }
 3021:             } elsif ($env{'form.roletype'} eq 'author') {
 3022:                 ($uname,$udom,$role) = split(/:/,$user,-1);
 3023:             } elsif (($env{'form.roletype'} eq 'course') || 
 3024:                      ($env{'form.roletype'} eq 'community')) {
 3025:                 ($uname,$udom,$role) = split(/:/,$user);
 3026:             }
 3027:         } else {
 3028:             ($uname,$udom,$role) = split(/:/,$user,-1);
 3029:             if (($context eq 'course') && $role eq '') {
 3030:                 $role = 'st';
 3031:             }
 3032:         }
 3033:         $userlist->{$user}->[$index{'role'}] = $role;
 3034:         if (($env{'form.showrole'} ne 'Any') && (!($env{'form.showrole'}  eq 'cr' && $role =~ /^cr\//)) && ($role ne $env{'form.showrole'})) {
 3035:             delete($userlist->{$user});
 3036:             next;
 3037:         }
 3038:         if ($context eq 'course') {
 3039:             my @ac_groups;
 3040:             if (ref($classgroups) eq 'HASH') {
 3041:                 $groups = $classgroups->{$user};
 3042:             }
 3043:             if (ref($groups->{'active'}) eq 'HASH') {
 3044:                 @ac_groups = keys(%{$groups->{'active'}});
 3045:                 $userlist->{$user}->[$index{'groups'}] = join(', ',@ac_groups);
 3046:             }
 3047:             if ($mode ne 'autoenroll') {
 3048:                 my $section = $userlist->{$user}->[$index{'section'}];
 3049:                 if (($env{'request.course.sec'} ne '') && 
 3050:                     ($section ne $env{'request.course.sec'})) {
 3051:                     if ($role eq 'st') {
 3052:                         delete($userlist->{$user});
 3053:                         next;
 3054:                     }
 3055:                 }
 3056:                 if ($secfilter eq 'none') {
 3057:                     if ($section ne '') {
 3058:                         delete($userlist->{$user});
 3059:                         next;
 3060:                     }
 3061:                 } elsif ($secfilter ne 'all') {
 3062:                     if ($section ne $secfilter) {
 3063:                         delete($userlist->{$user});
 3064:                         next;
 3065:                     }
 3066:                 }
 3067:                 if ($grpfilter eq 'none') {
 3068:                     if (@ac_groups > 0) {
 3069:                         delete($userlist->{$user});
 3070:                         next;
 3071:                     }
 3072:                 } elsif ($grpfilter ne 'all') {
 3073:                     if (!grep(/^\Q$grpfilter\E$/,@ac_groups)) {
 3074:                         delete($userlist->{$user});
 3075:                         next;
 3076:                     }
 3077:                 }
 3078:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3079:                     if ((grep/^photo$/,@cols) && ($role eq 'st')) {
 3080:                         $userlist->{$user}->[$index{'photo'}] =
 3081:                             &Apache::lonnet::retrievestudentphoto($udom,$uname,'jpg');
 3082:                         $userlist->{$user}->[$index{'thumbnail'}] =
 3083:                             &Apache::lonnet::retrievestudentphoto($udom,$uname,
 3084:                                                                 'gif','thumbnail');
 3085:                     }
 3086:                 }
 3087:                 if (($role eq 'st') && ($defaultcredits)) {
 3088:                     if ($userlist->{$user}->[$index{'credits'}] eq '') {
 3089:                         $userlist->{$user}->[$index{'credits'}] = $defaultcredits;
 3090:                     }
 3091:                 }
 3092:             }
 3093:         }
 3094:         my %emails   = &Apache::loncommon::getemails($uname,$udom);
 3095:         if ($emails{'permanentemail'} =~ /\S/) {
 3096:             $userlist->{$user}->[$index{'email'}] = $emails{'permanentemail'};
 3097:         }
 3098:         if (($context eq 'domain') && ($env{'form.roletype'} eq 'domain') && 
 3099:             ($role eq 'au')) {
 3100:             my ($disk_quota,$current_disk_usage,$percent); 
 3101:             if (($needauthorusage) || ($needauthorquota)) {
 3102:                 $disk_quota = &Apache::loncommon::get_user_quota($uname,$udom,'author');
 3103:             }
 3104:             if ($needauthorusage) {
 3105:                 $current_disk_usage =
 3106:                     &Apache::lonnet::diskusage($udom,$uname,"$londocroot/priv/$udom/$uname");
 3107:                 if ($disk_quota == 0) {
 3108:                     $percent = 100.0;
 3109:                 } else {
 3110:                     $percent = $current_disk_usage/(10 * $disk_quota);
 3111:                 }
 3112:                 $userlist->{$user}->[$index{'authorusage'}] = sprintf("%.0f",$percent);
 3113:             }
 3114:             if ($needauthorquota) {
 3115:                 $userlist->{$user}->[$index{'authorquota'}] = sprintf("%.2f",$disk_quota);
 3116:             }
 3117:         }
 3118:         $usercount ++;
 3119:     }
 3120:     my $autocount = 0;
 3121:     my $manualcount = 0;
 3122:     my $lockcount = 0;
 3123:     my $unlockcount = 0;
 3124:     if ($usercount) {
 3125:         $r->print($output);
 3126:     } else {
 3127:         if ($mode eq 'autoenroll') {
 3128:             return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
 3129:         } else {
 3130:             return;
 3131:         }
 3132:     }
 3133:     #
 3134:     # Sort the users
 3135:     my $index  = $index{$sortby};
 3136:     my $second = $index{'username'};
 3137:     my $third  = $index{'domain'};
 3138:     my @sorted_users;
 3139:     if (($sortby eq 'authorquota') || ($sortby eq 'authorusage')) {  
 3140:         @sorted_users = sort {
 3141:             $userlist->{$b}->[$index] <=> $userlist->{$a}->[$index]           ||
 3142:             lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second]) ||
 3143:             lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
 3144:             } (keys(%$userlist));
 3145:     } else {
 3146:         @sorted_users = sort {
 3147:             lc($userlist->{$a}->[$index]) cmp lc($userlist->{$b}->[$index])   ||
 3148:             lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second]) ||
 3149:             lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
 3150:             } (keys(%$userlist));
 3151:     }
 3152:     my $rowcount = 0;
 3153:     my $disabled;
 3154:     if ($mode eq 'autoenroll') {
 3155:         unless ($permission->{'cusr'}) {
 3156:             $disabled = ' disabled="disabled"';
 3157:         }
 3158:     }
 3159:     foreach my $user (@sorted_users) {
 3160:         my %in;
 3161:         my $sdata = $userlist->{$user};
 3162:         $rowcount ++; 
 3163:         foreach my $item (@{$keylist}) {
 3164:             $in{$item} = $sdata->[$index{$item}];
 3165:         }
 3166:         my $clickers = (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
 3167:         if ($clickers!~/\w/) { $clickers='-'; }
 3168:         $in{'clicker'} = $clickers;
 3169: 	my $role = $in{'role'};
 3170:         $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}],$crstype);
 3171:         unless ($mode eq 'excel') {
 3172:             if (! defined($in{'start'}) || $in{'start'} == 0) {
 3173:                 $in{'start'} = &mt('none');
 3174:             } else {
 3175:                 $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
 3176:             }
 3177:             if (! defined($in{'end'}) || $in{'end'} == 0) {
 3178:                 $in{'end'} = &mt('none');
 3179:             } else {
 3180:                 $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
 3181:             }
 3182:         }
 3183:         if ($context eq 'course') {
 3184:             my $lastlogin = $crslogins{$in{'username'}.':'.$in{'domain'}.':'.$in{'section'}.':'.$role};
 3185:             if ($lastlogin ne '') {
 3186:                 $in{'lastlogin'} = &Apache::lonlocal::locallocaltime($lastlogin);
 3187:             }
 3188:         }
 3189:         if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
 3190:             $r->print(&Apache::loncommon::start_data_table_row());
 3191:             my $checkval;
 3192:             if ($mode eq 'autoenroll') {
 3193:                 my $cellentry;
 3194:                 if ($in{'type'} eq 'auto') {
 3195:                     $cellentry = '<b>'.&mt('auto').'</b>&nbsp;<label><input type="checkbox" name="chgauto" value="'.$in{'username'}.':'.$in{'domain'}.'"'.$disabled.' />&nbsp;'.&mt('Change').'</label>';
 3196:                     $autocount ++;
 3197:                 } else {
 3198:                     $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'}.'"'.$disabled.' />&nbsp;'.&mt('Change').'</label></span></td></tr><tr><td><span class="LC_nobreak">';
 3199:                     $manualcount ++;
 3200:                     if ($in{'lockedtype'}) {
 3201:                         $cellentry .= '<label><input type="checkbox" name="unlockchg" value="'.$in{'username'}.':'.$in{'domain'}.'"'.$disabled.' />&nbsp;'.&mt('Unlock').'</label>';
 3202:                         $unlockcount ++;
 3203:                     } else {
 3204:                         $cellentry .= '<label><input type="checkbox" name="lockchg" value="'.$in{'username'}.':'.$in{'domain'}.'"'.$disabled.' />&nbsp;'.&mt('Lock').'</label>';
 3205:                         $lockcount ++;
 3206:                     }
 3207:                     $cellentry .= '</span></td></tr></table>';
 3208:                 }
 3209:                 $r->print("<td>$cellentry</td>\n");
 3210:             } else {
 3211:                 if ($mode ne 'pickauthor') {  
 3212:                     $r->print("<td>$rowcount</td>\n");
 3213:                 }
 3214:                 if ($actionselect) {
 3215:                     my $showcheckbox;
 3216:                     if ($role =~ /^cr\//) {
 3217:                         $showcheckbox = $canchange{'cr'};
 3218:                     } else {
 3219:                         $showcheckbox = $canchange{$role};
 3220:                     }
 3221:                     if (!$showcheckbox) {
 3222:                         if ($context eq 'course') {
 3223:                             if ($canchangesec{$role} ne '') {
 3224:                                 if ($canchangesec{$role} eq $in{'section'}) {
 3225:                                     $showcheckbox = 1;
 3226:                                 }
 3227:                             }
 3228:                         }
 3229:                     }
 3230:                     if ($showcheckbox) {
 3231:                         $checkval = $user; 
 3232:                         if ($context eq 'course') {
 3233:                             if (($role eq 'co' || $role eq 'cc') &&
 3234:                                 ($user =~ /^\Q$env{'user.name'}:$env{'user.domain'}:$role\E/)) {
 3235:                                 $showcheckbox = 0;
 3236:                             } else {
 3237:                                 if ($role eq 'st') {
 3238:                                     $checkval .= ':st';
 3239:                                 }
 3240:                                 $checkval .= ':'.$in{'section'};
 3241:                                 if ($role eq 'st') {
 3242:                                     $checkval .= ':'.$in{'type'}.':'.
 3243:                                                  $in{'lockedtype'}.':'.
 3244:                                                  $in{'credits'}.':'.
 3245:                                                  &escape($in{'instsec'});
 3246:                                 }
 3247:                              }
 3248:                         }
 3249:                         if ($showcheckbox) {
 3250:                             $r->print('<td><input type="checkbox" name="'.
 3251:                                       'actionlist" value="'.
 3252:                                       &HTML::Entities::encode($checkval,'&<>"').'" />');
 3253:                             foreach my $item ('start','end') {
 3254:                                 $r->print('<input type="hidden" name="'.
 3255:                                           &HTML::Entities::encode($checkval.'_'.$item,'&<>"').'"'.
 3256:                                           ' value="'.$sdata->[$index{$item}].'" />');
 3257:                             }
 3258:                             $r->print('</td>');
 3259:                         } else {
 3260:                             $r->print('<td>&nbsp;</td>');
 3261:                         }
 3262:                     } else {
 3263:                         $r->print('<td>&nbsp;</td>');
 3264:                     }
 3265:                 } elsif ($mode eq 'pickauthor') {
 3266:                         $r->print('<td><input type="button" name="chooseauthor" onclick="javascript:gochoose('."'$in{'username'}'".');" value="'.&mt('Select').'" /></td>');
 3267:                 }
 3268:             }
 3269:             foreach my $item (@cols) {
 3270:                 if ($item eq 'username') {
 3271:                     $r->print('<td>'.&print_username_link($mode,\%in).'</td>');
 3272:                 } elsif ($item eq 'status') {
 3273:                     my $showitem = $in{$item};
 3274:                     if (defined($ltstatus{$in{$item}})) {
 3275:                         $showitem = $ltstatus{$in{$item}};
 3276:                     }
 3277:                     $r->print('<td>'.$showitem.'</td>'."\n");
 3278:                 } elsif ($item eq 'photo') {
 3279:                      if (($context eq 'course') && ($mode ne 'autoenroll') && 
 3280:                          ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'})) { 
 3281:                          if ($role eq 'st') {
 3282:                              $r->print('<td align="right"><a href="javascript:photowindow('."'".$in{'photo'}."'".')"><img src="'.$in{'thumbnail'}.'" border="1" alt="" /></a></td>');
 3283:                          } else {
 3284:                              $r->print('<td>&nbsp;</td>');
 3285:                          }
 3286:                      }
 3287:                 } elsif ($item eq 'clicker') {
 3288:                     if (($context eq 'course') && ($mode ne 'autoenroll')) {
 3289:                         if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
 3290:                             my $clickers =
 3291:                    (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
 3292:                             if ($clickers!~/\w/) { $clickers='-'; }
 3293:                             $r->print('<td>'.$clickers.'</td>');
 3294:                         } else {
 3295:                              $r->print('<td>&nbsp;</td>'."\n");
 3296:                         } 
 3297:                     }
 3298:                 } elsif (($item eq 'authorquota') || ($item eq 'authorusage')) {
 3299:                     $r->print('<td align="right">'.$in{$item}.'</td>'."\n");
 3300:                 } else {
 3301:                     $r->print('<td>'.$in{$item}.'</td>'."\n");
 3302:                 }
 3303:             }
 3304:             $r->print(&Apache::loncommon::end_data_table_row());
 3305:         } elsif ($mode eq 'csv') {
 3306:             next if (! defined($CSVfile));
 3307:             # no need to bother with $linkto
 3308:             my @line = ();
 3309:             foreach my $item (@cols) {
 3310:                 push @line,&Apache::loncommon::csv_translate($in{$item});
 3311:             }
 3312:             print $CSVfile '"'.join('","',@line)."\"\n";
 3313:         } elsif ($mode eq 'excel') {
 3314:             my $col = 0;
 3315:             foreach my $item (@cols) {
 3316:                 if ($item eq 'start' || $item eq 'end') {
 3317:                     if ((defined($in{$item})) && ($in{$item} != 0)) {
 3318:                         $excel_sheet->write($row,$col++,
 3319:                             &Apache::lonstathelpers::calc_serial($in{$item}),
 3320:                                     $format->{'date'});
 3321:                     } else {
 3322:                         $excel_sheet->write($row,$col++,'none');
 3323:                     }
 3324:                 } else {
 3325:                     $excel_sheet->write($row,$col++,$in{$item});
 3326:                 }
 3327:             }
 3328:             $row++;
 3329:         }
 3330:     }
 3331:     if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
 3332:             $r->print(&Apache::loncommon::end_data_table().'<br />');
 3333:     } elsif ($mode eq 'excel') {
 3334:         $excel_workbook->close();
 3335: 	$r->print('<p>'.&mt('[_1]Your Excel spreadsheet[_2] is ready for download.', '<a href="'.$excel_filename.'">','</a>')."</p>\n");
 3336:     } elsif ($mode eq 'csv') {
 3337:         close($CSVfile);
 3338: 	$r->print('<p>'.&mt('[_1]Your CSV file[_2] is ready for download.', '<a href="'.$CSVfilename.'">','</a>')."</p>\n");
 3339:         $r->rflush();
 3340:     }
 3341:     if ($mode eq 'autoenroll') {
 3342:         return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
 3343:     } else {
 3344:         return ($usercount);
 3345:     }
 3346: }
 3347: 
 3348: sub bulkaction_javascript {
 3349:     my ($formname,$caller) = @_;
 3350:     my $docstart = 'document';
 3351:     if ($caller eq 'popup') {
 3352:         $docstart = 'opener.document';
 3353:     }
 3354:     my %lt = &Apache::lonlocal::texthash(
 3355:               acwi => 'Access will be set to start immediately',
 3356:               asyo => 'as you did not select an end date in the pop-up window',
 3357:               accw => 'Access will be set to continue indefinitely',
 3358:               asyd => 'as you did not select an end date in the pop-up window',
 3359:               sewi => "Sections will be switched to 'No section'",
 3360:               ayes => "as you either selected the 'No section' option",
 3361:               oryo => 'or you did not select a section in the pop-up window',
 3362:               arol => 'A role with no section will be added',
 3363:               swbs => 'Sections will be switched to:',
 3364:               rwba => 'Roles will be added for section(s):',
 3365:             );
 3366:     my $alert = &mt("You must select at least one user by checking a user's 'Select' checkbox");
 3367:     my $noaction = &mt("You need to select an action to take for the user(s) you have selected"); 
 3368:     my $singconfirm = &mt(' for a single user?');
 3369:     my $multconfirm = &mt(' for multiple users?');
 3370:     &js_escape(\$alert);
 3371:     &js_escape(\$noaction);
 3372:     &js_escape(\$singconfirm);
 3373:     &js_escape(\$multconfirm);
 3374:     my $output = <<"ENDJS";
 3375: function verify_action (field) {
 3376:     var numchecked = 0;
 3377:     var singconf = '$singconfirm';
 3378:     var multconf = '$multconfirm';
 3379:     if ($docstart.$formname.elements[field].length > 0) {
 3380:         for (i=0; i<$docstart.$formname.elements[field].length; i++) {
 3381:             if ($docstart.$formname.elements[field][i].checked == true) {
 3382:                numchecked ++;
 3383:             }
 3384:         }
 3385:     } else {
 3386:         if ($docstart.$formname.elements[field].checked == true) {
 3387:             numchecked ++;
 3388:         }
 3389:     }
 3390:     if (numchecked == 0) {
 3391:         alert("$alert");
 3392:         return;
 3393:     } else {
 3394:         var message = $docstart.$formname.bulkaction[$docstart.$formname.bulkaction.selectedIndex].text;
 3395:         var choice = $docstart.$formname.bulkaction[$docstart.$formname.bulkaction.selectedIndex].value;
 3396:         if (choice == '') {
 3397:             alert("$noaction");
 3398:             return;
 3399:         } else {
 3400:             if (numchecked == 1) {
 3401:                 message += singconf;
 3402:             } else {
 3403:                 message += multconf;
 3404:             }
 3405: ENDJS
 3406:     if ($caller ne 'popup') {
 3407:         $output .= <<"NEWWIN";
 3408:             if (choice == 'chgdates' || choice == 'reenable' || choice == 'activate' || choice == 'chgsec') {
 3409:                 opendatebrowser(document.$formname,'$formname','go');
 3410:                 return;
 3411: 
 3412:             } else {
 3413:                 if (confirm(message)) {
 3414:                     document.$formname.phase.value = 'bulkchange';
 3415:                     document.$formname.submit();
 3416:                     return;
 3417:                 }
 3418:             }
 3419: NEWWIN
 3420:     } else {
 3421:         $output .= <<"POPUP";
 3422:             if (choice == 'chgdates' || choice == 'reenable' || choice == 'activate') {
 3423:                 var datemsg = '';
 3424:                 if (($docstart.$formname.startdate_month.value == '') &&
 3425:                     ($docstart.$formname.startdate_day.value  == '') &&
 3426:                     ($docstart.$formname.startdate_year.value == '')) {
 3427:                     datemsg = "\\n$lt{'acwi'},\\n$lt{'asyo'}.\\n";
 3428:                 }
 3429:                 if (($docstart.$formname.enddate_month.value == '') &&
 3430:                     ($docstart.$formname.enddate_day.value  == '') &&
 3431:                     ($docstart.$formname.enddate_year.value == '')) {
 3432:                     datemsg += "\\n$lt{'accw'},\\n$lt{'asyd'}.\\n";
 3433:                 }
 3434:                 if (datemsg != '') {
 3435:                     message += "\\n"+datemsg;
 3436:                 }
 3437:             }
 3438:             if (choice == 'chgsec') {
 3439:                 var rolefilter = $docstart.$formname.showrole.options[$docstart.$formname.showrole.selectedIndex].value;
 3440:                 var retained =  $docstart.$formname.retainsec.value;
 3441:                 var secshow = $docstart.$formname.newsecs.value;
 3442:                 if (secshow == '') {
 3443:                     if (rolefilter == 'st' || retained == 0 || retained == "") {
 3444:                         message += "\\n\\n$lt{'sewi'},\\n$lt{'ayes'},\\n$lt{'oryo'}.\\n";
 3445:                     } else {
 3446:                         message += "\\n\\n$lt{'arol'}\\n$lt{'ayes'},\\n$lt{'oryo'}.\\n";
 3447:                     }
 3448:                 } else {
 3449:                     if (rolefilter == 'st' || retained == 0 || retained == "") {
 3450:                         message += "\\n\\n$lt{'swbs'} "+secshow+".\\n";
 3451:                     } else {
 3452:                         message += "\\n\\n$lt{'rwba'} "+secshow+".\\n";
 3453:                     }
 3454:                 }
 3455:             }
 3456:             if (confirm(message)) {
 3457:                 $docstart.$formname.phase.value = 'bulkchange';
 3458:                 $docstart.$formname.submit();
 3459:                 window.close();
 3460:             }
 3461: POPUP
 3462:     }
 3463:     $output .= '
 3464:         }
 3465:     }
 3466: }
 3467: ';
 3468:     return $output;
 3469: }
 3470: 
 3471: sub print_username_link {
 3472:     my ($mode,$in) = @_;
 3473:     my $output;
 3474:     if ($mode eq 'autoenroll') {
 3475:         $output = $in->{'username'};
 3476:     } else {
 3477:         $output = '<a href="javascript:username_display_launch('.
 3478:                   "'$in->{'username'}','$in->{'domain'}'".')">'.
 3479:                   $in->{'username'}.'</a>';
 3480:     }
 3481:     return $output;
 3482: }
 3483: 
 3484: sub role_type_names {
 3485:     my %lt = &Apache::lonlocal::texthash (
 3486:                          'domain' => 'Domain Roles',
 3487:                          'author' => 'Co-Author Roles',
 3488:                          'course' => 'Course Roles',
 3489:                          'community' => 'Community Roles',
 3490:              );
 3491:     return %lt;
 3492: }
 3493: 
 3494: sub select_actions {
 3495:     my ($context,$setting,$statusmode,$formname) = @_;
 3496:     my %lt = &Apache::lonlocal::texthash(
 3497:                 revoke   => "Revoke user roles",
 3498:                 delete   => "Delete user roles",
 3499:                 reenable => "Re-enable expired user roles",
 3500:                 activate => "Make future user roles active now",
 3501:                 chgdates  => "Change starting/ending dates",
 3502:                 chgsec   => "Change section associated with user roles",
 3503:     );
 3504:     # FIXME Add an option to change credits for student roles.
 3505:     my ($output,$options,%choices);
 3506:     # FIXME Disable actions for now for roletype=course in domain context
 3507:     if ($context eq 'domain' && $setting eq 'course') {
 3508:         return;
 3509:     }
 3510:     if ($context eq 'course') {
 3511:         if ($env{'form.showrole'} ne 'Any') {
 3512:             my $showactions;
 3513:             if (&Apache::lonnet::allowed('c'.$env{'form.showrole'},
 3514:                                           $env{'request.course.id'})) {
 3515:                 $showactions = 1;  
 3516:             } elsif ($env{'request.course.sec'} ne '') {
 3517:                 if (&Apache::lonnet::allowed('c'.$env{'form.showrole'},$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
 3518:                     $showactions = 1;
 3519:                 }
 3520:             }
 3521:             unless ($showactions) {
 3522:                 unless (&is_courseowner($env{'request.course.id'},
 3523:                                        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'})) {
 3524:                     return; 
 3525:                 }
 3526:             }
 3527:         }
 3528:     }
 3529:     if ($statusmode eq 'Any') {
 3530:         $options .= '
 3531: <option value="chgdates">'.$lt{'chgdates'}.'</option>';
 3532:         $choices{'dates'} = 1;
 3533:     } else {
 3534:         if ($statusmode eq 'Future') {
 3535:             $options .= '
 3536: <option value="activate">'.$lt{'activate'}.'</option>';
 3537:             $choices{'dates'} = 1;
 3538:         } elsif ($statusmode eq 'Expired') {
 3539:             $options .= '
 3540: <option value="reenable">'.$lt{'reenable'}.'</option>';
 3541:             $choices{'dates'} = 1;
 3542:         }
 3543:         if ($statusmode eq 'Active' || $statusmode eq 'Future') {
 3544:             $options .= '
 3545: <option value="chgdates">'.$lt{'chgdates'}.'</option>
 3546: <option value="revoke">'.$lt{'revoke'}.'</option>';
 3547:             $choices{'dates'} = 1;
 3548:         }
 3549:     }
 3550:     if ($context eq 'domain') {
 3551:         $options .= '
 3552: <option value="delete">'.$lt{'delete'}.'</option>';
 3553:     }
 3554:     if (($context eq 'course') || ($context eq 'domain' && $setting eq 'course')) {
 3555:         if (($statusmode ne 'Expired') && ($env{'request.course.sec'} eq '')) {
 3556:             $options .= '
 3557: <option value="chgsec">'.$lt{'chgsec'}.'</option>';
 3558:             $choices{'sections'} = 1;
 3559:         }
 3560:     }
 3561:     if ($options) {
 3562:         $output = '<select name="bulkaction">'."\n".
 3563:                   '<option value="" selected="selected">'.
 3564:                   &mt('Please select').'</option>'."\n".$options."\n".'</select>';
 3565:         if ($choices{'dates'}) {
 3566:             $output .= 
 3567:                 '<input type="hidden" name="startdate_month" value="" />'."\n".
 3568:                 '<input type="hidden" name="startdate_day" value="" />'."\n".
 3569:                 '<input type="hidden" name="startdate_year" value="" />'."\n".
 3570:                 '<input type="hidden" name="startdate_hour" value="" />'."\n".
 3571:                 '<input type="hidden" name="startdate_minute" value="" />'."\n".
 3572:                 '<input type="hidden" name="startdate_second" value="" />'."\n".
 3573:                 '<input type="hidden" name="enddate_month" value="" />'."\n".
 3574:                 '<input type="hidden" name="enddate_day" value="" />'."\n".
 3575:                 '<input type="hidden" name="enddate_year" value="" />'."\n".
 3576:                 '<input type="hidden" name="enddate_hour" value="" />'."\n".
 3577:                 '<input type="hidden" name="enddate_minute" value="" />'."\n".
 3578:                 '<input type="hidden" name="enddate_second" value="" />'."\n".
 3579:                 '<input type="hidden" name="no_end_date" value="" />'."\n";
 3580:             if ($context eq 'course') {
 3581:                 $output .= '<input type="hidden" name="makedatesdefault" value="" />'."\n";
 3582:             }
 3583:         }
 3584:         if ($choices{'sections'}) {
 3585:             $output .= '<input type="hidden" name="retainsec" value="" />'."\n".
 3586:                        '<input type="hidden" name="newsecs" value="" />'."\n";
 3587:         }
 3588:     }
 3589:     return $output;
 3590: }
 3591: 
 3592: sub date_section_javascript {
 3593:     my ($context,$setting) = @_;
 3594:     my $title = 'Date_And_Section_Selector';
 3595:     my %nopopup = &Apache::lonlocal::texthash (
 3596:         revoke => "Check the boxes for any users for whom roles are to be revoked, and click 'Proceed'",
 3597:         delete => "Check the boxes for any users for whom roles are to be deleted, and click 'Proceed'",
 3598:         none   => "Choose an action to take for selected users",
 3599:     );  
 3600:     my $output = <<"ENDONE";
 3601: <script type="text/javascript">
 3602: // <![CDATA[
 3603:     function opendatebrowser(callingform,formname,calledby) {
 3604:         var bulkaction = callingform.bulkaction.options[callingform.bulkaction.selectedIndex].value;
 3605:         var url = '/adm/createuser?';
 3606:         var type = '';
 3607:         var showrole = callingform.showrole.options[callingform.showrole.selectedIndex].value;
 3608: ENDONE
 3609:     if ($context eq 'domain') {
 3610:         $output .= '
 3611:         type = callingform.roletype.options[callingform.roletype.selectedIndex].value;
 3612: ';
 3613:     }
 3614:     my $width= '700';
 3615:     my $height = '400';
 3616:     $output .= <<"ENDTWO";
 3617:         url += 'action=dateselect&callingform=' + formname + 
 3618:                '&roletype='+type+'&showrole='+showrole +'&bulkaction='+bulkaction;
 3619:         var title = '$title';
 3620:         var options = 'scrollbars=1,resizable=1,menubar=0';
 3621:         options += ',width=$width,height=$height';
 3622:         stdeditbrowser = open(url,title,options,'1');
 3623:         stdeditbrowser.focus();
 3624:     }
 3625: // ]]>
 3626: </script>
 3627: ENDTWO
 3628:     return $output;
 3629: }
 3630: 
 3631: sub date_section_selector {
 3632:     my ($context,$permission,$crstype,$showcredits) = @_;
 3633:     my $callingform = $env{'form.callingform'};
 3634:     my $formname = 'dateselect';  
 3635:     my $groupslist = &get_groupslist();
 3636:     my $sec_js =
 3637:         &setsections_javascript($formname,$groupslist,undef,undef,$crstype,
 3638:                                 $showcredits);
 3639:     my $output = <<"END";
 3640: <script type="text/javascript">
 3641: // <![CDATA[
 3642: 
 3643: $sec_js
 3644: 
 3645: function saveselections(formname) {
 3646: 
 3647: END
 3648:     if ($env{'form.bulkaction'} eq 'chgsec') {
 3649:         $output .= <<"END";
 3650:         if (formname.retainsec.length > 1) {  
 3651:             for (var i=0; i<formname.retainsec.length; i++) {
 3652:                 if (formname.retainsec[i].checked == true) {
 3653:                     opener.document.$callingform.retainsec.value = formname.retainsec[i].value;
 3654:                 }
 3655:             }
 3656:         } else {
 3657:             opener.document.$callingform.retainsec.value = formname.retainsec.value;
 3658:         }
 3659:         setSections(formname,'$crstype');
 3660:         if (seccheck == 'ok') {
 3661:             opener.document.$callingform.newsecs.value = formname.sections.value;
 3662:         }
 3663: END
 3664:     } else {
 3665:         if ($context eq 'course') {
 3666:             if (($env{'form.bulkaction'} eq 'reenable') || 
 3667:                 ($env{'form.bulkaction'} eq 'activate') || 
 3668:                 ($env{'form.bulkaction'} eq 'chgdates')) {
 3669:                 if ($env{'request.course.sec'} eq '') {
 3670:                     $output .= <<"END";
 3671:  
 3672:         if (formname.makedatesdefault.checked == true) {
 3673:             opener.document.$callingform.makedatesdefault.value = 1;
 3674:         }
 3675:         else {
 3676:             opener.document.$callingform.makedatesdefault.value = 0;
 3677:         }
 3678: 
 3679: END
 3680:                 }
 3681:             }
 3682:         }
 3683:         $output .= <<"END";
 3684:     opener.document.$callingform.startdate_month.value =  formname.startdate_month.options[formname.startdate_month.selectedIndex].value;
 3685:     opener.document.$callingform.startdate_day.value =  formname.startdate_day.value;
 3686:     opener.document.$callingform.startdate_year.value = formname.startdate_year.value;
 3687:     opener.document.$callingform.startdate_hour.value =  formname.startdate_hour.options[formname.startdate_hour.selectedIndex].value;
 3688:     opener.document.$callingform.startdate_minute.value =  formname.startdate_minute.value;
 3689:     opener.document.$callingform.startdate_second.value = formname.startdate_second.value;
 3690:     opener.document.$callingform.enddate_month.value =  formname.enddate_month.options[formname.enddate_month.selectedIndex].value;
 3691:     opener.document.$callingform.enddate_day.value =  formname.enddate_day.value;
 3692:     opener.document.$callingform.enddate_year.value = formname.enddate_year.value;
 3693:     opener.document.$callingform.enddate_hour.value =  formname.enddate_hour.options[formname.enddate_hour.selectedIndex].value;
 3694:     opener.document.$callingform.enddate_minute.value =  formname.enddate_minute.value;
 3695:     opener.document.$callingform.enddate_second.value = formname.enddate_second.value;
 3696:     if (formname.no_end_date.checked) {
 3697:         opener.document.$callingform.no_end_date.value = '1';
 3698:     } else {
 3699:         opener.document.$callingform.no_end_date.value = '0';
 3700:     }
 3701: END
 3702:     }
 3703:     my $verify_action_js = &bulkaction_javascript($callingform,'popup');
 3704:     $output .= <<"ENDJS";
 3705:     verify_action('actionlist');
 3706: }
 3707: 
 3708: $verify_action_js
 3709: 
 3710: // ]]>
 3711: </script>
 3712: ENDJS
 3713:     my %lt = &Apache::lonlocal::texthash (
 3714:                  chac => 'Access dates to apply for selected users',
 3715:                  chse => 'Changes in section affiliation to apply to selected users',
 3716:                  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.',
 3717:                  forn => 'For a course role that is not "student", users may have roles in more than one section at a time.',
 3718:                  reta => "Retain each user's current section affiliations?",
 3719:                  dnap => '(Does not apply to student roles).',
 3720:             );
 3721:     my ($date_items,$headertext);
 3722:     if ($env{'form.bulkaction'} eq 'chgsec') {
 3723:         $headertext = $lt{'chse'};
 3724:     } else {
 3725:         $headertext = $lt{'chac'};
 3726:         my $starttime;
 3727:         if (($env{'form.bulkaction'} eq 'activate') || 
 3728:             ($env{'form.bulkaction'} eq 'reenable')) {
 3729:             $starttime = time;
 3730:         }
 3731:         $date_items = &date_setting_table($starttime,undef,$context,
 3732:                                           $env{'form.bulkaction'},$formname,
 3733:                                           $permission,$crstype);
 3734:     }
 3735:     $output .= '<h3>'.$headertext.'</h3>'.
 3736:                '<form name="'.$formname.'" method="post" action="">'."\n".
 3737:                 $date_items;
 3738:     if ($context eq 'course' && $env{'form.bulkaction'} eq 'chgsec') {
 3739:         my ($cnum,$cdom) = &get_course_identity();
 3740:         if ($crstype eq 'Community') {
 3741:             $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.');
 3742:             $lt{'forn'} = &mt('For a community role that is not "member", users may have roles in more than one section at a time.');
 3743:             $lt{'dnap'} = &mt('(Does not apply to member roles).'); 
 3744:         }
 3745:         my $info;
 3746:         if ($env{'form.showrole'} eq 'st') {
 3747:             $output .= '<p>'.$lt{'fors'}.'</p>'; 
 3748:         } elsif ($env{'form.showrole'} eq 'Any') {
 3749:             $output .= '<p>'.$lt{'fors'}.'</p>'.
 3750:                        '<p>'.$lt{'forn'}.'&nbsp;';
 3751:             $info = $lt{'reta'};
 3752:         } else {
 3753:             $output .= '<p>'.$lt{'forn'}.'&nbsp;';
 3754:             $info = $lt{'reta'};
 3755:         }
 3756:         if ($info) {
 3757:             $info .= '<span class="LC_nobreak">'.
 3758:                      '<label><input type="radio" name="retainsec" value="1" '.
 3759:                      'checked="checked" />'.&mt('Yes').'</label>&nbsp;&nbsp;'.
 3760:                      '<label><input type="radio" name="retainsec" value="0" />'.
 3761:                      &mt('No').'</label></span>';
 3762:             if ($env{'form.showrole'} eq 'Any') {
 3763:                 $info .= '<br />'.$lt{'dnap'};
 3764:             }
 3765:             $info .= '</p>';
 3766:         } else {
 3767:             $info = '<input type="hidden" name="retainsec" value="0" />'; 
 3768:         }
 3769:         my $rowtitle = &mt('New section to assign');
 3770:         my $secbox = &section_picker($cdom,$cnum,$env{'form.showrole'},$rowtitle,
 3771:                                      $permission,$context,'chgsec',$crstype);
 3772:         $output .= $info.$secbox;
 3773:     }
 3774:     $output .= '<p>'.
 3775: '<input type="button" name="dateselection" value="'.&mt('Save').'" onclick="javascript:saveselections(this.form)" /></p>'."\n".
 3776: '</form>';
 3777:     return $output;
 3778: }
 3779: 
 3780: sub section_picker {
 3781:     my ($cdom,$cnum,$role,$rowtitle,$permission,$context,$mode,$crstype,
 3782:         $showcredits,$credits) = @_;
 3783:     my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 3784:     my $sections_select .= &course_sections(\%sections_count,$role);
 3785:     my $secbox = '<div>'.&Apache::lonhtmlcommon::start_pick_box()."\n";
 3786:     if ($mode eq 'upload') {
 3787:         my ($options,$cb_script,$coursepick) =
 3788:             &default_role_selector($context,1,$crstype,$showcredits);
 3789:         $secbox .= &Apache::lonhtmlcommon::row_title(&mt('role'),'LC_oddrow_value').
 3790:                    $options. &Apache::lonhtmlcommon::row_closure(1)."\n";
 3791:     }
 3792:     $secbox .= &Apache::lonhtmlcommon::row_title($rowtitle,'LC_oddrow_value')."\n";
 3793:     if ($env{'request.course.sec'} eq '') {
 3794:         $secbox .= '<table class="LC_createuser"><tr class="LC_section_row">'."\n".
 3795:                    '<td align="center">'.&mt('Existing sections')."\n".
 3796:                    '<br />'.$sections_select.'</td><td align="center">'.
 3797:                    &mt('New section').'<br />'."\n".
 3798:                    '<input type="text" name="newsec" size="15" value="" />'."\n".
 3799:                    '<input type="hidden" name="sections" value="" />'."\n".
 3800:                    '</td></tr></table>'."\n";
 3801:     } else {
 3802:         $secbox .= '<input type="hidden" name="sections" value="'.
 3803:                    $env{'request.course.sec'}.'" />'.
 3804:                    $env{'request.course.sec'};
 3805:     }
 3806:     $secbox .= &Apache::lonhtmlcommon::row_closure(1)."\n";
 3807:     unless ($mode eq 'chgsec') {
 3808:         if ($showcredits) {
 3809:             $secbox .= 
 3810:                 &Apache::lonhtmlcommon::row_title(&mt('credits (students)'),
 3811:                                                   'LC_evenrow_value')."\n".
 3812:                 '<input type="text" name="credits" size="3" value="'.$credits.'" />'."\n".
 3813:                 &Apache::lonhtmlcommon::row_closure(1)."\n";
 3814:         }
 3815:     }
 3816:     $secbox .= &Apache::lonhtmlcommon::end_pick_box().'</div>';
 3817:     return $secbox;
 3818: }
 3819: 
 3820: sub results_header_row {
 3821:     my ($rolefilter,$statusmode,$context,$permission,$mode,$crstype) = @_;
 3822:     my ($description,$showfilter);
 3823:     if ($rolefilter ne 'Any') {
 3824:         $showfilter = $rolefilter;
 3825:     }
 3826:     if ($context eq 'course') {
 3827:         if ($mode eq 'csv' || $mode eq 'excel') {
 3828:             if ($crstype eq 'Community') {
 3829:                 $description = &mt('Community - [_1]:',$env{'course.'.$env{'request.course.id'}.'.description'}).' ';
 3830:             } else {
 3831:                 $description = &mt('Course - [_1]:',$env{'course.'.$env{'request.course.id'}.'.description'}).' ';
 3832:             }
 3833:         }
 3834:         if ($statusmode eq 'Expired') {
 3835:             if ($crstype eq 'Community') {
 3836:                 $description .= &mt('Users in community with expired [_1] roles',$showfilter);
 3837:             } else {
 3838:                 $description .= &mt('Users in course with expired [_1] roles',$showfilter);
 3839:             }
 3840:         } elsif ($statusmode eq 'Future') {
 3841:             if ($crstype eq 'Community') {
 3842:                 $description .= &mt('Users in community with future [_1] roles',$showfilter);
 3843:             } else {
 3844:                 $description .= &mt('Users in course with future [_1] roles',$showfilter);
 3845:             }
 3846:         } elsif ($statusmode eq 'Active') {
 3847:             if ($crstype eq 'Community') {
 3848:                 $description .= &mt('Users in community with active [_1] roles',$showfilter);
 3849:             } else {
 3850:                 $description .= &mt('Users in course with active [_1] roles',$showfilter);
 3851:             }
 3852:         } else {
 3853:             if ($rolefilter eq 'Any') {
 3854:                 if ($crstype eq 'Community') {
 3855:                     $description .= &mt('All users in community');
 3856:                 } else {
 3857:                     $description .= &mt('All users in course');
 3858:                 }
 3859:             } else {
 3860:                 if ($crstype eq 'Community') {
 3861:                     $description .= &mt('All users in community with [_1] roles',$rolefilter);
 3862:                 } else {
 3863:                     $description .= &mt('All users in course with [_1] roles',$rolefilter);
 3864:                 }
 3865:             }
 3866:         }
 3867:         my $constraint;
 3868:         my $viewablesec = &viewable_section($permission);
 3869:         if ($viewablesec ne '') {
 3870:             if ($env{'form.showrole'} eq 'st') {
 3871:                 $constraint = &mt('only users in section "[_1]"',$viewablesec);
 3872:             } elsif (($env{'form.showrole'} ne 'cc') && ($env{'form.showrole'} ne 'co')) {
 3873:                 $constraint = &mt('only users affiliated with no section or section "[_1]"',$viewablesec);
 3874:             }
 3875:             if (($env{'form.grpfilter'} ne 'all') && ($env{'form.grpfilter'} ne '')) {
 3876:                 if ($env{'form.grpfilter'} eq 'none') {
 3877:                     $constraint .= &mt(' and not in any group');
 3878:                 } else {
 3879:                     $constraint .= &mt(' and members of group: "[_1]"',$env{'form.grpfilter'});
 3880:                 }
 3881:             }
 3882:         } else {
 3883:             if (($env{'form.secfilter'} ne 'all') && ($env{'form.secfilter'} ne '')) {
 3884:                 if ($env{'form.secfilter'} eq 'none') {
 3885:                     $constraint = &mt('only users affiliated with no section');
 3886:                 } else {
 3887:                     $constraint = &mt('only users affiliated with section "[_1]"',$env{'form.secfilter'});
 3888:                 }
 3889:             }
 3890:             if (($env{'form.grpfilter'} ne 'all') && ($env{'form.grpfilter'} ne '')) {
 3891:                 if ($env{'form.grpfilter'} eq 'none') {
 3892:                     if ($constraint eq '') {
 3893:                         $constraint = &mt('only users not in any group');
 3894:                     } else {
 3895:                         $constraint .= &mt(' and also not in any group'); 
 3896:                     }
 3897:                 } else {
 3898:                     if ($constraint eq '') {
 3899:                         $constraint = &mt('only members of group: "[_1]"',$env{'form.grpfilter'});
 3900:                     } else {
 3901:                         $constraint .= &mt(' and also members of group: "[_1]"'.$env{'form.grpfilter'});
 3902:                     }
 3903:                 }
 3904:             }
 3905:         }
 3906:         if ($constraint ne '') {
 3907:             $description .= ' ('.$constraint.')';
 3908:         } 
 3909:     } elsif ($context eq 'author') {
 3910:         $description = 
 3911:             &mt('Author space for [_1]'
 3912:                 ,'<span class="LC_cusr_emph">'
 3913:                 .&Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'})
 3914:                 .'</span>')
 3915:             .':&nbsp;&nbsp;';
 3916:         if ($statusmode eq 'Expired') {
 3917:             $description .= &mt('Co-authors with expired [_1] roles',$showfilter);
 3918:         } elsif ($statusmode eq 'Future') {
 3919:             $description .= &mt('Co-authors with future [_1] roles',$showfilter);
 3920:         } elsif ($statusmode eq 'Active') {
 3921:             $description .= &mt('Co-authors with active [_1] roles',$showfilter);
 3922:         } else {
 3923:             if ($rolefilter eq 'Any') {
 3924:                 $description .= &mt('All co-authors');
 3925:             } else {
 3926:                 $description .= &mt('All co-authors with [_1] roles',$rolefilter);
 3927:             }
 3928:         }
 3929:     } elsif ($context eq 'domain') {
 3930:         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 3931:         $description = &mt('Domain - [_1]:',$domdesc).' ';
 3932:         if ($env{'form.roletype'} eq 'domain') {
 3933:             if ($statusmode eq 'Expired') {
 3934:                 $description .= &mt('Users in domain with expired [_1] roles',$showfilter);
 3935:             } elsif ($statusmode eq 'Future') {
 3936:                 $description .= &mt('Users in domain with future [_1] roles',$showfilter);
 3937:             } elsif ($statusmode eq 'Active') {
 3938:                 $description .= &mt('Users in domain with active [_1] roles',$showfilter);
 3939:             } else {
 3940:                 if ($rolefilter eq 'Any') {
 3941:                     $description .= &mt('All users in domain');
 3942:                 } else {
 3943:                     $description .= &mt('All users in domain with [_1] roles',$rolefilter);
 3944:                 }
 3945:             }
 3946:         } elsif ($env{'form.roletype'} eq 'author') {
 3947:             if ($statusmode eq 'Expired') {
 3948:                 $description .= &mt('Co-authors in domain with expired [_1] roles',$showfilter);
 3949:             } elsif ($statusmode eq 'Future') {
 3950:                 $description .= &mt('Co-authors in domain with future [_1] roles',$showfilter);
 3951:             } elsif ($statusmode eq 'Active') {
 3952:                $description .= &mt('Co-authors in domain with active [_1] roles',$showfilter);
 3953:             } else {
 3954:                 if ($rolefilter eq 'Any') {
 3955:                     $description .= &mt('All users with co-author roles in domain',$showfilter);
 3956:                 } else {
 3957:                     $description .= &mt('All co-authors in domain with [_1] roles',$rolefilter);
 3958:                 }
 3959:             }
 3960:         } elsif (($env{'form.roletype'} eq 'course') || 
 3961:                  ($env{'form.roletype'} eq 'community')) {
 3962:             my $coursefilter = $env{'form.coursepick'};
 3963:             if ($env{'form.roletype'} eq 'course') {
 3964:                 if ($coursefilter eq 'category') {
 3965:                     my $instcode = &instcode_from_coursefilter();
 3966:                     if ($instcode eq '.') {
 3967:                         $description .= &mt('All courses in domain').' - ';
 3968:                     } else {
 3969:                         $description .= &mt('Courses in domain with institutional code: [_1]',$instcode).' - ';
 3970:                     }
 3971:                 } elsif ($coursefilter eq 'selected') {
 3972:                     $description .= &mt('Selected courses in domain').' - ';
 3973:                 } elsif ($coursefilter eq 'all') {
 3974:                     $description .= &mt('All courses in domain').' - ';
 3975:                 }
 3976:             } elsif ($env{'form.roletype'} eq 'community') {
 3977:                 if ($coursefilter eq 'selected') {
 3978:                     $description .= &mt('Selected communities in domain').' - ';
 3979:                 } elsif ($coursefilter eq 'all') {
 3980:                     $description .= &mt('All communities in domain').' - ';
 3981:                 }
 3982:             }
 3983:             if ($statusmode eq 'Expired') {
 3984:                 $description .= &mt('users with expired [_1] roles',$showfilter);
 3985:             } elsif ($statusmode eq 'Future') {
 3986:                 $description .= &mt('users with future [_1] roles',$showfilter);
 3987:             } elsif ($statusmode eq 'Active') {
 3988:                 $description .= &mt('users with active [_1] roles',$showfilter);
 3989:             } else {
 3990:                 if ($rolefilter eq 'Any') {
 3991:                     $description .= &mt('all users');
 3992:                 } else {
 3993:                     $description .= &mt('users with [_1] roles',$rolefilter);
 3994:                 }
 3995:             }
 3996:         }
 3997:     }
 3998:     return $description;
 3999: }
 4000: 
 4001: sub viewable_section {
 4002:     my ($permission) = @_;
 4003:     my $viewablesec;
 4004:     if (ref($permission) eq 'HASH') {
 4005:         if (exists($permission->{'view_section'})) {
 4006:             $viewablesec = $permission->{'view_section'};
 4007:         } elsif (exists($permission->{'cusr_section'})) {
 4008:             $viewablesec = $permission->{'cusr_section'};
 4009:         }
 4010:     }
 4011:     return $viewablesec;
 4012: }
 4013: 
 4014:     
 4015: #################################################
 4016: #################################################
 4017: sub show_drop_list {
 4018:     my ($r,$classlist,$nosort,$permission,$crstype) = @_;
 4019:     my $cid = $env{'request.course.id'};
 4020:     my ($cnum,$cdom) = &get_course_identity($cid);
 4021:     if (! exists($env{'form.sortby'})) {
 4022:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4023:                                                 ['sortby']);
 4024:     }
 4025:     my $sortby = $env{'form.sortby'};
 4026:     if ($sortby !~ /^(username|domain|section|groups|fullname|id|start|end)$/) {
 4027:         $sortby = 'username';
 4028:     }
 4029:     my $action = "drop";
 4030:     my $check_uncheck_js = &Apache::loncommon::check_uncheck_jscript();
 4031:     $r->print(<<END);
 4032: <input type="hidden" name="sortby" value="$sortby" />
 4033: <input type="hidden" name="action" value="$action" />
 4034: <input type="hidden" name="state"  value="done" />
 4035: <script type="text/javascript" language="Javascript">
 4036: // <![CDATA[
 4037: $check_uncheck_js
 4038: // ]]>
 4039: </script>
 4040: <input type="hidden" name="phase" value="four" />
 4041: END
 4042:     my ($indexhash,$keylist) = &make_keylist_array();
 4043:     my $studentcount = 0;
 4044:     if (ref($classlist) eq 'HASH') {
 4045:         foreach my $student (keys(%{$classlist})) {
 4046:             my $sdata = $classlist->{$student}; 
 4047:             my $status = $sdata->[$indexhash->{'status'}];
 4048:             my $section = $sdata->[$indexhash->{'section'}];
 4049:             if ($status ne 'Active') {
 4050:                 delete($classlist->{$student});
 4051:                 next;
 4052:             }
 4053:             if ($env{'request.course.sec'} ne '') {
 4054:                 if ($section ne $env{'request.course.sec'}) {
 4055:                     delete($classlist->{$student});
 4056:                     next;
 4057:                 }
 4058:             }
 4059:             $studentcount ++;
 4060:         }
 4061:     }
 4062:     if (!$studentcount) {
 4063:        my $msg = '';
 4064:         if ($crstype eq 'Community') {
 4065:             $msg = &mt('There are no members to drop.');
 4066:         } else {
 4067:             $msg = &mt('There are no students to drop.');
 4068:         }
 4069:         $r->print('<p class="LC_info">'.$msg.'</p>');
 4070:         return;
 4071:     }
 4072:     my ($classgroups) = &Apache::loncoursedata::get_group_memberships(
 4073:                                               $classlist,$keylist,$cdom,$cnum);
 4074:     my %lt=&Apache::lonlocal::texthash('usrn'   => "username",
 4075:                                        'dom'    => "domain",
 4076:                                        'id'     => "ID",
 4077:                                        'sn'     => "student name",
 4078:                                        'mn'     => "member name",
 4079:                                        'sec'    => "section",
 4080:                                        'start'  => "start date",
 4081:                                        'end'    => "end date",
 4082:                                        'groups' => "active groups",
 4083:                                       );
 4084:     my $nametitle = $lt{'sn'};
 4085:     if ($crstype eq 'Community') {
 4086:         $nametitle = $lt{'mn'};
 4087:     }
 4088:     if ($nosort) {
 4089:         $r->print(&Apache::loncommon::start_data_table().
 4090:                   &Apache::loncommon::start_data_table_header_row());
 4091:         $r->print(<<END);
 4092:     <th>&nbsp;</th>
 4093:     <th>$lt{'usrn'}</th>
 4094:     <th>$lt{'dom'}</th>
 4095:     <th>$lt{'id'}</th>
 4096:     <th>$nametitle</th>
 4097:     <th>$lt{'sec'}</th>
 4098:     <th>$lt{'start'}</th>
 4099:     <th>$lt{'end'}</th>
 4100:     <th>$lt{'groups'}</th>
 4101: END
 4102:         $r->print(&Apache::loncommon::end_data_table_header_row());
 4103:     } else  {
 4104:         $r->print(&Apache::loncommon::start_data_table().
 4105:                   &Apache::loncommon::start_data_table_header_row());
 4106:         $r->print(<<END);
 4107:     <th>&nbsp;</th>
 4108:     <th>
 4109:        <a href="/adm/createuser?action=$action&amp;sortby=username">$lt{'usrn'}</a>
 4110:     </th><th>
 4111:        <a href="/adm/createuser?action=$action&amp;sortby=domain">$lt{'dom'}</a>
 4112:     </th><th>
 4113:        <a href="/adm/createuser?action=$action&amp;sortby=id">$lt{'id'}</a>
 4114:     </th><th>
 4115:        <a href="/adm/createuser?action=$action&amp;sortby=fullname">$nametitle</a>
 4116:     </th><th>
 4117:        <a href="/adm/createuser?action=$action&amp;sortby=section">$lt{'sec'}</a>
 4118:     </th><th>
 4119:        <a href="/adm/createuser?action=$action&amp;sortby=start">$lt{'start'}</a>
 4120:     </th><th>
 4121:        <a href="/adm/createuser?action=$action&amp;sortby=end">$lt{'end'}</a>
 4122:     </th><th>
 4123:        <a href="/adm/createuser?action=$action&amp;sortby=groups">$lt{'groups'}</a>
 4124:     </th>
 4125: END
 4126:         $r->print(&Apache::loncommon::end_data_table_header_row());
 4127:     }
 4128:     #
 4129:     # Sort the students
 4130:     my $index  = $indexhash->{$sortby};
 4131:     my $second = $indexhash->{'username'};
 4132:     my $third  = $indexhash->{'domain'};
 4133:     my @Sorted_Students = sort {
 4134:         lc($classlist->{$a}->[$index])  cmp lc($classlist->{$b}->[$index])
 4135:             ||
 4136:         lc($classlist->{$a}->[$second]) cmp lc($classlist->{$b}->[$second])
 4137:             ||
 4138:         lc($classlist->{$a}->[$third]) cmp lc($classlist->{$b}->[$third])
 4139:         } (keys(%{$classlist}));
 4140:     foreach my $student (@Sorted_Students) {
 4141:         my $error;
 4142:         my $sdata = $classlist->{$student};
 4143:         my $username = $sdata->[$indexhash->{'username'}];
 4144:         my $domain   = $sdata->[$indexhash->{'domain'}];
 4145:         my $section  = $sdata->[$indexhash->{'section'}];
 4146:         my $name     = $sdata->[$indexhash->{'fullname'}];
 4147:         my $id       = $sdata->[$indexhash->{'id'}];
 4148:         my $start    = $sdata->[$indexhash->{'start'}];
 4149:         my $end      = $sdata->[$indexhash->{'end'}];
 4150:         my $groups = $classgroups->{$student};
 4151:         my $active_groups;
 4152:         if (ref($groups->{active}) eq 'HASH') {
 4153:             $active_groups = join(', ',keys(%{$groups->{'active'}}));
 4154:         }
 4155:         if (! defined($start) || $start == 0) {
 4156:             $start = &mt('none');
 4157:         } else {
 4158:             $start = &Apache::lonlocal::locallocaltime($start);
 4159:         }
 4160:         if (! defined($end) || $end == 0) {
 4161:             $end = &mt('none');
 4162:         } else {
 4163:             $end = &Apache::lonlocal::locallocaltime($end);
 4164:         }
 4165:         my $studentkey = $student.':'.$section;
 4166:         my $startitem = '<input type="hidden" name="'.$studentkey.'_start" value="'.$sdata->[$indexhash->{'start'}].'" />';
 4167:         #
 4168:         $r->print(&Apache::loncommon::start_data_table_row());
 4169:         $r->print(<<"END");
 4170:     <td><input type="checkbox" name="droplist" value="$studentkey" /></td>
 4171:     <td>$username</td>
 4172:     <td>$domain</td>
 4173:     <td>$id</td>
 4174:     <td>$name</td>
 4175:     <td>$section</td>
 4176:     <td>$start $startitem</td>
 4177:     <td>$end</td>
 4178:     <td>$active_groups</td>
 4179: END
 4180:         $r->print(&Apache::loncommon::end_data_table_row());
 4181:     }
 4182:     $r->print(&Apache::loncommon::end_data_table().'<br />');
 4183:     %lt=&Apache::lonlocal::texthash(
 4184:                        'dp'   => "Drop Students",
 4185:                        'dm'   => "Drop Members",
 4186:                        'ca'   => "check all",
 4187:                        'ua'   => "uncheck all",
 4188:                                        );
 4189:     my $btn = $lt{'dp'};
 4190:     if ($crstype eq 'Community') {
 4191:         $btn = $lt{'dm'}; 
 4192:     }
 4193:     $r->print(<<"END");
 4194: <p>
 4195: <input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.droplist)" /> &nbsp;
 4196: <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.droplist)" />
 4197: </p>
 4198: <p>
 4199: <input type="submit" value="$btn" />
 4200: </p>
 4201: END
 4202:     return;
 4203: }
 4204: 
 4205: #
 4206: # Print out the initial form to get the file containing a list of users
 4207: #
 4208: sub print_first_users_upload_form {
 4209:     my ($r,$context) = @_;
 4210:     my $str;
 4211:     $str  = '<input type="hidden" name="phase" value="two" />';
 4212:     $str .= '<input type="hidden" name="action" value="upload" />';
 4213:     $str .= '<input type="hidden" name="state"  value="got_file" />';
 4214: 
 4215:     $str .= &Apache::grades::checkforfile_js();
 4216: 
 4217:     $str .= '<h2>'.&mt('Upload a file containing information about users').'</h2>'."\n";
 4218: 
 4219:     # Excel and CSV Help
 4220:     $str .= '<div class="LC_columnSection">'
 4221:            .&Apache::loncommon::help_open_topic("Course_Create_Class_List",
 4222:                 &mt("How do I create a users list from a spreadsheet"))
 4223:            .' '.&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
 4224:                 &mt("How do I create a CSV file from a spreadsheet"))
 4225:            ."</div>\n";
 4226:     $str .= &Apache::lonhtmlcommon::start_pick_box()
 4227:            .&Apache::lonhtmlcommon::row_title(&mt('File'));
 4228:     if (&Apache::lonlocal::current_language() ne 'en') {
 4229:         if ($context eq 'course') { 
 4230:             $str .= '<p class="LC_info">'."\n"
 4231:                    .&mt('Please upload an UTF8 encoded file to ensure a correct character encoding in your classlist.')."\n"
 4232:                    .'</p>'."\n";
 4233:         }
 4234:     }
 4235:     $str .= &Apache::loncommon::upfile_select_html()
 4236:            .&Apache::lonhtmlcommon::row_closure()
 4237:            .&Apache::lonhtmlcommon::row_title(
 4238:                 '<label for="noFirstLine">'
 4239:                .&mt('Ignore First Line')
 4240:                .'</label>')
 4241:            .'<input type="checkbox" name="noFirstLine" id="noFirstLine" />'
 4242:            .&Apache::lonhtmlcommon::row_closure(1)
 4243:            .&Apache::lonhtmlcommon::end_pick_box();
 4244: 
 4245:     $str .= '<p>'
 4246:            .'<input type="button" name="fileupload" value="'.&mt('Next').'"'
 4247:            .' onclick="javascript:checkUpload(this.form);" />'
 4248:            .'</p>';
 4249: 
 4250:     $r->print($str);
 4251:     return;
 4252: }
 4253: 
 4254: # ================================================= Drop/Add from uploaded file
 4255: sub upfile_drop_add {
 4256:     my ($r,$context,$permission,$showcredits) = @_;
 4257:     my $datatoken = &Apache::loncommon::valid_datatoken($env{'form.datatoken'});
 4258:     if ($datatoken ne '') {
 4259:         &Apache::loncommon::load_tmp_file($r,$datatoken);
 4260:     }
 4261:     my @userdata=&Apache::loncommon::upfile_record_sep();
 4262:     if($env{'form.noFirstLine'}){shift(@userdata);}
 4263:     my @keyfields = split(/\,/,$env{'form.keyfields'});
 4264:     my %fields=();
 4265:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
 4266:         if ($env{'form.upfile_associate'} eq 'reverse') {
 4267:             if ($env{'form.f'.$i} ne 'none') {
 4268:                 $fields{$keyfields[$i]}=$env{'form.f'.$i};
 4269:             }
 4270:         } else {
 4271:             $fields{$env{'form.f'.$i}}=$keyfields[$i];
 4272:         }
 4273:     }
 4274:     #
 4275:     # Store the field choices away
 4276:     my @storefields = qw/username names fname mname lname gen id 
 4277:                          sec ipwd email role domain inststatus/;
 4278:     if ($showcredits) {
 4279:         push (@storefields,'credits');
 4280:     }
 4281:     my %fieldstype; 
 4282:     foreach my $field (@storefields) {
 4283:         $env{'form.'.$field.'_choice'}=$fields{$field};
 4284:         $fieldstype{$field.'_choice'} = 'scalar';
 4285:     }
 4286:     &Apache::loncommon::store_course_settings('enrollment_upload',\%fieldstype);
 4287:     my ($cid,$crstype,$setting);
 4288:     if ($context eq 'domain') {
 4289:         $setting = $env{'form.roleaction'};
 4290:     }
 4291:     if ($env{'request.course.id'} ne '') {
 4292:         $cid = $env{'request.course.id'};
 4293:         $crstype = &Apache::loncommon::course_type();
 4294:     } elsif ($setting eq 'course') {
 4295:         if (&Apache::lonnet::is_course($env{'form.dcdomain'},$env{'form.dccourse'})) {
 4296:             $cid = $env{'form.dcdomain'}.'_'.$env{'form.dccourse'};
 4297:             $crstype = &Apache::loncommon::course_type($cid);
 4298:         }
 4299:     }
 4300:     my ($startdate,$enddate) = &get_dates_from_form();
 4301:     if ($env{'form.makedatesdefault'}) {
 4302:         $r->print(&make_dates_default($startdate,$enddate,$context,$crstype));
 4303:     }
 4304:     # Determine domain and desired host (home server)
 4305:     my $defdom=$env{'request.role.domain'};
 4306:     my $domain;
 4307:     if ($env{'form.defaultdomain'} ne '') {
 4308:         $domain = $env{'form.defaultdomain'};
 4309:     } else {
 4310:         $domain = $defdom;
 4311:     }
 4312:     my $desiredhost = $env{'form.lcserver'};
 4313:     if (lc($desiredhost) eq 'default') {
 4314:         $desiredhost = undef;
 4315:     } else {
 4316:         my %home_servers = &Apache::lonnet::get_servers($defdom,'library');
 4317:         if (! exists($home_servers{$desiredhost})) {
 4318:             $r->print('<p class="LC_error">'.&mt('Error').': '.
 4319:                       &mt('Invalid home server specified').'</p>');
 4320:             $r->print(&Apache::loncommon::end_page());
 4321:             return 'invalidhome';
 4322:         }
 4323:     }
 4324:     # Determine authentication mechanism
 4325:     my $changeauth;
 4326:     if ($context eq 'domain') {
 4327:         $changeauth = $env{'form.changeauth'};
 4328:     }
 4329:     my $amode  = '';
 4330:     my $genpwd = '';
 4331:     my @genpwdfail;
 4332:     if ($env{'form.login'} eq 'krb') {
 4333:         $amode='krb';
 4334:         $amode.=$env{'form.krbver'};
 4335:         $genpwd=$env{'form.krbarg'};
 4336:     } elsif ($env{'form.login'} eq 'int') {
 4337:         $amode='internal';
 4338:         if ((defined($env{'form.intarg'})) && ($env{'form.intarg'})) {
 4339:             $genpwd=$env{'form.intarg'};
 4340:             @genpwdfail =
 4341:                 &Apache::loncommon::check_passwd_rules($domain,$genpwd);
 4342:         }
 4343:     } elsif ($env{'form.login'} eq 'loc') {
 4344:         $amode='localauth';
 4345:         if ((defined($env{'form.locarg'})) && ($env{'form.locarg'})) {
 4346:             $genpwd=$env{'form.locarg'};
 4347:         }
 4348:     }
 4349:     if ($amode =~ /^krb/) {
 4350:         if (! defined($genpwd) || $genpwd eq '') {
 4351:             $r->print('<span class="Error">'.
 4352:                       &mt('Unable to enroll users').' '.
 4353:                       &mt('No Kerberos domain was specified.').'</span></p>');
 4354:             $amode = ''; # This causes the loop below to be skipped
 4355:         }
 4356:     }
 4357:     my ($defaultsec,$defaultrole,$defaultcredits,$commoncredits);
 4358:     if ($context eq 'domain') {
 4359:         if ($setting eq 'domain') {
 4360:             $defaultrole = $env{'form.defaultrole'};
 4361:         } elsif ($setting eq 'course') {
 4362:             $defaultrole = $env{'form.courserole'};
 4363:             $defaultsec = $env{'form.sections'};
 4364:             if ($showcredits) {
 4365:                 $commoncredits = $env{'form.credits'};
 4366:                 if ($crstype ne 'Community') {
 4367:                     my %coursehash=&Apache::lonnet::coursedescription($cid);
 4368:                     $defaultcredits = $coursehash{'internal.defaultcredits'};
 4369:                 }
 4370:             }
 4371:         }
 4372:     } elsif ($context eq 'author') {
 4373:         $defaultrole = $env{'form.defaultrole'};
 4374:     } elsif ($context eq 'course') {
 4375:         $defaultrole = $env{'form.defaultrole'};
 4376:         $defaultsec = $env{'form.sections'};
 4377:         if ($showcredits) {
 4378:             $commoncredits = $env{'form.credits'};
 4379:             $defaultcredits = $env{'course.'.$cid.'.internal.defaultcredits'};
 4380:         }
 4381:     }
 4382:     # Check to see if user information can be changed
 4383:     my @userinfo = ('firstname','middlename','lastname','generation',
 4384:                     'permanentemail','id');
 4385:     my %canmodify;
 4386:     if (&Apache::lonnet::allowed('mau',$domain)) {
 4387:         push(@userinfo,'inststatus');
 4388:         foreach my $field (@userinfo) {
 4389:             $canmodify{$field} = 1;
 4390:         }
 4391:     }
 4392:     my (%userlist,%modifiable_fields,@poss_roles);
 4393:     my $secidx = &Apache::loncoursedata::CL_SECTION();
 4394:     my @courseroles = &roles_by_context('course',1,$crstype);
 4395:     if (!&Apache::lonnet::allowed('mau',$domain)) {
 4396:         if ($context eq 'course' || $context eq 'author') {
 4397:             @poss_roles =  &curr_role_permissions($context,'','',$crstype);
 4398:             my @statuses = ('active','future');
 4399:             my ($indexhash,$keylist) = &make_keylist_array();
 4400:             my %info;
 4401:             foreach my $role (@poss_roles) {
 4402:                 %{$modifiable_fields{$role}} = &can_modify_userinfo($context,$domain,
 4403:                                                         \@userinfo,[$role]);
 4404:             }
 4405:             if ($context eq 'course') {
 4406:                 my ($cnum,$cdom) = &get_course_identity();
 4407:                 my $roster = &Apache::loncoursedata::get_classlist();
 4408:                 if (ref($roster) eq 'HASH') {
 4409:                     %userlist = %{$roster};
 4410:                 }
 4411:                 my %advrolehash = &Apache::lonnet::get_my_roles($cnum,$cdom,undef,
 4412:                                                          \@statuses,\@poss_roles);
 4413:                 &gather_userinfo($context,'view',\%userlist,$indexhash,\%info,
 4414:                                 \%advrolehash,$permission);
 4415:             } elsif ($context eq 'author') {
 4416:                 my %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
 4417:                                                   \@statuses,\@poss_roles);
 4418:                 &gather_userinfo($context,'view',\%userlist,$indexhash,\%info,
 4419:                              \%cstr_roles,$permission);
 4420:             }
 4421:         }
 4422:     }
 4423:     if ($datatoken eq '') {
 4424:         $r->print('<p class="LC_error">'.&mt('Error').': '.
 4425:                   &mt('Invalid datatoken').'</p>');
 4426:         return 'missingdata';
 4427:     }
 4428:     if ( $domain eq &LONCAPA::clean_domain($domain)
 4429:         && ($amode ne '')) {
 4430:         #######################################
 4431:         ##         Add/Modify Users          ##
 4432:         #######################################
 4433:         if ($context eq 'course') {
 4434:             $r->print('<h3>'.&mt('Enrolling Users')."</h3>\n<p>\n");
 4435:         } elsif ($context eq 'author') {
 4436:             $r->print('<h3>'.&mt('Updating Co-authors')."</h3>\n<p>\n");
 4437:         } else {
 4438:             $r->print('<h3>'.&mt('Adding/Modifying Users')."</h3>\n<p>\n");
 4439:         }
 4440:         $r->rflush;
 4441: 
 4442:         my %counts = (
 4443:                        user => 0,
 4444:                        auth => 0,
 4445:                        role => 0,
 4446:                      );
 4447:         my $flushc=0;
 4448:         my %student=();
 4449:         my (%curr_groups,@sections,@cleansec,$defaultwarn,$groupwarn);
 4450:         my %userchg;
 4451:         if ($context eq 'course' || $setting eq 'course') {
 4452:             if ($context eq 'course') {
 4453:                 # Get information about course groups
 4454:                 %curr_groups = &Apache::longroup::coursegroups();
 4455:             } elsif ($setting eq 'course') {
 4456:                 if ($cid) {
 4457:                     %curr_groups =
 4458:                         &Apache::longroup::coursegroups($env{'form.dcdomain'},
 4459:                                                         $env{'form.dccourse'});
 4460:                 }
 4461:             }
 4462:             # determine section number
 4463:             if ($defaultsec =~ /,/) {
 4464:                 push(@sections,split(/,/,$defaultsec));
 4465:             } else {
 4466:                 push(@sections,$defaultsec);
 4467:             }
 4468:             # remove non alphanumeric values from section
 4469:             foreach my $item (@sections) {
 4470:                 $item =~ s/\W//g;
 4471:                 if ($item eq "none" || $item eq 'all') {
 4472:                     $defaultwarn = &mt('Default section name [_1] could not be used as it is a reserved word.',$item);
 4473:                 } elsif ($item ne ''  && exists($curr_groups{$item})) {
 4474:                     $groupwarn = &mt('Default section name "[_1]" is the name of a course group. Section names and group names must be distinct.',$item);
 4475:                 } elsif ($item ne '') {
 4476:                     push(@cleansec,$item);
 4477:                 }
 4478:             }
 4479:             if ($defaultwarn) {
 4480:                 $r->print($defaultwarn.'<br />');
 4481:             }
 4482:             if ($groupwarn) {
 4483:                 $r->print($groupwarn.'<br />');
 4484:             }
 4485:         }
 4486:         my (%curr_rules,%got_rules,%alerts,%cancreate);
 4487:         my %customroles = &my_custom_roles($crstype);
 4488:         my @permitted_roles = 
 4489:             &roles_on_upload($context,$setting,$crstype,%customroles);
 4490:         my %longtypes = &Apache::lonlocal::texthash(
 4491:                             official   => 'Institutional',
 4492:                             unofficial => 'Non-institutional',
 4493:                         );
 4494:         my $newuserdom = $env{'request.role.domain'};
 4495:         map { $cancreate{$_} = &can_create_user($newuserdom,$context,$_); } keys(%longtypes);
 4496:         # Get new users list
 4497:         my (%existinguser,%userinfo,%disallow,%rulematch,%inst_results,%alerts,%checkuname,
 4498:             %showpasswdrules,$haspasswdmap);
 4499:         my $counter = -1;
 4500:         foreach my $line (@userdata) {
 4501:             $counter ++;
 4502:             my @secs;
 4503:             my %entries=&Apache::loncommon::record_sep($line);
 4504:             # Determine user name
 4505:             $entries{$fields{'username'}} =~ s/^\s+|\s+$//g;
 4506:             unless (($entries{$fields{'username'}} eq '') ||
 4507:                     (!defined($entries{$fields{'username'}}))) {
 4508:                 my ($fname, $mname, $lname,$gen) = ('','','','');
 4509:                 if (defined($fields{'names'})) {
 4510:                     ($lname,$fname,$mname)=($entries{$fields{'names'}}=~
 4511:                                             /([^\,]+)\,\s*(\w+)\s*(.*)$/);
 4512:                 } else {
 4513:                     if (defined($fields{'fname'})) {
 4514:                         $fname=$entries{$fields{'fname'}};
 4515:                     }
 4516:                     if (defined($fields{'mname'})) {
 4517:                         $mname=$entries{$fields{'mname'}};
 4518:                     }
 4519:                     if (defined($fields{'lname'})) {
 4520:                         $lname=$entries{$fields{'lname'}};
 4521:                     }
 4522:                     if (defined($fields{'gen'})) {
 4523:                         $gen=$entries{$fields{'gen'}};
 4524:                     }
 4525:                 }
 4526: 
 4527:                 if ($entries{$fields{'username'}}
 4528:                     ne &LONCAPA::clean_username($entries{$fields{'username'}})) {
 4529:                     my $nowhitespace;
 4530:                     if ($entries{$fields{'username'}} =~ /\s/) {
 4531:                         $nowhitespace = ' - '.&mt('usernames may not contain spaces.');
 4532:                     }
 4533:                     $disallow{$counter} =
 4534:                         &mt('Unacceptable username [_1] for user [_2] [_3] [_4] [_5]',
 4535:                             '"<b>'.$entries{$fields{'username'}}.'</b>"',
 4536:                             $fname,$mname,$lname,$gen).$nowhitespace;
 4537:                     next;
 4538:                 } else {
 4539:                     $entries{$fields{'domain'}} =~ s/^\s+|\s+$//g;
 4540:                     if ($entries{$fields{'domain'}} 
 4541:                         ne &LONCAPA::clean_domain($entries{$fields{'domain'}})) {
 4542:                         $disallow{$counter} =
 4543:                             &mt('Unacceptable domain [_1] for user [_2] [_3] [_4] [_5]',
 4544:                                 '"<b>'.$entries{$fields{'domain'}}.'</b>"',
 4545:                                 $fname,$mname,$lname,$gen);
 4546:                         next;
 4547:                     }
 4548:                     my $username = $entries{$fields{'username'}};
 4549:                     my $userdomain = $entries{$fields{'domain'}};
 4550:                     if ($userdomain eq '') {
 4551:                         $userdomain = $domain;
 4552:                     }
 4553:                     if (defined($fields{'sec'})) {
 4554:                         if (defined($entries{$fields{'sec'}})) {
 4555:                             $entries{$fields{'sec'}} =~ s/\W//g;
 4556:                             my $item = $entries{$fields{'sec'}};
 4557:                             if ($item eq "none" || $item eq 'all') {
 4558:                                 $disallow{$counter} =
 4559:                                     &mt('[_1]: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]" - this is a reserved word.',
 4560:                                         '<b>'.$username.'</b>',$fname,$mname,$lname,$gen,$item);
 4561:                                 next;
 4562:                             } elsif (exists($curr_groups{$item})) {
 4563:                                 $disallow{$counter} =
 4564:                                     &mt('[_1]: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]" - this is a course group.',
 4565:                                         '<b>'.$username.'</b>',$fname,$mname,$lname,$gen,$item).' '.
 4566:                                     &mt('Section names and group names must be distinct.');
 4567:                                 next;
 4568:                             } else {
 4569:                                 push(@secs,$item);
 4570:                             }
 4571:                         }
 4572:                     }
 4573:                     if ($env{'request.course.sec'} ne '') {
 4574:                         @secs = ($env{'request.course.sec'});
 4575:                         if (ref($userlist{$username.':'.$userdomain}) eq 'ARRAY') {
 4576:                             my $currsec = $userlist{$username.':'.$userdomain}[$secidx];
 4577:                             if ($currsec ne $env{'request.course.sec'}) {
 4578:                                 $disallow{$counter} =
 4579:                                     &mt('[_1]: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]".',
 4580:                                         '<b>'.$username.'</b>',$fname,$mname,$lname,$gen,$secs[0]);
 4581:                                 if ($currsec eq '') {
 4582:                                     $disallow{$counter} .=
 4583:                                         &mt('This user already has an active/future student role in the course, unaffiliated to any section.');
 4584: 
 4585:                                 } else {
 4586:                                     $disallow{$counter} .=
 4587:                                         &mt('This user already has an active/future role in section "[_1]" of the course.',$currsec);
 4588:                                 }
 4589:                                 $disallow{$counter} .=
 4590:                                     '<br />'.
 4591:                                     &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.',
 4592:                                         $secs[0]);
 4593:                                 next;
 4594:                             }
 4595:                         }
 4596:                     } elsif ($context eq 'course' || $setting eq 'course') {
 4597:                         if (@secs == 0) {
 4598:                             @secs = @cleansec;
 4599:                         }
 4600:                     }
 4601:                     # determine id number
 4602:                     my $id='';
 4603:                     if (defined($fields{'id'})) {
 4604:                         if (defined($entries{$fields{'id'}})) {
 4605:                             $id=$entries{$fields{'id'}};
 4606:                         }
 4607:                         $id=~tr/A-Z/a-z/;
 4608:                     }
 4609:                     # determine email address
 4610:                     my $email='';
 4611:                     if (defined($fields{'email'})) {
 4612:                         $entries{$fields{'email'}} =~ s/^\s+|\s+$//g;
 4613:                         if (defined($entries{$fields{'email'}})) {
 4614:                             $email=$entries{$fields{'email'}};
 4615:                             unless ($email=~/^[^\@]+\@[^\@]+$/) { $email=''; }
 4616:                         }
 4617:                     }
 4618:                     # determine affiliation
 4619:                     my $inststatus='';
 4620:                     if (defined($fields{'inststatus'})) {
 4621:                         if (defined($entries{$fields{'inststatus'}})) {
 4622:                             $inststatus=$entries{$fields{'inststatus'}};
 4623:                         }
 4624:                     }
 4625:                     # determine user password
 4626:                     my $password;
 4627:                     my $passwdfromfile;
 4628:                     if (defined($fields{'ipwd'})) {
 4629:                         if ($entries{$fields{'ipwd'}}) {
 4630:                             $password=$entries{$fields{'ipwd'}};
 4631:                             $passwdfromfile = 1;
 4632:                             if ($env{'form.login'} eq 'int') {
 4633:                                 my $uhome=&Apache::lonnet::homeserver($username,$userdomain);
 4634:                                 if (($uhome eq 'no_host') || ($changeauth)) {
 4635:                                     my @brokepwdrules =
 4636:                                         &Apache::loncommon::check_passwd_rules($domain,$password);
 4637:                                     if (@brokepwdrules) {
 4638:                                         $disallow{$counter} = &mt('[_1]: Password included in file for this user did not meet requirements.',
 4639:                                                                   '<b>'.$username.'</b>');
 4640:                                         map { $showpasswdrules{$_} = 1; } @brokepwdrules;
 4641:                                         next;
 4642:                                     }
 4643:                                 }
 4644:                             }
 4645:                         }
 4646:                     }
 4647:                     unless ($passwdfromfile) {
 4648:                         if ($env{'form.login'} eq 'int') {
 4649:                             if (@genpwdfail) {
 4650:                                 my $uhome=&Apache::lonnet::homeserver($username,$userdomain);
 4651:                                 if (($uhome eq 'no_host') || ($changeauth)) {
 4652:                                     $disallow{$counter} = &mt('[_1]: No specific password in file for this user; default password did not meet requirements',
 4653:                                                               '<b>'.$username.'</b>');
 4654:                                     unless ($haspasswdmap) {
 4655:                                         map { $showpasswdrules{$_} = 1; } @genpwdfail;
 4656:                                         $haspasswdmap = 1;
 4657:                                     }
 4658:                                 }
 4659:                                 next;
 4660:                             }
 4661:                         }
 4662:                         $password = $genpwd;
 4663:                     }
 4664:                     # determine user role
 4665:                     my $role = '';
 4666:                     if (defined($fields{'role'})) {
 4667:                         if ($entries{$fields{'role'}}) {
 4668:                             $entries{$fields{'role'}}  =~ s/(\s+$|^\s+)//g;
 4669:                             if ($entries{$fields{'role'}} ne '') {
 4670:                                 if (grep(/^\Q$entries{$fields{'role'}}\E$/,@permitted_roles)) {
 4671:                                     $role = $entries{$fields{'role'}};
 4672:                                 }
 4673:                             }
 4674:                             if ($role eq '') {
 4675:                                 my $rolestr = join(', ',@permitted_roles);
 4676:                                 $disallow{$counter} =
 4677:                                     &mt('[_1]: You do not have permission to add the requested role [_2] for the user.'
 4678:                                         ,'<b>'.$entries{$fields{'username'}}.'</b>'
 4679:                                         ,$entries{$fields{'role'}})
 4680:                                         .'<br />'
 4681:                                         .&mt('Allowable role(s) is/are: [_1].',$rolestr);
 4682:                                 next;
 4683:                             }
 4684:                         }
 4685:                     }
 4686:                     if ($role eq '') {
 4687:                         $role = $defaultrole;
 4688:                     }
 4689:                     # Clean up whitespace
 4690:                     foreach (\$id,\$fname,\$mname,\$lname,\$gen,\$inststatus) {
 4691:                         $$_ =~ s/(\s+$|^\s+)//g;
 4692:                     }
 4693:                     my $credits;
 4694:                     if ($showcredits) {
 4695:                         if (($role eq 'st') && ($crstype ne 'Community')) {
 4696:                             $credits = $entries{$fields{'credits'}};
 4697:                             if ($credits ne '') {
 4698:                                 $credits =~ s/[^\d\.]//g;
 4699:                             }
 4700:                             if ($credits eq '') {
 4701:                                 $credits = $commoncredits;
 4702:                             }
 4703:                             if ($credits eq $defaultcredits) {
 4704:                                 undef($credits);
 4705:                             }
 4706:                         }
 4707:                     }
 4708:                     # check against rules
 4709:                     my $checkid = 0;
 4710:                     my $newuser = 0;
 4711:                     my $uhome=&Apache::lonnet::homeserver($username,$userdomain);
 4712:                     if ($uhome eq 'no_host') {
 4713:                         if ($userdomain ne $newuserdom) {
 4714:                             if ($context eq 'course') {
 4715:                                 $disallow{$counter} =
 4716:                                     &mt('[_1]: The domain specified ([_2]) is different to that of the course.',
 4717:                                        '<b>'.$username.'</b>',$userdomain);
 4718:                             } elsif ($context eq 'author') {
 4719:                                 $disallow{$counter} =
 4720:                                     &mt('[_1]: The domain specified ([_2]) is different to that of the author.',
 4721:                                         '<b>'.$username.'</b>',$userdomain); 
 4722:                             } else {
 4723:                                 $disallow{$counter} =
 4724:                                     &mt('[_1]: The domain specified ([_2]) is different to that of your current role.',
 4725:                                         '<b>'.$username.'</b>',$userdomain);
 4726:                             }
 4727:                             $disallow{$counter} .=
 4728:                                 &mt('The user does not already exist, and you may not create a new user in a different domain.');
 4729:                             next;
 4730:                         } else {
 4731:                             unless ($password || $env{'form.login'} eq 'loc') {
 4732:                                 $disallow{$counter} =
 4733:                                     &mt('[_1]: This is a new user but no default password was provided, and the authentication type requires one.',
 4734:                                         '<b>'.$username.'</b>');
 4735:                                 next;
 4736:                             }
 4737:                         }
 4738:                         $checkid = 1;
 4739:                         $newuser = 1;
 4740:                         $checkuname{$username.':'.$newuserdom} = { 'newuser' => $newuser, 'id' => $id };
 4741:                     } else {
 4742:                         if ($context eq 'course' || $context eq 'author') {
 4743:                             if ($userdomain eq $domain ) {
 4744:                                 if ($role eq '') {
 4745:                                     my @checkroles;
 4746:                                     foreach my $role (@poss_roles) {
 4747:                                         my $endkey;
 4748:                                         if ($role ne 'st') {
 4749:                                             $endkey = ':'.$role;
 4750:                                         }
 4751:                                         if (exists($userlist{$username.':'.$userdomain.$endkey})) {
 4752:                                             if (!grep(/^\Q$role\E$/,@checkroles)) {
 4753:                                                 push(@checkroles,$role);
 4754:                                             }
 4755:                                         }
 4756:                                     }
 4757:                                     if (@checkroles > 0) {
 4758:                                         %canmodify = &can_modify_userinfo($context,$domain,\@userinfo,\@checkroles);
 4759:                                     }
 4760:                                 } elsif (ref($modifiable_fields{$role}) eq 'HASH') {
 4761:                                     %canmodify = %{$modifiable_fields{$role}};
 4762:                                 }
 4763:                             }
 4764:                             my @newinfo = (\$fname,\$mname,\$lname,\$gen,\$email,\$id);
 4765:                             for (my $i=0; $i<@newinfo; $i++) {
 4766:                                 if (${$newinfo[$i]} ne '') {
 4767:                                     if (!$canmodify{$userinfo[$i]}) {
 4768:                                         ${$newinfo[$i]} = '';
 4769:                                     }
 4770:                                 }
 4771:                             }
 4772:                         }
 4773:                         if ($id) {
 4774:                             $existinguser{$userdomain}{$username} = $id;
 4775:                         }
 4776:                     }
 4777:                     $userinfo{$counter} = {
 4778:                                           username   => $username,
 4779:                                           domain     => $userdomain,
 4780:                                           fname      => $fname,
 4781:                                           mname      => $mname,
 4782:                                           lname      => $lname,
 4783:                                           gen        => $gen,
 4784:                                           email      => $email,
 4785:                                           id         => $id, 
 4786:                                           password   => $password,
 4787:                                           inststatus => $inststatus,
 4788:                                           role       => $role,
 4789:                                           sections   => \@secs,
 4790:                                           credits    => $credits,
 4791:                                           newuser    => $newuser,
 4792:                                           checkid    => $checkid,
 4793:                                         };
 4794:                 }
 4795:             }
 4796:         } # end of foreach (@userdata)
 4797:         if ($counter > -1) {
 4798:             my $total = $counter + 1;
 4799:             my %checkids;
 4800:             if ((keys(%existinguser)) || (keys(%checkuname))) {
 4801:                 $r->print(&mt('Please be patient -- checking for institutional data ...'));
 4802:                 $r->rflush();
 4803:                 if (keys(%existinguser)) {
 4804:                     foreach my $dom (keys(%existinguser)) {
 4805:                         if (ref($existinguser{$dom}) eq 'HASH') {
 4806:                             my %idhash = &Apache::lonnet::idrget($dom,keys(%{$existinguser{$dom}}));
 4807:                             foreach my $username (keys(%{$existinguser{$dom}})) {
 4808:                                 if ($idhash{$username} ne $existinguser{$dom}{$username}) {
 4809:                                     $checkids{$username.':'.$dom} = {
 4810:                                                                     'id' => $existinguser{$dom}{$username},
 4811:                                                                     };
 4812:                                 }
 4813:                             }
 4814:                             if (keys(%checkids)) {
 4815:                                 &Apache::loncommon::user_rule_check(\%checkids,{ 'id' => 1 },
 4816:                                                                     \%alerts,\%rulematch,
 4817:                                                                     \%inst_results,\%curr_rules,
 4818:                                                                     \%got_rules);
 4819:                             }
 4820:                         }
 4821:                     }
 4822:                 }
 4823:                 if (keys(%checkuname)) {
 4824:                     &Apache::loncommon::user_rule_check(\%checkuname,{ 'username' => 1, 'id' => 1, },
 4825:                                                         \%alerts,\%rulematch,\%inst_results,
 4826:                                                         \%curr_rules,\%got_rules);
 4827:                 }
 4828:                 $r->print(' '.&mt('done').'<br /><br />');
 4829:                 $r->rflush();
 4830:             }
 4831:             my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,$total);
 4832:             $r->print('<ul>');
 4833:             for (my $i=0; $i<=$counter; $i++) {
 4834:                 if ($disallow{$i}) {
 4835:                     $r->print('<li>'.$disallow{$i}.'</li>');
 4836:                 } elsif (ref($userinfo{$i}) eq 'HASH') {
 4837:                     my $password = $userinfo{$i}{'password'}; 
 4838:                     my $newuser = $userinfo{$i}{'newuser'};
 4839:                     my $checkid = $userinfo{$i}{'checkid'};
 4840:                     my $id = $userinfo{$i}{'id'};
 4841:                     my $role = $userinfo{$i}{'role'};
 4842:                     my @secs;
 4843:                     if (ref($userinfo{$i}{'sections'}) eq 'ARRAY') {
 4844:                         @secs = @{$userinfo{$i}{'sections'}};
 4845:                     }
 4846:                     my $fname = $userinfo{$i}{'fname'};
 4847:                     my $mname = $userinfo{$i}{'mname'}; 
 4848:                     my $lname = $userinfo{$i}{'lname'};
 4849:                     my $gen = $userinfo{$i}{'gen'};
 4850:                     my $email = $userinfo{$i}{'email'};
 4851:                     my $inststatus = $userinfo{$i}{'inststatus'};
 4852:                     my $credits = $userinfo{$i}{'credits'};
 4853:                     my $username = $userinfo{$i}{'username'};
 4854:                     my $userdomain = $userinfo{$i}{'domain'};
 4855:                     my $user = $username.':'.$userdomain;
 4856:                     if ($newuser) {
 4857:                         if (ref($alerts{'username'}) eq 'HASH') {
 4858:                             if (ref($alerts{'username'}{$userdomain}) eq 'HASH') {
 4859:                                 if ($alerts{'username'}{$userdomain}{$username}) {
 4860:                                     $r->print('<li>'.
 4861:                                               &mt('[_1]: matches the username format at your institution, but is not known to your directory service.','<b>'.$username.'</b>').'<br />'.
 4862:                                               &mt('Consequently, the user was not created.').'</li>');
 4863:                                     next;
 4864:                                 }
 4865:                             }
 4866:                         }
 4867:                         if (ref($inst_results{$user}) eq 'HASH') {
 4868:                             if ($inst_results{$user}{'firstname'} ne '') {
 4869:                                 $fname = $inst_results{$user}{'firstname'};
 4870:                             }
 4871:                             if ($inst_results{$user}{'middlename'} ne '') {
 4872:                                 $mname = $inst_results{$user}{'middlename'};
 4873:                             }
 4874:                             if ($inst_results{$user}{'lasttname'} ne '') {
 4875:                                 $lname = $inst_results{$user}{'lastname'};
 4876:                             }
 4877:                             if ($inst_results{$user}{'permanentemail'} ne '') {
 4878:                                 $email = $inst_results{$user}{'permanentemail'};
 4879:                             }
 4880:                             if ($inst_results{$user}{'id'} ne '') {
 4881:                                 $id = $inst_results{$user}{'id'};
 4882:                                 $checkid = 0;
 4883:                             }
 4884:                             if (ref($inst_results{$user}{'inststatus'}) eq 'ARRAY') {
 4885:                                 $inststatus = join(':',@{$inst_results{$user}{'inststatus'}});
 4886:                             }
 4887:                         }
 4888:                         if (($checkid) && ($id ne '')) {
 4889:                             if (ref($alerts{'id'}) eq 'HASH') {
 4890:                                 if (ref($alerts{'id'}{$userdomain}) eq 'HASH') {
 4891:                                     if ($alerts{'id'}{$userdomain}{$username}) {
 4892:                                         $r->print('<li>'.
 4893:                                                   &mt('[_1]: has a student/employee ID matching the format at your institution, but the ID is not found by your directory service.',
 4894:                                                   '<b>'.$username.'</b>').'<br />'.
 4895:                                                   &mt('Consequently, the user was not created.').'</li>');
 4896:                                         next;
 4897:                                     }
 4898:                                 }
 4899:                             }
 4900:                         }
 4901:                         my $usertype = 'unofficial';
 4902:                         if (ref($rulematch{$user}) eq 'HASH') {
 4903:                             if ($rulematch{$user}{'username'}) {
 4904:                                 $usertype = 'official';
 4905:                             }
 4906:                         }
 4907:                         unless ($cancreate{$usertype}) {
 4908:                             my $showtype = $longtypes{$usertype};
 4909:                             $r->print('<li>'.
 4910:                                       &mt('[_1]: The user does not exist, and you are not permitted to create users of type: [_2].','<b>'.$username.'</b>',$showtype).'</li>');
 4911:                             next;
 4912:                         }
 4913:                     } elsif ($id ne '') {
 4914:                         if (exists($checkids{$user})) {
 4915:                             $checkid = 1; 
 4916:                             if (ref($alerts{'id'}) eq 'HASH') {
 4917:                                 if (ref($alerts{'id'}{$userdomain}) eq 'HASH') {
 4918:                                     if ($alerts{'id'}{$userdomain}{$username}) {
 4919:                                         $r->print('<li>'.
 4920:                                                   &mt('[_1]: has a student/employee ID matching the format at your institution, but the ID is not found by your directory service.',
 4921:                                                   '<b>'.$username.'</b>').'<br />'.
 4922:                                                   &mt('Consequently, the ID was not changed.').'</li>');
 4923:                                         $id = '';
 4924:                                     }
 4925:                                 }
 4926:                             }
 4927:                         }
 4928:                     }
 4929:                     my $multiple = 0;
 4930:                     my ($userresult,$authresult,$roleresult,$idresult);
 4931:                     my (%userres,%authres,%roleres,%idres);
 4932:                     my $singlesec = '';
 4933:                     if ($role eq 'st') {
 4934:                         my $sec;
 4935:                         if (ref($userinfo{$i}{'sections'}) eq 'ARRAY') {
 4936:                             if (@secs > 0) {
 4937:                                 $sec = $secs[0];
 4938:                             }
 4939:                         }
 4940:                         &modifystudent($userdomain,$username,$cid,$sec,
 4941:                                        $desiredhost,$context);
 4942:                         $roleresult =
 4943:                             &Apache::lonnet::modifystudent
 4944:                                 ($userdomain,$username,$id,$amode,$password,
 4945:                                  $fname,$mname,$lname,$gen,$sec,$enddate,
 4946:                                  $startdate,$env{'form.forceid'},
 4947:                                  $desiredhost,$email,'manual','',$cid,
 4948:                                  '',$context,$inststatus,$credits);
 4949:                         $userresult = $roleresult;
 4950:                     } else {
 4951:                         if ($role ne '') { 
 4952:                             if ($context eq 'course' || $setting eq 'course') {
 4953:                                 if ($customroles{$role}) {
 4954:                                     $role = 'cr_'.$env{'user.domain'}.'_'.
 4955:                                             $env{'user.name'}.'_'.$role;
 4956:                                 }
 4957:                                 if (($role ne 'cc') && ($role ne 'co')) { 
 4958:                                    if (@secs > 1) {
 4959:                                         $multiple = 1;
 4960:                                         foreach my $sec (@secs) {
 4961:                                             ($userres{$sec},$authres{$sec},$roleres{$sec},$idres{$sec}) =
 4962:                                             &modifyuserrole($context,$setting,
 4963:                                                 $changeauth,$cid,$userdomain,$username,
 4964:                                                 $id,$amode,$password,$fname,
 4965:                                                 $mname,$lname,$gen,$sec,
 4966:                                                 $env{'form.forceid'},$desiredhost,
 4967:                                                 $email,$role,$enddate,
 4968:                                                 $startdate,$checkid,$inststatus);
 4969:                                         }
 4970:                                     } elsif (@secs > 0) {
 4971:                                         $singlesec = $secs[0];
 4972:                                     }
 4973:                                 }
 4974:                             }
 4975:                             if (!$multiple) {
 4976:                                 ($userresult,$authresult,$roleresult,$idresult) = 
 4977:                                     &modifyuserrole($context,$setting,
 4978:                                                     $changeauth,$cid,$userdomain,$username, 
 4979:                                                     $id,$amode,$password,$fname,
 4980:                                                     $mname,$lname,$gen,$singlesec,
 4981:                                                     $env{'form.forceid'},$desiredhost,
 4982:                                                     $email,$role,$enddate,$startdate,
 4983:                                                     $checkid,$inststatus);
 4984:                             }
 4985:                         }
 4986:                     }
 4987:                     if ($multiple) {
 4988:                         foreach my $sec (sort(keys(%userres))) {
 4989:                             $flushc =
 4990:                                 &user_change_result($r,$userres{$sec},$authres{$sec},
 4991:                                                     $roleres{$sec},$idres{$sec},\%counts,$flushc,
 4992:                                                     $username,$userdomain,\%userchg);
 4993: 
 4994:                         }
 4995:                     } else {
 4996:                         $flushc = 
 4997:                             &user_change_result($r,$userresult,$authresult,
 4998:                                                 $roleresult,$idresult,\%counts,$flushc,
 4999:                                                 $username,$userdomain,\%userchg);
 5000:                     }
 5001:                 }
 5002:                 &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last user');
 5003:             } # end of loop
 5004:             $r->print('</ul>');
 5005:             &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 5006:         }
 5007:         # Flush the course logs so reverse user roles immediately updated
 5008:         $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 5009:         $r->print("</p>\n<p>\n".&mt('Processed [quant,_1,user].',$counts{'user'}).
 5010:                   "</p>\n");
 5011:         if ($counts{'role'} > 0) {
 5012:             $r->print("<p>\n".
 5013:                       &mt('Roles added for [quant,_1,user].',$counts{'role'}).' '.
 5014:                       &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.').
 5015:                       "</p>\n");
 5016:         } else {
 5017:             $r->print('<p>'.&mt('No roles added').'</p>');
 5018:         }
 5019:         if ($counts{'auth'} > 0) {
 5020:             $r->print("<p>\n".
 5021:                       &mt('Authentication changed for [_1] existing users.',
 5022:                           $counts{'auth'})."</p>\n");
 5023:         }
 5024:         $r->print(&print_namespacing_alerts($domain,\%alerts,\%curr_rules));
 5025:         $r->print(&passwdrule_alerts($domain,\%showpasswdrules));
 5026:         #####################################
 5027:         # Display list of students to drop  #
 5028:         #####################################
 5029:         if ($env{'form.fullup'} eq 'yes') {
 5030:             $r->print('<h3>'.&mt('Students to Drop')."</h3>\n");
 5031:             #  Get current classlist
 5032:             my $classlist = &Apache::loncoursedata::get_classlist();
 5033:             if (! defined($classlist)) {
 5034:                 $r->print('<p class="LC_info">'.
 5035:                           &mt('There are no students with current/future access to the course.').
 5036:                           '</p>'."\n");
 5037:             } elsif (ref($classlist) eq 'HASH') {
 5038:                 # Remove the students we just added from the list of students.
 5039:                 foreach my $line (@userdata) {
 5040:                     my %entries=&Apache::loncommon::record_sep($line);
 5041:                     unless (($entries{$fields{'username'}} eq '') ||
 5042:                             (!defined($entries{$fields{'username'}}))) {
 5043:                         delete($classlist->{$entries{$fields{'username'}}.
 5044:                                                 ':'.$domain});
 5045:                     }
 5046:                 }
 5047:                 # Print out list of dropped students.
 5048:                 &show_drop_list($r,$classlist,'nosort',$permission);
 5049:             }
 5050:         }
 5051:     } # end of unless
 5052:     return 'ok';
 5053: }
 5054: 
 5055: sub print_namespacing_alerts {
 5056:     my ($domain,$alerts,$curr_rules) = @_;
 5057:     my $output;
 5058:     if (ref($alerts) eq 'HASH') {
 5059:         if (keys(%{$alerts}) > 0) {
 5060:             if (ref($alerts->{'username'}) eq 'HASH') {
 5061:                 foreach my $dom (sort(keys(%{$alerts->{'username'}}))) {
 5062:                     my $count;
 5063:                     if (ref($alerts->{'username'}{$dom}) eq 'HASH') {
 5064:                         $count = keys(%{$alerts->{'username'}{$dom}});
 5065:                     }
 5066:                     my $domdesc = &Apache::lonnet::domain($domain,'description');
 5067:                     if (ref($curr_rules->{$dom}) eq 'HASH') {
 5068:                         $output .= &Apache::loncommon::instrule_disallow_msg(
 5069:                                         'username',$domdesc,$count,'upload');
 5070:                     }
 5071:                     $output .= &Apache::loncommon::user_rule_formats($dom,
 5072:                                    $domdesc,$curr_rules->{$dom}{'username'},
 5073:                                    'username');
 5074:                 }
 5075:             }
 5076:             if (ref($alerts->{'id'}) eq 'HASH') {
 5077:                 foreach my $dom (sort(keys(%{$alerts->{'id'}}))) {
 5078:                     my $count;
 5079:                     if (ref($alerts->{'id'}{$dom}) eq 'HASH') {
 5080:                         $count = keys(%{$alerts->{'id'}{$dom}});
 5081:                     }
 5082:                     my $domdesc = &Apache::lonnet::domain($domain,'description');
 5083:                     if (ref($curr_rules->{$dom}) eq 'HASH') {
 5084:                         $output .= &Apache::loncommon::instrule_disallow_msg(
 5085:                                               'id',$domdesc,$count,'upload');
 5086:                     }
 5087:                     $output .= &Apache::loncommon::user_rule_formats($dom,
 5088:                                     $domdesc,$curr_rules->{$dom}{'id'},'id');
 5089:                 }
 5090:             }
 5091:         }
 5092:     }
 5093: }
 5094: 
 5095: sub passwdrule_alerts {
 5096:     my ($domain,$passwdrules) = @_;
 5097:     my $warning;
 5098:     if (ref($passwdrules) eq 'HASH') {
 5099:         my %showrules = %{$passwdrules};
 5100:         if (keys(%showrules)) {
 5101:             my %passwdconf = &Apache::lonnet::get_passwdconf($domain);
 5102:             $warning = '<b>'.&mt('Password requirement(s) unmet for one or more users:').'</b><ul>';
 5103:             if ($showrules{'min'}) {
 5104:                 $warning .= '<li>'.&mt('minimum [quant,_1,character]',$passwdconf{'min'}).'</li>';
 5105:             }
 5106:             if ($showrules{'max'}) {
 5107:                 $warning .= '<li>'.&mt('maximum [quant,_1,character]',$passwdconf{'max'}).'</li>';
 5108:             }
 5109:             if ($showrules{'uc'}) {
 5110:                 $warning .= '<li>'.&mt('contain at least one upper case letter').'</li>';
 5111:             }
 5112:             if ($showrules{'lc'}) {
 5113:                 $warning .= '<li>'.&mt('contain at least one lower case letter').'</li>';
 5114:             }
 5115:             if ($showrules{'num'}) {
 5116:                 $warning .= '<li>'.&mt('contain at least one number').'</li>';
 5117:             }
 5118:             if ($showrules{'spec'}) {
 5119:                 $warning .= '<li>'.&mt('contain at least one non-alphanumeric').'</li>';
 5120:             }
 5121:             $warning .= '</ul>';
 5122:         }
 5123:     }
 5124:     return $warning;
 5125: }
 5126: 
 5127: sub user_change_result {
 5128:     my ($r,$userresult,$authresult,$roleresult,$idresult,$counts,$flushc,
 5129:         $username,$userdomain,$userchg) = @_;
 5130:     my $okresult = 0;
 5131:     my @status;
 5132:     if ($userresult ne 'ok') {
 5133:         if ($userresult =~ /^error:(.+)$/) {
 5134:             my $error = $1;
 5135:             push(@status,
 5136:                  &mt('[_1]: Unable to add/modify: [_2]','<b>'.$username.':'.$userdomain.'</b>',$error));
 5137:         }
 5138:     } else {
 5139:         $counts->{'user'} ++;
 5140:         $okresult = 1;
 5141:     }
 5142:     if ($authresult ne 'ok') {
 5143:         if ($authresult =~ /^error:(.+)$/) {
 5144:             my $error = $1;
 5145:             push(@status, 
 5146:                  &mt('[_1]: Unable to modify authentication: [_2]','<b>'.$username.':'.$userdomain.'</b>',$error));
 5147:         } 
 5148:     } else {
 5149:         $counts->{'auth'} ++;
 5150:         $okresult = 1;
 5151:     }
 5152:     if ($roleresult ne 'ok') {
 5153:         if ($roleresult =~ /^error:(.+)$/) {
 5154:             my $error = $1;
 5155:             push(@status,
 5156:                  &mt('[_1]: Unable to add role: [_2]','<b>'.$username.':'.$userdomain.'</b>',$error));
 5157:         }
 5158:     } else {
 5159:         $counts->{'role'} ++;
 5160:         $okresult = 1;
 5161:     }
 5162:     if ($okresult) {
 5163:         $flushc++;
 5164:         $userchg->{$username.':'.$userdomain}=1;
 5165:         if ($flushc>15) {
 5166:             $r->rflush;
 5167:             $flushc=0;
 5168:         }
 5169:     }
 5170:     if ($idresult) {
 5171:         push(@status,$idresult);
 5172:     }
 5173:     if (@status) {
 5174:         $r->print('<li>'.join('<br />',@status).'</li>');
 5175:     }
 5176:     return $flushc;
 5177: }
 5178: 
 5179: # ========================================================= Menu Phase Two Drop
 5180: sub print_drop_menu {
 5181:     my ($r,$context,$permission,$crstype) = @_;
 5182:     my $heading;
 5183:     if ($crstype eq 'Community') {
 5184:         $heading = &mt("Drop Members");
 5185:     } else {
 5186:         $heading = &mt("Drop Students");
 5187:     }
 5188:     $r->print('<h3>'.$heading.'</h3>'."\n".
 5189:               '<form name="studentform" method="post" action="">'."\n");
 5190:     my $classlist = &Apache::loncoursedata::get_classlist();
 5191:     if (! defined($classlist)) {
 5192:         my $msg = '';
 5193:         if ($crstype eq 'Community') {
 5194:             $msg = &mt('There are no members currently enrolled.');
 5195:         } else {
 5196:             $msg = &mt('There are no students currently enrolled.');
 5197:         }
 5198:         $r->print('<p class="LC_info">'.$msg."</p>\n");
 5199:     } else {
 5200:         &show_drop_list($r,$classlist,'nosort',$permission,$crstype);
 5201:     }
 5202:     $r->print('</form>');
 5203:     return;
 5204: }
 5205: 
 5206: # ================================================================== Phase four
 5207: 
 5208: sub update_user_list {
 5209:     my ($r,$context,$setting,$choice,$crstype) = @_;
 5210:     my $now = time;
 5211:     my $count=0;
 5212:     if ($context eq 'course') {
 5213:         $crstype = &Apache::loncommon::course_type();
 5214:     }
 5215:     my @changelist;
 5216:     if ($choice eq 'drop') {
 5217:         @changelist = &Apache::loncommon::get_env_multiple('form.droplist');
 5218:     } else {
 5219:         @changelist = &Apache::loncommon::get_env_multiple('form.actionlist');
 5220:     }
 5221:     my %result_text = ( ok    => { 'revoke'   => 'Revoked',
 5222:                                    'delete'   => 'Deleted',
 5223:                                    'reenable' => 'Re-enabled',
 5224:                                    'activate' => 'Activated',
 5225:                                    'chgdates' => 'Changed Access Dates for',
 5226:                                    'chgsec'   => 'Changed section(s) for',
 5227:                                    'drop'     => 'Dropped',
 5228:                                  },
 5229:                         error => {'revoke'    => 'revoking',
 5230:                                   'delete'    => 'deleting',
 5231:                                   'reenable'  => 're-enabling',
 5232:                                   'activate'  => 'activating',
 5233:                                   'chgdates'  => 'changing access dates for',
 5234:                                   'chgsec'    => 'changing section for',
 5235:                                   'drop'      => 'dropping',
 5236:                                  },
 5237:                       );
 5238:     my ($startdate,$enddate);
 5239:     if ($choice eq 'chgdates' || $choice eq 'reenable' || $choice eq 'activate') {
 5240:         ($startdate,$enddate) = &get_dates_from_form();
 5241:     }
 5242:     foreach my $item (@changelist) {
 5243:         my ($role,$uname,$udom,$cid,$sec,$scope,$result,$type,$locktype,
 5244:             @sections,$scopestem,$singlesec,$showsecs,$warn_singlesec,
 5245:             $nothingtodo,$keepnosection,$credits,$instsec);
 5246:         if ($choice eq 'drop') {
 5247:             ($uname,$udom,$sec) = split(/:/,$item,-1);
 5248:             $role = 'st';
 5249:             $cid = $env{'request.course.id'};
 5250:             $scopestem = '/'.$cid;
 5251:             $scopestem =~s/\_/\//g;
 5252:             if ($sec eq '') {
 5253:                 $scope = $scopestem;
 5254:             } else {
 5255:                 $scope = $scopestem.'/'.$sec;
 5256:             }
 5257:         } elsif ($context eq 'course') {
 5258:             ($uname,$udom,$role,$sec,$type,$locktype,$credits,$instsec) =
 5259:                 split(/\:/,$item,8);
 5260:             $instsec = &unescape($instsec);
 5261:             $cid = $env{'request.course.id'};
 5262:             $scopestem = '/'.$cid;
 5263:             $scopestem =~s/\_/\//g;
 5264:             if ($sec eq '') {
 5265:                 $scope = $scopestem;
 5266:             } else {
 5267:                 $scope = $scopestem.'/'.$sec;
 5268:             }
 5269:         } elsif ($context eq 'author') {
 5270:             ($uname,$udom,$role) = split(/\:/,$item,-1);
 5271:             $scope = '/'.$env{'user.domain'}.'/'.$env{'user.name'};
 5272:         } elsif ($context eq 'domain') {
 5273:             if ($setting eq 'domain') {
 5274:                 ($role,$uname,$udom) = split(/\:/,$item,-1);
 5275:                 $scope = '/'.$env{'request.role.domain'}.'/';
 5276:             } elsif ($setting eq 'author') { 
 5277:                 ($uname,$udom,$role,$scope) = split(/\:/,$item);
 5278:             } elsif ($setting eq 'course') {
 5279:                 ($uname,$udom,$role,$cid,$sec,$type,$locktype,$credits,$instsec) = 
 5280:                     split(/\:/,$item,9);
 5281:                 $instsec = &unescape($instsec);
 5282:                 $scope = '/'.$cid;
 5283:                 $scope =~s/\_/\//g;
 5284:                 if ($sec ne '') {
 5285:                     $scope .= '/'.$sec;
 5286:                 }
 5287:             }
 5288:         }
 5289:         my $plrole = &Apache::lonnet::plaintext($role,$crstype);
 5290:         my $start = $env{'form.'.$item.'_start'};
 5291:         my $end = $env{'form.'.$item.'_end'};
 5292:         if ($choice eq 'drop') {
 5293:             # drop students
 5294:             $end = $now;
 5295:             $type = 'manual';
 5296:             $result =
 5297:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
 5298:         } elsif ($choice eq 'revoke') {
 5299:             # revoke or delete user role
 5300:             $end = $now; 
 5301:             if ($role eq 'st') {
 5302:                 $result = 
 5303:                     &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5304:             } else {
 5305:                 $result = 
 5306:                     &Apache::lonnet::revokerole($udom,$uname,$scope,$role,
 5307:                                                 '','',$context);
 5308:             }
 5309:         } elsif ($choice eq 'delete') {
 5310:             if ($role eq 'st') {
 5311:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$now,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5312:             }
 5313:             $result =
 5314:                 &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$now,
 5315:                                             $start,1,'',$context);
 5316:         } else {
 5317:             #reenable, activate, change access dates or change section
 5318:             if ($choice ne 'chgsec') {
 5319:                 $start = $startdate; 
 5320:                 $end = $enddate;
 5321:             }
 5322:             if ($choice eq 'reenable') {
 5323:                 if ($role eq 'st') {
 5324:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5325:                 } else {
 5326:                     $result = 
 5327:                         &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
 5328:                                                     $now,'','',$context);
 5329:                 }
 5330:             } elsif ($choice eq 'activate') {
 5331:                 if ($role eq 'st') {
 5332:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5333:                 } else {
 5334:                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
 5335:                                             $now,'','',$context);
 5336:                 }
 5337:             } elsif ($choice eq 'chgdates') {
 5338:                 if ($role eq 'st') {
 5339:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5340:                 } else {
 5341:                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
 5342:                                                 $start,'','',$context);
 5343:                 }
 5344:             } elsif ($choice eq 'chgsec') {
 5345:                 my (@newsecs,$revresult,$nochg,@retained);
 5346:                 if (($role ne 'cc') && ($role ne 'co')) {
 5347:                     my @secs = sort(split(/,/,$env{'form.newsecs'}));
 5348:                     if (@secs) {
 5349:                         my %curr_groups = &Apache::longroup::coursegroups();
 5350:                         foreach my $sec (@secs) {
 5351:                             next if (($sec =~ /\W/) || ($sec eq 'none') ||
 5352:                             (exists($curr_groups{$sec})));
 5353:                             push(@newsecs,$sec);
 5354:                         }
 5355:                     }
 5356:                 }
 5357:                 # remove existing section if not to be retained.   
 5358:                 if (!$env{'form.retainsec'} || ($role eq 'st')) {
 5359:                     if ($sec eq '') {
 5360:                         if (@newsecs == 0) {
 5361:                             $result = 'ok';
 5362:                             $nochg = 1;
 5363:                             $nothingtodo = 1;
 5364:                         } else {
 5365:                             $revresult =
 5366:                                 &Apache::lonnet::revokerole($udom,$uname,
 5367:                                                             $scope,$role,
 5368:                                                             '','',$context);
 5369:                         } 
 5370:                     } else {
 5371:                         if (@newsecs > 0) {
 5372:                             if (grep(/^\Q$sec\E$/,@newsecs)) {
 5373:                                 push(@retained,$sec);
 5374:                             } else {
 5375:                                 $revresult =
 5376:                                     &Apache::lonnet::revokerole($udom,$uname,
 5377:                                                                 $scope,$role,
 5378:                                                                 '','',$context);
 5379:                             }
 5380:                         } else {
 5381:                             $revresult =
 5382:                                 &Apache::lonnet::revokerole($udom,$uname,
 5383:                                                             $scope,$role,
 5384:                                                             '','',$context);
 5385:                         }
 5386:                     }
 5387:                 } else {
 5388:                     if ($sec eq '') {
 5389:                         $nochg = 1;
 5390:                         $keepnosection = 1;
 5391:                     } else {
 5392:                         push(@retained,$sec);
 5393:                     }
 5394:                 }
 5395:                 # add new sections
 5396:                 my (@diffs,@shownew);
 5397:                 if (@retained) {
 5398:                     @diffs = &Apache::loncommon::compare_arrays(\@retained,\@newsecs);
 5399:                 } else {
 5400:                     @diffs = @newsecs;
 5401:                 }
 5402:                 if (@newsecs == 0) {
 5403:                     if ($nochg) {
 5404:                         $result = 'ok';
 5405:                         $nothingtodo = 1;
 5406:                     } else {
 5407:                         if ($role eq 'st') {
 5408:                             $result = 
 5409:                                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,undef,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5410:                         } else {
 5411:                             my $newscope = $scopestem;
 5412:                             $result = &Apache::lonnet::assignrole($udom,$uname,$newscope,$role,$end,$start,'','',$context);
 5413:                         }
 5414:                     }
 5415:                     $showsecs = &mt('No section');
 5416:                 } elsif (@diffs == 0) {
 5417:                     $result = 'ok';
 5418:                     $nothingtodo = 1;
 5419:                 } else {
 5420:                     foreach my $newsec (@newsecs) {
 5421:                         if (!grep(/^\Q$newsec\E$/,@retained)) {
 5422:                             if ($role eq 'st') {
 5423:                                 $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$newsec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
 5424:                                 if (@newsecs > 1) {
 5425:                                     my $showsingle; 
 5426:                                     if ($newsec eq '') {
 5427:                                         $showsingle = &mt('No section');
 5428:                                     } else {
 5429:                                         $showsingle = $newsec;
 5430:                                     }
 5431:                                     if ($crstype eq 'Community') {
 5432:                                         $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>');
 5433:                                     } else { 
 5434:                                         $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>');
 5435:                                     }
 5436:                                     $showsecs = $showsingle; 
 5437:                                     last;
 5438:                                 } else {
 5439:                                     if ($newsec eq '') {
 5440:                                         $showsecs = &mt('No section');
 5441:                                     } else {
 5442:                                         $showsecs = $newsec;
 5443:                                     }
 5444:                                 }
 5445:                             } else {
 5446:                                 my $newscope = $scopestem;
 5447:                                 if ($newsec ne '') {
 5448:                                    $newscope .= '/'.$newsec;
 5449:                                    push(@shownew,$newsec); 
 5450:                                 }
 5451:                                 $result = &Apache::lonnet::assignrole($udom,$uname,
 5452:                                                         $newscope,$role,$end,$start);
 5453:                                 
 5454:                             }
 5455:                         }
 5456:                     }
 5457:                 }
 5458:                 unless ($role eq 'st') {
 5459:                     unless ($showsecs) {
 5460:                         my @tolist = sort(@shownew,@retained);
 5461:                         if ($keepnosection) {
 5462:                             push(@tolist,&mt('No section'));
 5463:                         }
 5464:                         $showsecs = join(', ',@tolist);
 5465:                     }
 5466:                 }
 5467:             }
 5468:         }
 5469:         my $extent = $scope;
 5470:         if ($choice eq 'drop' || $context eq 'course') {
 5471:             my ($cnum,$cdom,$cdesc) = &get_course_identity($cid);
 5472:             if ($cdesc) {
 5473:                 $extent = $cdesc;
 5474:             }
 5475:         }
 5476:         if ($result eq 'ok' || $result eq 'ok:') {
 5477:             my $dates;
 5478:             if (($choice eq 'chgsec') || ($choice eq 'chgdates')) {
 5479:                 $dates = &dates_feedback($start,$end,$now);
 5480:             }
 5481:             if ($choice eq 'chgsec') {
 5482:                 if ($nothingtodo) {
 5483:                     $r->print(&mt("Section assignment for role of '[_1]' in [_2] for '[_3]' unchanged.",$plrole,$extent,'<i>'.
 5484:                           &Apache::loncommon::plainname($uname,$udom).
 5485:                           '</i>').' ');
 5486:                     if ($sec eq '') {
 5487:                         $r->print(&mt('[_1]No section[_2] - [_3]','<b>','</b>',$dates));
 5488:                     } else {
 5489:                         $r->print(&mt('Section(s): [_1] - [_2]',
 5490:                                       '<b>'.$showsecs.'</b>',$dates));
 5491:                     }
 5492:                     $r->print('<br />');
 5493:                 } else {
 5494:                     $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]' to [_4] - [_5]",$plrole,$extent,
 5495:                         '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
 5496:                         '<b>'.$showsecs.'</b>',$dates).'<br />');
 5497:                    $count ++;
 5498:                }
 5499:                if ($warn_singlesec) {
 5500:                    $r->print('<div class="LC_warning">'.$warn_singlesec.'</div>');
 5501:                }
 5502:             } elsif ($choice eq 'chgdates') {
 5503:                 $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]' - [_4]",$plrole,$extent, 
 5504:                       '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
 5505:                       $dates).'<br />');
 5506:                $count ++;
 5507:             } else {
 5508:                 $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]'.",$plrole,$extent,
 5509:                       '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>').
 5510:                           '<br />');
 5511:                 $count ++;
 5512:             }
 5513:         } else {
 5514:             $r->print(
 5515:                 &mt("Error $result_text{'error'}{$choice} [_1] in [_2] for '[_3]': [_4].",
 5516:                     $plrole,$extent,
 5517:                     '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
 5518:                     $result).'<br />');
 5519:         }
 5520:     }
 5521:     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n");
 5522:     if ($choice eq 'drop') {
 5523:         $r->print('<input type="hidden" name="action" value="listusers" />'."\n".
 5524:                   '<input type="hidden" name="Status" value="Active" />'."\n".
 5525:                   '<input type="hidden" name="showrole" value="st" />'."\n");
 5526:     } else {
 5527:         foreach my $item ('action','sortby','roletype','showrole','Status','secfilter','grpfilter') {
 5528:             if ($env{'form.'.$item} ne '') {
 5529:                 $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.
 5530:                           '" />'."\n");
 5531:             }
 5532:         }
 5533:     }
 5534:     $r->print('<p><b>'.&mt("$result_text{'ok'}{$choice} [quant,_1,user role,user roles,no user roles].",$count).'</b></p>');
 5535:     if ($count > 0) {
 5536:         if ($choice eq 'revoke' || $choice eq 'drop') {
 5537:             $r->print('<p>'.&mt('Re-enabling will re-activate data for the role.').'</p>');
 5538:         }
 5539:         # Flush the course logs so reverse user roles immediately updated
 5540:         $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 5541:     }
 5542:     if ($env{'form.makedatesdefault'}) {
 5543:         if ($choice eq 'chgdates' || $choice eq 'reenable' || $choice eq 'activate') {
 5544:             $r->print(&make_dates_default($startdate,$enddate,$context,$crstype));
 5545:         }
 5546:     }
 5547:     my $linktext = &mt('Display User Lists');
 5548:     if ($choice eq 'drop') {
 5549:         $linktext = &mt('Display current class roster');
 5550:     }
 5551:     $r->print(
 5552:         &Apache::lonhtmlcommon::actionbox(
 5553:             ['<a href="javascript:document.studentform.submit()">'.$linktext.'</a>'])
 5554:        .'</form>'."\n");
 5555: }
 5556: 
 5557: sub dates_feedback {
 5558:     my ($start,$end,$now) = @_;
 5559:     my $dates;
 5560:     if ($start < $now) {
 5561:         if ($end == 0) {
 5562:             $dates = &mt('role(s) active now; no end date');
 5563:         } elsif ($end > $now) {
 5564:             $dates = &mt('role(s) active now; ends [_1].',&Apache::lonlocal::locallocaltime($end));
 5565:         } else {
 5566:             $dates = &mt('role(s) expired: [_1].',&Apache::lonlocal::locallocaltime($end));
 5567:         }
 5568:      } else {
 5569:         if ($end == 0 || $end > $now) {
 5570:             $dates = &mt('future role(s); starts: [_1].',&Apache::lonlocal::locallocaltime($start));
 5571:         } else {
 5572:             $dates = &mt('role(s) expired: [_1].',&Apache::lonlocal::locallocaltime($end));
 5573:         }
 5574:     }
 5575:     return $dates;
 5576: }
 5577: 
 5578: sub classlist_drop {
 5579:     my ($scope,$uname,$udom,$now) = @_;
 5580:     my ($cdom,$cnum) = ($scope=~m{^/($match_domain)/($match_courseid)});
 5581:     if (&Apache::lonnet::is_course($cdom,$cnum)) {
 5582:         if (!&active_student_roles($cnum,$cdom,$uname,$udom)) {
 5583:             my %user;
 5584:             my $result = &update_classlist($cdom,$cnum,$udom,$uname,\%user,$now);
 5585:             return &mt('Drop from classlist: [_1]',
 5586:                        '<b>'.$result.'</b>').'<br />';
 5587:         }
 5588:     }
 5589: }
 5590: 
 5591: sub active_student_roles {
 5592:     my ($cnum,$cdom,$uname,$udom) = @_;
 5593:     my %roles =
 5594:         &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
 5595:                                       ['future','active'],['st']);
 5596:     return exists($roles{"$cnum:$cdom:st"});
 5597: }
 5598: 
 5599: sub section_check_js {
 5600:     my $groupslist= &get_groupslist();
 5601:     my %js_lt = &Apache::lonlocal::texthash(
 5602:         mayn   => 'may not be used as the name for a section, as it is a reserved word.',
 5603:         plch   => 'Please choose a different section name.',
 5604:         mnot   => 'may not be used as a section name, as it is the name of a course group.',
 5605:         secn   => 'Section names and group names must be distinct. Please choose a different section name.',
 5606:     );
 5607:     &js_escape(\%js_lt);
 5608:     return <<"END";
 5609: function validate(caller) {
 5610:     var groups = new Array($groupslist);
 5611:     var secname = caller.value;
 5612:     if ((secname == 'all') || (secname == 'none')) {
 5613:         alert("'"+secname+"' $js_lt{'mayn'}\\n$js_lt{'plch'}");
 5614:         return 'error';
 5615:     }
 5616:     if (secname != '') {
 5617:         for (var k=0; k<groups.length; k++) {
 5618:             if (secname == groups[k]) {
 5619:                 alert("'"+secname+"' $js_lt{'mnot'}\\n$js_lt{'secn'}");
 5620:                 return 'error';
 5621:             }
 5622:         }
 5623:     }
 5624:     return 'ok';
 5625: }
 5626: END
 5627: }
 5628: 
 5629: sub set_login {
 5630:     my ($dom,$authformkrb,$authformint,$authformloc) = @_;
 5631:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 5632:     my $response;
 5633:     my ($authnum,%can_assign) =
 5634:         &Apache::loncommon::get_assignable_auth($dom);
 5635:     if ($authnum) {
 5636:         $response = &Apache::loncommon::start_data_table();
 5637:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 5638:             $response .= &Apache::loncommon::start_data_table_row().
 5639:                          '<td>'.$authformkrb.'</td>'.
 5640:                          &Apache::loncommon::end_data_table_row()."\n";
 5641:         }
 5642:         if ($can_assign{'int'}) {
 5643:             $response .= &Apache::loncommon::start_data_table_row().
 5644:                          '<td>'.$authformint.'</td>'.
 5645:                          &Apache::loncommon::end_data_table_row()."\n"
 5646:         }
 5647:         if ($can_assign{'loc'}) {
 5648:             $response .= &Apache::loncommon::start_data_table_row().
 5649:                          '<td>'.$authformloc.'</td>'.
 5650:                          &Apache::loncommon::end_data_table_row()."\n";
 5651:         }
 5652:         $response .= &Apache::loncommon::end_data_table();
 5653:     }
 5654:     return $response;
 5655: }
 5656: 
 5657: sub course_sections {
 5658:     my ($sections_count,$role,$current_sec,$disabled) = @_;
 5659:     my $output = '';
 5660:     my @sections = (sort {$a <=> $b} keys(%{$sections_count}));
 5661:     my $numsec = scalar(@sections);
 5662:     my $is_selected = ' selected="selected"';
 5663:     if ($numsec <= 1) {
 5664:         $output = '<select name="currsec_'.$role.'"'.$disabled.'>'."\n".
 5665:                   '  <option value="">'.&mt('Select').'</option>'."\n";
 5666:         if ($current_sec eq 'none') {
 5667:             $output .=       
 5668:                   '  <option value=""'.$is_selected.'>'.&mt('No section').'</option>'."\n";
 5669:         } else {
 5670:             $output .=
 5671:                   '  <option value="">'.&mt('No section').'</option>'."\n";
 5672:         }
 5673:         if ($numsec == 1) {
 5674:             if ($current_sec eq $sections[0]) {
 5675:                 $output .=
 5676:                   '  <option value="'.$sections[0].'"'.$is_selected.'>'.$sections[0].'</option>'."\n";
 5677:             } else {
 5678:                 $output .=  
 5679:                   '  <option value="'.$sections[0].'" >'.$sections[0].'</option>'."\n";
 5680:             }
 5681:         }
 5682:     } else {
 5683:         $output = '<select name="currsec_'.$role.'" ';
 5684:         my $multiple = 4;
 5685:         if (scalar(@sections) < 4) { $multiple = scalar(@sections); }
 5686:         if ($role eq 'st') {
 5687:             $output .= $disabled.'>'."\n".
 5688:                        '  <option value="">'.&mt('Select').'</option>'."\n";
 5689:             if ($current_sec eq 'none') {
 5690:                 $output .= 
 5691:                        '  <option value=""'.$is_selected.'>'.&mt('No section')."</option>\n";
 5692:             } else {
 5693:                 $output .=
 5694:                        '  <option value="">'.&mt('No section')."</option>\n";
 5695:             }
 5696:         } else {
 5697:             $output .= 'multiple="multiple" size="'.$multiple.'"'.$disabled.'>'."\n";
 5698:         }
 5699:         foreach my $sec (@sections) {
 5700:             if ($current_sec eq $sec) {
 5701:                 $output .= '<option value="'.$sec.'"'.$is_selected.'>'.$sec."</option>\n";
 5702:             } else {
 5703:                 $output .= '<option value="'.$sec.'">'.$sec."</option>\n";
 5704:             }
 5705:         }
 5706:     }
 5707:     $output .= '</select>';
 5708:     return $output;
 5709: }
 5710: 
 5711: sub get_groupslist {
 5712:     my $groupslist;
 5713:     my %curr_groups = &Apache::longroup::coursegroups();
 5714:     if (%curr_groups) {
 5715:         $groupslist = join('","',sort(keys(%curr_groups)));
 5716:         $groupslist = '"'.$groupslist.'"';
 5717:     }
 5718:     return $groupslist; 
 5719: }
 5720: 
 5721: sub setsections_javascript {
 5722:     my ($formname,$groupslist,$mode,$checkauth,$crstype,$showcredits) = @_;
 5723:     my ($checkincluded,$finish,$rolecode,$setsection_js);
 5724:     if ($mode eq 'upload') {
 5725:         $checkincluded = 'formname.name == "'.$formname.'"';
 5726:         $finish = "return 'ok';";
 5727:         $rolecode = "var role = formname.defaultrole.options[formname.defaultrole.selectedIndex].value;\n";
 5728:     } elsif ($formname eq 'cu') {
 5729:         if (($crstype eq 'Course') && ($showcredits)) {
 5730:             $checkincluded = "((role == 'st') && (formname.elements[i-2].checked == true)) || ((role != 'st') && (formname.elements[i-1].checked == true))";
 5731:         } else {
 5732:             $checkincluded = 'formname.elements[i-1].checked == true';
 5733:         }
 5734:         if ($checkauth) {
 5735:             $finish = "var authcheck = auth_check();\n".
 5736:                       "   if (authcheck == 'ok') {\n".
 5737:                       "       formname.submit();\n".
 5738:                       "   }\n";
 5739:         } else {
 5740:             $finish = 'formname.submit()';
 5741:         }
 5742:         $rolecode = "var match = str.split('_');
 5743:                 var role = match[3];\n";
 5744:     } elsif (($formname eq 'enrollstudent') || ($formname eq 'selfenroll')) {
 5745:         $checkincluded = 'formname.name == "'.$formname.'"';
 5746:         if ($checkauth) {
 5747:             $finish = "var authcheck = auth_check();\n".
 5748:                       "   if (authcheck == 'ok') {\n".
 5749:                       "       formname.submit();\n".
 5750:                       "   }\n";
 5751:         } else {
 5752:             $finish = 'formname.submit()';
 5753:         }
 5754:         $rolecode = "var match = str.split('_');
 5755:                 var role = match[1];\n";
 5756:     } else {
 5757:         $checkincluded = 'formname.name == "'.$formname.'"'; 
 5758:         $finish = "seccheck = 'ok';";
 5759:         $rolecode = "var match = str.split('_');
 5760:                 var role = match[1];\n";
 5761:         $setsection_js = "var seccheck = 'alert';"; 
 5762:     }
 5763:     my %alerts = &Apache::lonlocal::texthash(
 5764:                     secd => 'Section designations do not apply to Course Coordinator roles.',
 5765:                     sedn => 'Section designations do not apply to Coordinator roles.',
 5766:                     accr => 'A course coordinator role will be added with access to all sections.',
 5767:                     acor => 'A coordinator role will be added with access to all sections',
 5768:                     inea => 'In each course, each user may only have one student role at a time.',
 5769:                     inco => 'In each community, each user may only have one member role at a time.',
 5770:                     youh => 'You had selected',
 5771:                     secs => 'sections.',
 5772:                     plmo => 'Please modify your selections so they include no more than one section.',
 5773:                     mayn => 'may not be used as the name for a section, as it is a reserved word.',
 5774:                     plch => 'Please choose a different section name.',
 5775:                     mnot => 'may not be used as a section name, as it is the name of a course group.',
 5776:                     secn => 'Section names and group names must be distinct. Please choose a different section name.',
 5777:                     nonw => 'Section names may only contain letters or numbers.',
 5778:                  );
 5779:     &js_escape(\%alerts);
 5780:     $setsection_js .= <<"ENDSECCODE";
 5781: 
 5782: function setSections(formname,crstype) {
 5783:     var re1 = /^currsec_/;
 5784:     var re2 =/\\W/;
 5785:     var trimleading = /^\\s+/;
 5786:     var trimtrailing = /\\s+\$/;
 5787:     var groups = new Array($groupslist);
 5788:     for (var i=0;i<formname.elements.length;i++) {
 5789:         var str = formname.elements[i].name;
 5790:         if (typeof(str) === "undefined") {
 5791:             continue;
 5792:         }
 5793:         var checkcurr = str.match(re1);
 5794:         if (checkcurr != null) {
 5795:             var num = i;
 5796:             $rolecode
 5797:             if ($checkincluded) {
 5798:                 if (role == 'cc' || role == 'co') {
 5799:                     if (role == 'cc') {
 5800:                         alert("$alerts{'secd'}\\n$alerts{'accr'}");
 5801:                     } else {
 5802:                         alert("$alerts{'sedn'}\\n$alerts{'acor'}");
 5803:                     }
 5804:                 } else {
 5805:                     var sections = '';
 5806:                     var numsec = 0;
 5807:                     var fromexisting = new Array();
 5808:                     for (var j=0; j<formname.elements[num].length; j++) {
 5809:                         if (formname.elements[num].options[j].selected == true ) {
 5810:                             var addsec = formname.elements[num].options[j].value;
 5811:                             if ((addsec != "") && (addsec != null)) {
 5812:                                 fromexisting.push(addsec);
 5813:                                 if (numsec == 0) {
 5814:                                     sections = addsec;
 5815:                                 } else {
 5816:                                     sections = sections + "," +  addsec;
 5817:                                 }
 5818:                                 numsec ++;
 5819:                             }
 5820:                         }
 5821:                     }
 5822:                     var newsecs = formname.elements[num+1].value;
 5823:                     var validsecs = new Array();
 5824:                     var validsecstr = '';
 5825:                     var badsecs = new Array();
 5826:                     if (newsecs != null && newsecs != "") {
 5827:                         var numsplit;
 5828:                         if (newsecs.indexOf(',') == -1) {
 5829:                             numsplit = new Array(newsecs);
 5830:                         } else {
 5831:                             numsplit = newsecs.split(/,/g);
 5832:                         }
 5833:                         for (var m=0; m<numsplit.length; m++) {
 5834:                             var newsec = numsplit[m];
 5835:                             newsec = newsec.replace(trimleading,'');
 5836:                             newsec = newsec.replace(trimtrailing,'');
 5837:                             if (re2.test(newsec) == true) {
 5838:                                 badsecs.push(newsec);
 5839:                             } else {
 5840:                                 if (newsec != '') {
 5841:                                     var isnew = 1;
 5842:                                     if (fromexisting != null) {
 5843:                                         for (var n=0; n<fromexisting.length; n++) {
 5844:                                             if (newsec == fromexisting[n]) {
 5845:                                                 isnew = 0;
 5846:                                             }
 5847:                                         }
 5848:                                     }
 5849:                                     if (isnew == 1) {
 5850:                                         validsecs.push(newsec);
 5851:                                     }
 5852:                                 }
 5853:                             }
 5854:                         }
 5855:                         if (badsecs.length > 0) {
 5856:                             alert("$alerts{'nonw'}\\n$alerts{'plch'}");
 5857:                             return;
 5858:                         }
 5859:                         numsec = numsec + validsecs.length;
 5860:                     }
 5861:                     if ((role == 'st') && (numsec > 1)) {
 5862:                         if (crstype == 'Community') {
 5863:                             alert("$alerts{'inea'} $alerts{'youh'} "+numsec+" $alerts{'secs'}\\n$alerts{'plmo'}");
 5864:                         } else {
 5865:                             alert("$alerts{'inco'} $alerts{'youh'} "+numsec+" $alerts{'secs'}\\n$alerts{'plmo'}");
 5866:                         }
 5867:                         return;
 5868:                     } else {
 5869:                         if (validsecs != null) {
 5870:                             for (var j=0; j<validsecs.length; j++) {
 5871:                                 if (validsecstr == '' || validsecstr == null) {
 5872:                                     validsecstr = validsecs[j];
 5873:                                 } else {
 5874:                                     validsecstr += ','+validsecs[j];
 5875:                                 }
 5876:                                 if ((validsecs[j] == 'all') ||
 5877:                                     (validsecs[j] == 'none')) {
 5878:                                     alert("'"+validsecs[j]+"' $alerts{'mayn'}\\n$alerts{'plch'}");
 5879:                                     return;
 5880:                                 }
 5881:                                 for (var k=0; k<groups.length; k++) {
 5882:                                     if (validsecs[j] == groups[k]) {
 5883:                                         alert("'"+validsecs[j]+"' $alerts{'mnot'}\\n$alerts{'secn'}");
 5884:                                         return;
 5885:                                     }
 5886:                                 }
 5887:                             }
 5888:                         }
 5889:                     }
 5890:                     if ((validsecstr != '') && (validsecstr != null)) {
 5891:                         if ((sections == '') || (sections == null)) {
 5892:                             sections = validsecstr;
 5893:                         } else {
 5894:                             sections = sections + "," + validsecstr;
 5895:                         }
 5896:                     }
 5897:                     formname.elements[num+2].value = sections;
 5898:                 }
 5899:             }
 5900:         }
 5901:     }
 5902:     $finish
 5903: }
 5904: ENDSECCODE
 5905:     return $setsection_js; 
 5906: }
 5907: 
 5908: sub can_create_user {
 5909:     my ($dom,$context,$usertype) = @_;
 5910:     my %domconf = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 5911:     my $cancreate = 1;
 5912:     if (&Apache::lonnet::allowed('mau',$dom)) {
 5913:         return $cancreate;
 5914:     } elsif ($context eq 'domain') {
 5915:         $cancreate = 0;
 5916:         return $cancreate;
 5917:     }
 5918:     if (ref($domconf{'usercreation'}) eq 'HASH') {
 5919:         if (ref($domconf{'usercreation'}{'cancreate'}) eq 'HASH') {
 5920:             if ($context eq 'course' || $context eq 'author' || $context eq 'requestcrs') {
 5921:                 my $creation = $domconf{'usercreation'}{'cancreate'}{$context};
 5922:                 if ($creation eq 'none') {
 5923:                     $cancreate = 0;
 5924:                 } elsif ($creation ne 'any') {
 5925:                     if (defined($usertype)) {
 5926:                         if ($creation ne $usertype) {
 5927:                             $cancreate = 0;
 5928:                         }
 5929:                     }
 5930:                 }
 5931:             }
 5932:         }
 5933:     }
 5934:     return $cancreate;
 5935: }
 5936: 
 5937: sub can_modify_userinfo {
 5938:     my ($context,$dom,$fields,$userroles) = @_;
 5939:     my %domconfig =
 5940:        &Apache::lonnet::get_dom('configuration',['usermodification'],
 5941:                                 $dom);
 5942:     my %canmodify;
 5943:     if (ref($fields) eq 'ARRAY') {
 5944:         foreach my $field (@{$fields}) {
 5945:             $canmodify{$field}  = 0;
 5946:             if (&Apache::lonnet::allowed('mau',$dom)) {
 5947:                 $canmodify{$field} = 1;
 5948:             } else {
 5949:                 if (ref($domconfig{'usermodification'}) eq 'HASH') {
 5950:                     if (ref($domconfig{'usermodification'}{$context}) eq 'HASH') {
 5951:                         if (ref($userroles) eq 'ARRAY') {
 5952:                             foreach my $role (@{$userroles}) {
 5953:                                 my $testrole;
 5954:                                 if ($context eq 'selfcreate') {
 5955:                                     $testrole = $role;
 5956:                                 } else {
 5957:                                     if ($role =~ /^cr\//) {
 5958:                                         $testrole = 'cr';
 5959:                                     } else {
 5960:                                         $testrole = $role;
 5961:                                     }
 5962:                                 }
 5963:                                 if (ref($domconfig{'usermodification'}{$context}{$testrole}) eq 'HASH') {
 5964:                                     if ($domconfig{'usermodification'}{$context}{$testrole}{$field}) {
 5965:                                         $canmodify{$field} = 1;
 5966:                                         last;
 5967:                                     }
 5968:                                 }
 5969:                             }
 5970:                         } else {
 5971:                             foreach my $key (keys(%{$domconfig{'usermodification'}{$context}})) {
 5972:                                 if (ref($domconfig{'usermodification'}{$context}{$key}) eq 'HASH') {
 5973:                                     if ($domconfig{'usermodification'}{$context}{$key}{$field}) {
 5974:                                         $canmodify{$field} = 1;
 5975:                                         last;
 5976:                                     }
 5977:                                 }
 5978:                             }
 5979:                         }
 5980:                     }
 5981:                 } elsif ($context eq 'course') {
 5982:                     if (ref($userroles) eq 'ARRAY') {
 5983:                         if (grep(/^st$/,@{$userroles})) {
 5984:                             $canmodify{$field} = 1;
 5985:                         }
 5986:                     } else {
 5987:                         $canmodify{$field} = 1;
 5988:                     }
 5989:                 }
 5990:             }
 5991:         }
 5992:     }
 5993:     return %canmodify;
 5994: }
 5995: 
 5996: sub check_usertype {
 5997:     my ($dom,$uname,$rules,$curr_rules,$got_rules) = @_;
 5998:     my $usertype;
 5999:     if ((ref($got_rules) eq 'HASH') && (ref($curr_rules) eq 'HASH')) {
 6000:         if (!$got_rules->{$dom}) {
 6001:             my %domconfig = &Apache::lonnet::get_dom('configuration',
 6002:                                               ['usercreation'],$dom);
 6003:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 6004:                 foreach my $item ('username','id') {
 6005:                     if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 6006:                         $curr_rules->{$dom}{$item} =
 6007:                                 $domconfig{'usercreation'}{$item.'_rule'};
 6008:                     }
 6009:                 }
 6010:             }
 6011:             $got_rules->{$dom} = 1;
 6012:         }
 6013:         if (ref($rules) eq 'HASH') {
 6014:             my @user_rules;
 6015:             if (ref($curr_rules->{$dom}{'username'}) eq 'ARRAY') {
 6016:                 foreach my $rule (keys(%{$rules})) {
 6017:                     if (grep(/^\Q$rule\E/,@{$curr_rules->{$dom}{'username'}})) {
 6018:                         push(@user_rules,$rule);
 6019:                     }
 6020:                 } 
 6021:             }
 6022:             if (@user_rules > 0) {
 6023:                 my %rule_check = &Apache::lonnet::inst_rulecheck($dom,$uname,undef,'username',\@user_rules);
 6024:                 if (keys(%rule_check) > 0) {
 6025:                     $usertype = 'unofficial';
 6026:                     foreach my $item (keys(%rule_check)) {
 6027:                         if ($rule_check{$item}) {
 6028:                             $usertype = 'official';
 6029:                             last;
 6030:                         }
 6031:                     }
 6032:                 }
 6033:             }
 6034:         }
 6035:     }
 6036:     return $usertype;
 6037: }
 6038: 
 6039: sub roles_by_context {
 6040:     my ($context,$custom,$crstype) = @_;
 6041:     my @allroles;
 6042:     if ($context eq 'course') {
 6043:         @allroles = ('st');
 6044:         if ($env{'request.role'} =~ m{^dc\./}) {
 6045:             push(@allroles,'ad');
 6046:         }
 6047:         push(@allroles,('ta','ep','in'));
 6048:         if ($crstype eq 'Community') {
 6049:             push(@allroles,'co');
 6050:         } else {
 6051:             push(@allroles,'cc');
 6052:         }
 6053:         if ($custom) {
 6054:             push(@allroles,'cr');
 6055:         }
 6056:     } elsif ($context eq 'author') {
 6057:         @allroles = ('ca','aa');
 6058:     } elsif ($context eq 'domain') {
 6059:         @allroles = ('li','ad','dg','dh','da','sc','au','dc');
 6060:     }
 6061:     return @allroles;
 6062: }
 6063: 
 6064: sub get_permission {
 6065:     my ($context,$crstype) = @_;
 6066:     my %permission;
 6067:     if ($context eq 'course') {
 6068:         my $custom = 1;
 6069:         my @allroles = &roles_by_context($context,$custom,$crstype);
 6070:         foreach my $role (@allroles) {
 6071:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
 6072:                 $permission{'cusr'} = 1;
 6073:                 last;
 6074:             }
 6075:         }
 6076:         if (&Apache::lonnet::allowed('ccr',$env{'request.course.id'})) {
 6077:             $permission{'custom'} = 1;
 6078:         }
 6079:         if (&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) {
 6080:             $permission{'view'} = 1;
 6081:         }
 6082:         if (!$permission{'view'}) {
 6083:             my $scope = $env{'request.course.id'}.'/'.$env{'request.course.sec'};
 6084:             $permission{'view'} =  &Apache::lonnet::allowed('vcl',$scope);
 6085:             if ($permission{'view'}) {
 6086:                 $permission{'view_section'} = $env{'request.course.sec'};
 6087:             }
 6088:         }
 6089:         if (!$permission{'cusr'}) {
 6090:             if ($env{'request.course.sec'} ne '') {
 6091:                 my $scope = $env{'request.course.id'}.'/'.$env{'request.course.sec'};
 6092:                 $permission{'cusr'} = (&Apache::lonnet::allowed('cst',$scope));
 6093:                 if ($permission{'cusr'}) {
 6094:                     $permission{'cusr_section'} = $env{'request.course.sec'};
 6095:                 }
 6096:             }
 6097:         }
 6098:         if (&Apache::lonnet::allowed('mdg',$env{'request.course.id'})) {
 6099:             $permission{'grp_manage'} = 1;
 6100:         }
 6101:         if ($permission{'cusr'}) {
 6102:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6103:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6104:             my %coursehash = (
 6105:                 'internal.selfenrollmgrdc' => $env{'course.'.$env{'request.course.id'}.'.internal.selfenrollmgrdc'},
 6106:                 'internal.selfenrollmgrcc' => $env{'course.'.$env{'request.course.id'}.'.internal.selfenrollmgrcc'},
 6107:                 'internal.coursecode'      => $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'},
 6108:                 'internal.textbook'        =>$env{'course.'.$env{'request.course.id'}.'.internal.textbook'},
 6109:             );
 6110:             my ($managed_by_cc,$managed_by_dc) = &selfenrollment_administration($cdom,$cnum,$crstype,\%coursehash);
 6111:             if (ref($managed_by_cc) eq 'ARRAY') {
 6112:                 if (@{$managed_by_cc}) {
 6113:                     $permission{'selfenrolladmin'} = 1;
 6114:                 }
 6115:             }
 6116:         }
 6117:         if ($env{'request.course.id'}) {
 6118:             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 6119:             if (($user ne '') && ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq
 6120:                                   $user)) {
 6121:                 $permission{'owner'} = 1;
 6122:             } elsif (($user ne '') && ($env{'course.'.$env{'request.course.id'}.'.internal.co-owners'} ne '')) {
 6123:                 if (grep(/^\Q$user\E$/,split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.co-owners'}))) {
 6124:                     $permission{'co-owner'} = 1;
 6125:                 }
 6126:             }
 6127:         }
 6128:     } elsif ($context eq 'author') {
 6129:         $permission{'cusr'} = &authorpriv($env{'user.name'},$env{'request.role.domain'});
 6130:         $permission{'view'} = $permission{'cusr'};
 6131:     } else {
 6132:         my @allroles = &roles_by_context($context);
 6133:         foreach my $role (@allroles) {
 6134:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
 6135:                 $permission{'cusr'} = 1;
 6136:                 last;
 6137:             }
 6138:         }
 6139:         if (!$permission{'cusr'}) {
 6140:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 6141:                 $permission{'cusr'} = 1;
 6142:             }
 6143:         }
 6144:         if (&Apache::lonnet::allowed('ccr',$env{'request.role.domain'})) {
 6145:             $permission{'custom'} = 1;
 6146:         }
 6147:         if (&Apache::lonnet::allowed('vac',$env{'request.role.domain'})) {
 6148:             $permission{'activity'} = 1;
 6149:         }
 6150:         if (&Apache::lonnet::allowed('vur',$env{'request.role.domain'})) {
 6151:             $permission{'view'} = 1;
 6152:         }
 6153:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 6154:             $permission{'owner'} = 1;
 6155:         }
 6156:     }
 6157:     my $allowed = 0;
 6158:     foreach my $perm (values(%permission)) {
 6159:         if ($perm) { $allowed=1; last; }
 6160:     }
 6161:     return (\%permission,$allowed);
 6162: }
 6163: 
 6164: # ==================================================== Figure out author access
 6165: 
 6166: sub authorpriv {
 6167:     my ($auname,$audom)=@_;
 6168:     unless ((&Apache::lonnet::allowed('cca',$audom.'/'.$auname))
 6169:          || (&Apache::lonnet::allowed('caa',$audom.'/'.$auname))) { return ''; }    return 1;
 6170: }
 6171: 
 6172: sub roles_on_upload {
 6173:     my ($context,$setting,$crstype,%customroles) = @_;
 6174:     my (@possible_roles,@permitted_roles);
 6175:     @possible_roles = &curr_role_permissions($context,$setting,1,$crstype);
 6176:     foreach my $role (@possible_roles) {
 6177:         if ($role eq 'cr') {
 6178:             push(@permitted_roles,keys(%customroles));
 6179:         } else {
 6180:             push(@permitted_roles,$role);
 6181:         }
 6182:     }
 6183:     return @permitted_roles;
 6184: }
 6185: 
 6186: sub get_course_identity {
 6187:     my ($cid) = @_;
 6188:     my ($cnum,$cdom,$cdesc);
 6189:     if ($cid eq '') {
 6190:         $cid = $env{'request.course.id'}
 6191:     }
 6192:     if ($cid ne '') {
 6193:         $cnum = $env{'course.'.$cid.'.num'};
 6194:         $cdom = $env{'course.'.$cid.'.domain'};
 6195:         $cdesc = $env{'course.'.$cid.'.description'};
 6196:         if ($cnum eq '' || $cdom eq '') {
 6197:             my %coursehash =
 6198:                 &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 6199:             $cdom = $coursehash{'domain'};
 6200:             $cnum = $coursehash{'num'};
 6201:             $cdesc = $coursehash{'description'};
 6202:         }
 6203:     }
 6204:     return ($cnum,$cdom,$cdesc);
 6205: }
 6206: 
 6207: sub dc_setcourse_js {
 6208:     my ($formname,$mode,$context,$showcredits,$domain) = @_;
 6209:     my ($dc_setcourse_code,$authen_check);
 6210:     my $cctext = &Apache::lonnet::plaintext('cc');
 6211:     my $cotext = &Apache::lonnet::plaintext('co');
 6212:     my %alerts = &sectioncheck_alerts();
 6213:     my $role = 'role';
 6214:     if ($mode eq 'upload') {
 6215:         $role = 'courserole';
 6216:     } else {
 6217:         $authen_check = &verify_authen($formname,$context,$domain);
 6218:     }
 6219:     $dc_setcourse_code = (<<"SCRIPTTOP");
 6220: $authen_check
 6221: 
 6222: function setCourse() {
 6223:     var course = document.$formname.dccourse.value;
 6224:     if (course != "") {
 6225:         if (document.$formname.dcdomain.value != document.$formname.origdom.value) {
 6226:             alert("$alerts{'curd'}");
 6227:             return;
 6228:         }
 6229:         var userrole = document.$formname.$role.options[document.$formname.$role.selectedIndex].value
 6230:         var section="";
 6231:         var numsections = 0;
 6232:         var newsecs = new Array();
 6233:         for (var i=0; i<document.$formname.currsec.length; i++) {
 6234:             if (document.$formname.currsec.options[i].selected == true ) {
 6235:                 if (document.$formname.currsec.options[i].value != "" && document.$formname.currsec.options[i].value != null) {
 6236:                     if (numsections == 0) {
 6237:                         section = document.$formname.currsec.options[i].value
 6238:                         numsections = 1;
 6239:                     }
 6240:                     else {
 6241:                         section = section + "," +  document.$formname.currsec.options[i].value
 6242:                         numsections ++;
 6243:                     }
 6244:                 }
 6245:             }
 6246:         }
 6247:         if (document.$formname.newsec.value != "" && document.$formname.newsec.value != null) {
 6248:             if (numsections == 0) {
 6249:                 section = document.$formname.newsec.value
 6250:             }
 6251:             else {
 6252:                 section = section + "," +  document.$formname.newsec.value
 6253:             }
 6254:             newsecs = document.$formname.newsec.value.split(/,/g);
 6255:             numsections = numsections + newsecs.length;
 6256:         }
 6257:         if ((userrole == 'st') && (numsections > 1)) {
 6258:             if (document.$formname.crstype.value == 'Community') {
 6259:                 alert("$alerts{'inco'}. $alerts{'youh'} "+numsections+" $alerts{'sect'}.\\n$alerts{'plsm'}.")
 6260:             } else {
 6261:                 alert("$alerts{'inea'}. $alerts{'youh'} "+numsections+" $alerts{'sect'}.\\n$alerts{'plsm'}.")
 6262:             }
 6263:             return;
 6264:         }
 6265:         for (var j=0; j<newsecs.length; j++) {
 6266:             if ((newsecs[j] == 'all') || (newsecs[j] == 'none')) {
 6267:                 alert("'"+newsecs[j]+"' $alerts{'mayn'}.\\n$alerts{'plsc'}.");
 6268:                 return;
 6269:             }
 6270:             if (document.$formname.groups.value != '') {
 6271:                 var groups = document.$formname.groups.value.split(/,/g);
 6272:                 for (var k=0; k<groups.length; k++) {
 6273:                     if (newsecs[j] == groups[k]) {
 6274:                         if (document.$formname.crstype.value == 'Community') {
 6275:                             alert("'"+newsecs[j]+"' $alerts{'mayc'}.\\n$alerts{'secn'}. $alerts{'plsc'}.");
 6276:                         } else {
 6277:                             alert("'"+newsecs[j]+"' $alerts{'mayt'}.\\n$alerts{'secn'}. $alerts{'plsc'}.");
 6278:                         }
 6279:                         return;
 6280:                     }
 6281:                 }
 6282:             }
 6283:         }
 6284:         if ((userrole == 'cc') && (numsections > 0)) {
 6285:             alert("$alerts{'secd'} $cctext $alerts{'role'}.\\n$alerts{'accr'}.");
 6286:             section = "";
 6287:         }
 6288:         if ((userrole == 'co') && (numsections > 0)) {
 6289:             alert("$alerts{'secd'} $cotext $alerts{'role'}.\\n$alerts{'accr'}.");
 6290:             section = "";
 6291:         }
 6292: SCRIPTTOP
 6293:     if ($mode ne 'upload') {
 6294:         $dc_setcourse_code .= (<<"SCRIPTMID");
 6295:         var coursename = "_$env{'request.role.domain'}"+"_"+course+"_"+userrole
 6296:         var numcourse = getIndex(document.$formname.dccourse);
 6297:         if (numcourse == "-1") {
 6298:             if (document.$formname.type == 'Community') {
 6299:                 alert("$alerts{'thwc'}");
 6300:             } else {
 6301:                 alert("$alerts{'thwa'}");
 6302:             }
 6303:             return;
 6304:         }
 6305:         else {
 6306:             document.$formname.elements[numcourse].name = "act"+coursename;
 6307:             var numnewsec = getIndex(document.$formname.newsec);
 6308:             if (numnewsec != "-1") {
 6309:                 document.$formname.elements[numnewsec].name = "sec"+coursename;
 6310:                 document.$formname.elements[numnewsec].value = section;
 6311:             }
 6312:             var numstart = getIndex(document.$formname.start);
 6313:             if (numstart != "-1") {
 6314:                 document.$formname.elements[numstart].name = "start"+coursename;
 6315:             }
 6316:             var numend = getIndex(document.$formname.end);
 6317:             if (numend != "-1") {
 6318:                 document.$formname.elements[numend].name = "end"+coursename
 6319:             }
 6320: SCRIPTMID
 6321:         if ($showcredits) {
 6322:             $dc_setcourse_code .= <<ENDCRED;
 6323:             var numcredits = getIndex(document.$formname.credits);
 6324:             if (numcredits != "-1") {
 6325:                 document.$formname.elements[numcredits].name = "credits"+coursename;
 6326:             }
 6327: ENDCRED
 6328:         }
 6329:         $dc_setcourse_code .= <<ENDSCRIPT; 
 6330:         }
 6331:     }
 6332:     var authcheck = auth_check();
 6333:     if (authcheck == 'ok') {
 6334:         document.$formname.submit();
 6335:     }
 6336: }
 6337: ENDSCRIPT
 6338:     } else {
 6339:         $dc_setcourse_code .=  "
 6340:         document.$formname.sections.value = section;
 6341:     }
 6342:     return 'ok';
 6343: }
 6344: ";
 6345:     }
 6346:     $dc_setcourse_code .= (<<"ENDSCRIPT");
 6347: 
 6348:     function getIndex(caller) {
 6349:         for (var i=0;i<document.$formname.elements.length;i++) {
 6350:             if (document.$formname.elements[i] == caller) {
 6351:                 return i;
 6352:             }
 6353:         }
 6354:         return -1;
 6355:     }
 6356: ENDSCRIPT
 6357:     return $dc_setcourse_code;
 6358: }
 6359: 
 6360: sub verify_authen {
 6361:     my ($formname,$context,$domain) = @_;
 6362:     my %alerts = &authcheck_alerts();
 6363:     my $finish = "return 'ok';";
 6364:     if ($context eq 'author') {
 6365:         $finish = "document.$formname.submit();";
 6366:     }
 6367:     my ($numrules,$intargjs) =
 6368:         &passwd_validation_js('argpicked',$domain);
 6369:     my $outcome = <<"ENDSCRIPT";
 6370: 
 6371: function auth_check() {
 6372:     var logintype;
 6373:     if (document.$formname.login.length) {
 6374:         if (document.$formname.login.length > 0) {
 6375:             var loginpicked = 0;
 6376:             for (var i=0; i<document.$formname.login.length; i++) {
 6377:                 if (document.$formname.login[i].checked == true) {
 6378:                     loginpicked = 1;
 6379:                     logintype = document.$formname.login[i].value;
 6380:                 }
 6381:             }
 6382:             if (loginpicked == 0) {
 6383:                 alert("$alerts{'authen'}");
 6384:                 return;
 6385:             }
 6386:         }
 6387:     } else {
 6388:         logintype = document.$formname.login.value;
 6389:     }
 6390:     if (logintype == 'nochange') {
 6391:         return 'ok';
 6392:     }
 6393:     var argpicked = document.$formname.elements[logintype+'arg'].value;
 6394:     if ((argpicked == null) || (argpicked == '') || (typeof argpicked == 'undefined')) {
 6395:         var alertmsg = '';
 6396:         switch (logintype) {
 6397:             case 'krb':
 6398:                 alertmsg = '$alerts{'krb'}';
 6399:                 break;
 6400:             case 'int':
 6401:                 alertmsg = '$alerts{'ipass'}';
 6402:                 break;
 6403:             case 'fsys':
 6404:                 alertmsg = '$alerts{'ipass'}';
 6405:                 break;
 6406:             case 'loc':
 6407:                 alertmsg = '';
 6408:                 break;
 6409:             default:
 6410:                 alertmsg = '';
 6411:         }
 6412:         if (alertmsg != '') {
 6413:             alert(alertmsg);
 6414:             return;
 6415:         }
 6416:     } else if (logintype == 'int') {
 6417:         var numrules = $numrules;
 6418:         if (numrules > 0) {
 6419: $intargjs
 6420:         }
 6421:     }
 6422:     $finish
 6423: }
 6424: ENDSCRIPT
 6425: }
 6426: 
 6427: sub sectioncheck_alerts {
 6428:     my %alerts = &Apache::lonlocal::texthash(
 6429:                     curd => 'You must select a course or community in the current domain',
 6430:                     inea => 'In each course, each user may only have one student role at a time',
 6431:                     inco => 'In each community, each user may only have one member role at a time', 
 6432:                     youh => 'You had selected',
 6433:                     sect => 'sections',
 6434:                     plsm => 'Please modify your selections so they include no more than one section',
 6435:                     mayn => 'may not be used as the name for a section, as it is a reserved word',
 6436:                     plsc => 'Please choose a different section name',
 6437:                     mayt => 'may not be used as the name for a section, as it is the name of a course group',
 6438:                     mayc => 'may not be used as the name for a section, as it is the name of a community group',
 6439:                     secn => 'Section names and group names must be distinct',
 6440:                     secd => 'Section designations do not apply to ',
 6441:                     role => 'roles',
 6442:                     accr => 'role will be added with access to all sections',
 6443:                     thwa => 'There was a problem with your course selection',
 6444:                     thwc => 'There was a problem with your community selection',
 6445:                  );
 6446:     &js_escape(\%alerts);
 6447:     return %alerts;
 6448: }
 6449: 
 6450: sub authcheck_alerts {
 6451:     my %alerts = 
 6452:         &Apache::lonlocal::texthash(
 6453:                     authen => 'You must choose an authentication type.',
 6454:                     krb    => 'You need to specify the Kerberos domain.',
 6455:                     ipass  => 'You need to specify the initial password.',
 6456:         );
 6457:     &js_escape(\%alerts);
 6458:     return %alerts;
 6459: }
 6460: 
 6461: sub is_courseowner {
 6462:     my ($thiscourse,$courseowner) = @_;
 6463:     if ($courseowner eq '') {
 6464:         if ($env{'request.course.id'} eq $thiscourse) {
 6465:             $courseowner = $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 6466:         }
 6467:     }
 6468:     if ($courseowner ne '') {
 6469:         if ($courseowner eq $env{'user.name'}.':'.$env{'user.domain'}) {
 6470:             return 1;
 6471:         }
 6472:     }
 6473:     return;
 6474: }
 6475: 
 6476: sub get_selfenroll_titles {
 6477:     my @row = ('types','registered','enroll_dates','access_dates','section',
 6478:                'approval','limit');
 6479:     my %lt = &Apache::lonlocal::texthash (
 6480:                 types        => 'Users allowed to self-enroll',
 6481:                 registered   => 'Registration status (official courses)' ,
 6482:                 enroll_dates => 'Dates self-enrollment available',
 6483:                 access_dates => 'Access dates for self-enrolling users',
 6484:                 section      => "Self-enrolling users' section",
 6485:                 approval     => 'Processing of requests',
 6486:                 limit        => 'Enrollment limit',
 6487:              );
 6488:     return (\@row,\%lt);
 6489: }
 6490: 
 6491: sub selfenroll_default_descs {
 6492:     my %desc = (
 6493:                  types => {
 6494:                             dom => &mt('Course domain'),
 6495:                             all => &mt('Any domain'),
 6496:                             ''  => &mt('None'),
 6497:                           },
 6498:                  limit => {
 6499:                             none         => &mt('No limit'),
 6500:                             allstudents  => &mt('Limit by total students'),
 6501:                             selfenrolled => &mt('Limit by total self-enrolled'),
 6502:                           },
 6503:                  approval => {
 6504:                                 '0' => &mt('Processed automatically'),
 6505:                                 '1' => &mt('Queued for approval'),
 6506:                                 '2' => &mt('Queued, pending validation'),
 6507:                              },
 6508:                  registered => {
 6509:                                  0 => 'No registration required',
 6510:                                  1 => 'Registered students only',
 6511:                                },
 6512:                );
 6513:     return %desc;
 6514: }
 6515: 
 6516: sub selfenroll_validation_types {
 6517:     my @items = ('url','fields','button','markup');
 6518:     my %names =  &Apache::lonlocal::texthash (
 6519:             url      => 'Web address of validation server/script',
 6520:             fields   => 'Form fields to send to validator',
 6521:             button   => 'Text for validation button',
 6522:             markup   => 'Validation description (HTML)',
 6523:     );
 6524:     my @fields = ('username','domain','uniquecode','course','coursetype','description');
 6525:     return (\@items,\%names,\@fields);
 6526: }
 6527: 
 6528: sub get_extended_type {
 6529:     my ($cdom,$cnum,$crstype,$current) = @_;
 6530:     my $type = 'unofficial';
 6531:     my %settings;
 6532:     if (ref($current) eq 'HASH') {
 6533:         %settings = %{$current};
 6534:     } else {
 6535:         %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook'],$cdom,$cnum);
 6536:     }
 6537:     if ($crstype eq 'Community') {
 6538:         $type = 'community';
 6539:     } elsif ($crstype eq 'Placement') {
 6540:         $type = 'placement';
 6541:     } elsif ($settings{'internal.coursecode'}) {
 6542:         $type = 'official';
 6543:     } elsif ($settings{'internal.textbook'}) {
 6544:         $type = 'textbook';
 6545:     }
 6546:     return $type;
 6547: }
 6548: 
 6549: sub selfenrollment_administration {
 6550:     my ($cdom,$cnum,$crstype,$coursehash) = @_;
 6551:     my %settings;
 6552:     if (ref($coursehash) eq 'HASH') {
 6553:         %settings = %{$coursehash};
 6554:     } else {
 6555:         %settings = &Apache::lonnet::get('environment',
 6556:                         ['internal.selfenrollmgrdc','internal.selfenrollmgrcc',
 6557:                          'internal.coursecode','internal.textbook'],$cdom,$cnum);
 6558:     }
 6559:     my ($possconfigs) = &get_selfenroll_titles(); 
 6560:     my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6561:     my $selfenrolltype = &get_extended_type($cdom,$cnum,$crstype,\%settings);
 6562: 
 6563:     my (@in_course,@in_domain); 
 6564:     if ($settings{'internal.selfenrollmgrcc'} ne '') {
 6565:         @in_course = split(/,/,$settings{'internal.selfenrollmgrcc'}); 
 6566:         my @diffs = &Apache::loncommon::compare_arrays($possconfigs,\@in_course);
 6567:         unless (@diffs) {
 6568:             return (\@in_course,\@in_domain);
 6569:         }
 6570:     }
 6571:     if ($settings{'internal.selfenrollmgrdc'} ne '') {
 6572:         my @in_domain = split(/,/,$settings{'internal.selfenrollmgrdc'});
 6573:         my @diffs = &Apache::loncommon::compare_arrays(\@in_domain,$possconfigs);
 6574:         unless (@diffs) {
 6575:             return (\@in_course,\@in_domain);
 6576:         }
 6577:     }
 6578:     my @combined = @in_course;
 6579:     push(@combined,@in_domain);
 6580:     my @diffs = &Apache::loncommon::compare_arrays(\@combined,$possconfigs); 
 6581:     unless (@diffs) {
 6582:         return (\@in_course,\@in_domain);
 6583:     }
 6584:     if ($domdefaults{$selfenrolltype.'selfenrolladmdc'} eq '') {
 6585:         push(@in_course,@diffs);
 6586:     } else {
 6587:         my @defaultdc = split(/,/,$domdefaults{$selfenrolltype.'selfenrolladmdc'});
 6588:         foreach my $item (@diffs) {
 6589:             if (grep(/^\Q$item\E$/,@defaultdc)) {
 6590:                 push(@in_domain,$item);
 6591:             } else {
 6592:                 push(@in_course,$item);
 6593:             }
 6594:         }
 6595:     }
 6596:     return (\@in_course,\@in_domain);
 6597: }
 6598: 
 6599: sub custom_role_header {
 6600:     my ($context,$crstype,$templaterolerefs,$prefix) = @_;
 6601:     my %lt = &Apache::lonlocal::texthash(
 6602:                  sele => 'Select a Template',
 6603:     );
 6604:     my ($context_code,$button_code);
 6605:     if ($context eq 'domain') {
 6606:         $context_code = &custom_coursetype_switch($crstype,$prefix);
 6607:     }
 6608:     if (ref($templaterolerefs) eq 'ARRAY') {
 6609:         foreach my $role (@{$templaterolerefs}) {
 6610:             my $display = 'inline';
 6611:             if (($context eq 'domain') && ($role eq 'co')) {
 6612:                 $display = 'none';
 6613:             }
 6614:             $button_code .= &make_button_code($role,$crstype,$display,$prefix).' ';
 6615:         }
 6616:     }
 6617:     return <<"END";
 6618: <div class="LC_left_float">
 6619: <fieldset>
 6620: <legend>$lt{'sele'}</legend>
 6621: $button_code
 6622: </fieldset></div>
 6623: $context_code
 6624: <br clear="all" />
 6625: END
 6626: }
 6627: 
 6628: sub custom_coursetype_switch {
 6629:     my ($crstype,$prefix) = @_;
 6630:     my ($checkedcourse,$checkedcommunity);
 6631:     if ($crstype eq 'Community') {
 6632:         $checkedcommunity = ' checked="checked"';
 6633:     } else {
 6634:         $checkedcourse = ' checked="checked"';
 6635:     }
 6636:     my %lt = &Apache::lonlocal::texthash(
 6637:         cont => 'Context',
 6638:         cour => 'Course',
 6639:         comm => 'Community',
 6640:     );
 6641:     return <<"END";
 6642: <div class="LC_left_float">
 6643: <fieldset>
 6644: <legend>$lt{'cont'}</legend>
 6645: <label>
 6646: <input type="radio" name="${prefix}_custrolecrstype" value="Course"$checkedcourse onclick="javascript:customSwitchType('$prefix');" />
 6647: $lt{'cour'}
 6648: </label>&nbsp;&nbsp;
 6649: <label>
 6650: <input type="radio" name="${prefix}_custrolecrstype" value="Community"$checkedcommunity onclick="javascript:customSwitchType('$prefix');" />
 6651: $lt{'comm'}
 6652: </label>
 6653: </fieldset>
 6654: </div>
 6655: END
 6656: }
 6657: 
 6658: sub custom_role_table {
 6659:     my ($crstype,$full,$levels,$levelscurrent,$prefix,$add_class,$id) = @_;
 6660:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 6661:                    (ref($levelscurrent) eq 'HASH'));
 6662:     my %lt=&Apache::lonlocal::texthash (
 6663:                     'prv'  => "Privilege",
 6664:                     'crl'  => "Course Level",
 6665:                     'dml'  => "Domain Level",
 6666:                     'ssl'  => "System Level");
 6667:     my %cr = (
 6668:                course => '_c',
 6669:                domain => '_d',
 6670:                system => '_s',
 6671:              );
 6672: 
 6673:     my $output=&Apache::loncommon::start_data_table($add_class,$id).
 6674:                &Apache::loncommon::start_data_table_header_row().
 6675:                '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
 6676:                '</th><th>'.$lt{'ssl'}.'</th>'.
 6677:                &Apache::loncommon::end_data_table_header_row();
 6678:     foreach my $priv (sort(keys(%{$full}))) {
 6679:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 6680:         $output .= &Apache::loncommon::start_data_table_row().
 6681:                   '<td><span id="'.$prefix.$priv.'">'.$privtext.'</span></td>';
 6682:         foreach my $type ('course','domain','system') {
 6683:             if (($type eq 'system') && ($priv eq 'bre') && ($crstype eq 'Community')) {
 6684:                 $output .= '<td>&nbsp;</td>';
 6685:             } else {
 6686:                 $output .= '<td>'.
 6687:                   ($levels->{$type}{$priv}?'<input type="checkbox" id="'.$prefix.$priv.$cr{$type}.'"'.
 6688:                   ' name="'.$prefix.$priv.$cr{$type}.'"'.
 6689:                   ($levelscurrent->{$type}{$priv}?' checked="checked"':'').' />':'&nbsp;').
 6690:                   '</td>';
 6691:             }
 6692:         }
 6693:         $output .= &Apache::loncommon::end_data_table_row();
 6694:     }
 6695:     $output .= &Apache::loncommon::end_data_table();
 6696:     return $output;
 6697: }
 6698: 
 6699: sub custom_role_privs {
 6700:     my ($privs,$full,$levels,$levelscurrent)= @_;
 6701:     return unless ((ref($privs) eq 'HASH') && (ref($full) eq 'HASH') &&
 6702:                    (ref($levels) eq 'HASH') && (ref($levelscurrent) eq 'HASH'));
 6703:     my %cr = (
 6704:                course => 'cr:c',
 6705:                domain => 'cr:d',
 6706:                system => 'cr:s',
 6707:              );
 6708:     foreach my $type ('course','domain','system') {
 6709:         foreach my $item (split(/\:/,$Apache::lonnet::pr{$cr{$type}})) {
 6710:             my ($priv,$restrict)=split(/\&/,$item);
 6711:             if (!$restrict) { $restrict='F'; }
 6712:             $levels->{$type}->{$priv}=$restrict;
 6713:             if ($privs->{$type}=~/\:$priv/) {
 6714:                 $levelscurrent->{$type}->{$priv}=1;
 6715:             }
 6716:             $full->{$priv}=1;
 6717:         }
 6718:     }
 6719:     return;
 6720: }
 6721: 
 6722: sub custom_template_roles {
 6723:     my ($context,$crstype) = @_;
 6724:     my @template_roles = ("in","ta","ep");
 6725:     if (($context eq 'domain') || ($context eq 'domprefs')) {
 6726:         push(@template_roles,"ad");
 6727:     }
 6728:     push(@template_roles,"st");
 6729:     if ($context eq 'domain') {
 6730:         unshift(@template_roles,('co','cc'));
 6731:     } else {
 6732:         if ($crstype eq 'Community') {
 6733:             unshift(@template_roles,'co');
 6734:         } else {
 6735:             unshift(@template_roles,'cc');
 6736:         }
 6737:     }
 6738:     return @template_roles;
 6739: }
 6740: 
 6741: sub custom_roledefs_js {
 6742:     my ($context,$crstype,$formname,$full,$templaterolesref,$jsback) = @_;
 6743:     my $button_code = "\n";
 6744:     my $head_script = "\n";
 6745:     my (%roletitlestr,$rolenamestr);
 6746:     my %role_titles = (
 6747:                         Course    => [],
 6748:                         Community => [],
 6749:                       );
 6750:     $head_script .= '<script type="text/javascript">'."\n"
 6751:                    .'// <![CDATA['."\n";
 6752:     if (ref($templaterolesref) eq 'ARRAY') {
 6753:         if ($context eq 'domain') {
 6754:             $rolenamestr = join("','",@{$templaterolesref});
 6755:         }
 6756:         foreach my $role (@{$templaterolesref}) {
 6757:             $head_script .= &make_script_template($role,$crstype,$formname);
 6758:             if ($context eq 'domain') {
 6759:                 foreach my $type ('Course','Community') {
 6760:                     push(@{$role_titles{$type}},&Apache::lonnet::plaintext($role,$type));
 6761:                 }
 6762:             }
 6763:         }
 6764:     }
 6765:     if ($context eq 'domain') {
 6766:         foreach my $type ('Course','Community') {
 6767:             $roletitlestr{$type} = join("','",@{$role_titles{$type}});
 6768:         }
 6769:         my %pt = (
 6770:             Community => {
 6771:                            cst => &mt('Grant/revoke role of Member'),
 6772:                            mdc => &mt('Edit community contents'),
 6773:                            pch => &mt('Post discussion on community resources'),
 6774:                            pfo => &mt('Print for other users and entire community'),
 6775:                          },
 6776:             Course    => {
 6777:                            cst => &mt('Grant/revoke role of Student'),
 6778:                            mdc => &mt('Edit course contents'),
 6779:                            pch => &mt('Post discussion on course resources'),
 6780:                            pfo => &mt('Print for other users and entire course'),
 6781:                          },
 6782:         );
 6783:         $head_script .= <<"ENDJS";
 6784: function customSwitchType(prefix) {
 6785:     var privnames = new Array('cst','mdc','pch','pfo');
 6786:     var privtxtcrs = new Array('$pt{Course}{cst}','$pt{Course}{mdc}','$pt{Course}{pch}','$pt{Course}{pfo}');
 6787:     var privtxtcom = new Array('$pt{Community}{cst}','$pt{Community}{mdc}','$pt{Community}{pch}','$pt{Community}{pfo}');
 6788:     var rolenames = new Array('$rolenamestr');
 6789:     var rolescrs = new Array('$roletitlestr{Course}');
 6790:     var rolescom = new Array('$roletitlestr{Community}');
 6791:     var radio = prefix+'_custrolecrstype';
 6792:     if (document.$formname.elements[radio].length > 1) {
 6793:         for (var i=0; i<document.$formname.elements[radio].length; i++) {
 6794:             if (document.$formname.elements[radio][i].checked) {
 6795:                 if ((document.getElementById(prefix+'bre_s')) && (document.getElementById(prefix+'bro_s'))) {
 6796:                     if (document.$formname.elements[radio][i].value == 'Community') {
 6797:                         if (document.getElementById(prefix+'bre_s').checked) {
 6798:                             document.getElementById(prefix+'bro_s').checked = true;
 6799:                             document.getElementById(prefix+'bre_s').checked = false;
 6800: 
 6801:                         }
 6802:                         document.getElementById(prefix+'bre_s').style.visibility = 'hidden';
 6803:                     } else {
 6804:                         document.getElementById(prefix+'bre_s').style.visibility = 'visible';
 6805:                         if (document.getElementById(prefix+'bro_s').checked) {
 6806:                             document.getElementById(prefix+'bre_s').checked = true;
 6807:                             document.getElementById(prefix+'bro_s').checked = false;
 6808:                         }
 6809:                     }
 6810:                 }
 6811:                 for (var j=0; j<privnames.length; j++) {
 6812:                     if (document.getElementById(prefix+privnames[j])) {
 6813:                         if (document.getElementById(prefix+privnames[j])) {
 6814:                             if (document.$formname.elements[radio][i].value == 'Course') {
 6815:                                 document.getElementById(prefix+privnames[j]).innerHTML = privtxtcrs[j];
 6816:                             } else {
 6817:                                 document.getElementById(prefix+privnames[j]).innerHTML = privtxtcom[j];
 6818:                             }
 6819:                         }
 6820:                     }
 6821:                 }
 6822:                 for (var j=0; j<rolenames.length; j++) {
 6823:                     if (document.getElementById(prefix+rolenames[j])) {
 6824:                         if (document.getElementById(prefix+rolenames[j])) {
 6825:                             if (document.$formname.elements[radio][i].value == 'Course') {
 6826:                                 document.getElementById(prefix+rolenames[j]).value = rolescrs[j];
 6827:                                 if (rolenames[j] == 'cc') {
 6828:                                     document.getElementById(prefix+rolenames[j]).style.display = 'inline';
 6829:                                 }
 6830:                                 if (rolenames[j] == 'co') {
 6831:                                     document.getElementById(prefix+rolenames[j]).style.display = 'none';
 6832:                                 }
 6833:                             } else {
 6834:                                 document.getElementById(prefix+rolenames[j]).value = rolescom[j];
 6835:                                 if (rolenames[j] == 'cc') {
 6836:                                     document.getElementById(prefix+rolenames[j]).style.display = 'none';
 6837:                                 }
 6838:                                 if (rolenames[j] == 'co') {
 6839:                                     document.getElementById(prefix+rolenames[j]).style.display = 'inline';
 6840:                                 }
 6841:                             }
 6842:                         }
 6843:                     }
 6844:                 }
 6845:             }
 6846:         }
 6847:     }
 6848:     return;
 6849: }
 6850: ENDJS
 6851:     }
 6852:     $head_script .= "\n".$jsback."\n"
 6853:                    .'// ]]>'."\n"
 6854:                    .'</script>'."\n";
 6855:     return $head_script;
 6856: }
 6857: 
 6858: # --------------------------------------------------------
 6859: sub make_script_template {
 6860:     my ($role,$crstype,$formname) = @_;
 6861:     my $return_script = 'function set_'.$role.'(prefix) {'."\n";
 6862:     my (%full_by_level,%role_priv);
 6863:     foreach my $level ('c','d','s') {
 6864:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:'.$level})) {
 6865:             next if (($level eq 's') && ($crstype eq 'Community') && ($item eq 'bre&S'));
 6866:             my ($priv,$restrict)=split(/\&/,$item);
 6867:             $full_by_level{$level}{$priv}=1;
 6868:         }
 6869:         $role_priv{$level} = {};
 6870:         my @temp = split(/:/,$Apache::lonnet::pr{$role.':'.$level});
 6871:         foreach my $priv (@temp) {
 6872:             my ($priv_item, $dummy) = split(/\&/,$priv);
 6873:             $role_priv{$level}{$priv_item} = 1;
 6874:         }
 6875:     }
 6876:     my %to_check = (
 6877:                       c => ['c','d','s'],
 6878:                       d => ['d','s'],
 6879:                       s => ['s'],
 6880:                    );
 6881:     foreach my $level ('c','d','s') {
 6882:         if (ref($full_by_level{$level}) eq 'HASH') {
 6883:             foreach my $priv (keys(%{$full_by_level{$level}})) {
 6884:                 my $value = 'false';
 6885:                 if (ref($to_check{$level}) eq 'ARRAY') {
 6886:                     foreach my $lett (@{$to_check{$level}}) {
 6887:                         if (exists($role_priv{$lett}{$priv})) {
 6888:                             $value = 'true';
 6889:                             last;
 6890:                         }
 6891:                     }
 6892:                     $return_script .= "document.$formname.elements[prefix+'".$priv."_".$level."'].checked = $value;\n";
 6893:                 }
 6894:             }
 6895:         }
 6896:     }
 6897:     $return_script .= '}'."\n";
 6898:     return ($return_script);
 6899: }
 6900: # ----------------------------------------------------------
 6901: sub make_button_code {
 6902:     my ($role,$crstype,$display,$prefix) = @_;
 6903:     my $label = &Apache::lonnet::plaintext($role,$crstype);
 6904:     my $button_code = '<input type="button" onclick="set_'.$role."('$prefix'".')" '.
 6905:                       'id="'.$prefix.$role.'" value="'.$label.'" '.
 6906:                       'style="display:'.$display.'" />';
 6907:     return ($button_code);
 6908: }
 6909: 
 6910: sub custom_role_update {
 6911:     my ($rolename,$prefix) = @_;
 6912: # ------------------------------------------------------- What can be assigned?
 6913:     my %privs = (
 6914:                       c => '',
 6915:                       d => '',
 6916:                       s => '',
 6917:                     );
 6918:     foreach my $level (keys(%privs)) {
 6919:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:'.$level})) {
 6920:             my ($priv,$restrict)=split(/\&/,$item);
 6921:             if (!$restrict) { $restrict=''; }
 6922:             if ($env{'form.'.$prefix.$priv.'_'.$level}) {
 6923:                 $privs{$level} .=':'.$item;
 6924:             }
 6925:         }
 6926:     }
 6927:     return %privs;
 6928: }
 6929: 
 6930: sub adhoc_status_types {
 6931:     my ($cdom,$context,$role,$selectedref,$othertitle,$usertypes,$types,$disabled) = @_;
 6932:     my $output = &Apache::loncommon::start_data_table();
 6933:     my $numinrow = 3;
 6934:     my $rem;
 6935:     if (ref($types) eq 'ARRAY') {
 6936:         for (my $i=0; $i<@{$types}; $i++) {
 6937:             if (defined($usertypes->{$types->[$i]})) {
 6938:                 my $rem = $i%($numinrow);
 6939:                 if ($rem == 0) {
 6940:                     if ($i > 0) {
 6941:                         $output .= &Apache::loncommon::end_data_table_row();
 6942:                     }
 6943:                     $output .= &Apache::loncommon::start_data_table_row();
 6944:                 }
 6945:                 my $check;
 6946:                 if (ref($selectedref) eq 'ARRAY') {
 6947:                     if (grep(/^\Q$types->[$i]\E$/,@{$selectedref})) {
 6948:                         $check = ' checked="checked"';
 6949:                     }
 6950:                 }
 6951:                 $output .= '<td>'.
 6952:                            '<span class="LC_nobreak"><label>'.
 6953:                            '<input type="checkbox" name="'.$context.$role.'_status" '.
 6954:                            'value="'.$types->[$i].'"'.$check.$disabled.' />'.
 6955:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 6956:             }
 6957:         }
 6958:         $rem = @{$types}%($numinrow);
 6959:     }
 6960:     my $colsleft = $numinrow - $rem;
 6961:     if (($rem == 0) && (@{$types} > 0)) {
 6962:         $output .= &Apache::loncommon::start_data_table_row();
 6963:     }
 6964:     if ($colsleft > 1) {
 6965:         $output .= '<td colspan="'.$colsleft.'">';
 6966:     } else {
 6967:         $output .= '<td>';
 6968:     }
 6969:     my $defcheck;
 6970:     if (ref($selectedref) eq 'ARRAY') {
 6971:         if (grep(/^default$/,@{$selectedref})) {
 6972:             $defcheck = ' checked="checked"';
 6973:         }
 6974:     }
 6975:     $output .= '<span class="LC_nobreak"><label>'.
 6976:                '<input type="checkbox" name="'.$context.$role.'_status"'.
 6977:                'value="default"'.$defcheck.$disabled.' />'.
 6978:                $othertitle.'</label></span></td>'.
 6979:                &Apache::loncommon::end_data_table_row().
 6980:                &Apache::loncommon::end_data_table();
 6981:     return $output;
 6982: }
 6983: 
 6984: sub adhoc_staff {
 6985:     my ($access,$context,$role,$selectedref,$adhocref,$disabled) = @_;
 6986:     my $output;
 6987:     if (ref($adhocref) eq 'HASH') {
 6988:         my %by_fullname;
 6989:         my $numinrow = 4;
 6990:         my $rem;
 6991:         my @personnel = keys(%{$adhocref});
 6992:         if (@personnel) {
 6993:             foreach my $person (@personnel) {
 6994:                 my ($uname,$udom) = split(/:/,$person);
 6995:                 my $fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
 6996:                 $by_fullname{$fullname} = $person;
 6997:             }
 6998:             my @sorted = sort(keys(%by_fullname));
 6999:             my $count = scalar(@sorted);
 7000:             $output = &Apache::loncommon::start_data_table();
 7001:             for (my $i=0; $i<$count; $i++) {
 7002:                 my $rem = $i%($numinrow);
 7003:                 if ($rem == 0) {
 7004:                     if ($i > 0) {
 7005:                         $output .= &Apache::loncommon::end_data_table_row();
 7006:                     }
 7007:                     $output .= &Apache::loncommon::start_data_table_row();
 7008:                 }
 7009:                 my $check;
 7010:                 my $user = $by_fullname{$sorted[$i]};
 7011:                 if (ref($selectedref) eq 'ARRAY') {
 7012:                     if (grep(/^\Q$user\E$/,@{$selectedref})) {
 7013:                         $check = ' checked="checked"';
 7014:                     }
 7015:                 }
 7016:                 if ($i == $count-1) {
 7017:                     my $colsleft = $numinrow - $rem;
 7018:                     if ($colsleft > 1) {
 7019:                         $output .= '<td colspan="'.$colsleft.'">';
 7020:                     } else {
 7021:                         $output .= '<td>';
 7022:                     }
 7023:                 } else {
 7024:                     $output .= '<td>';
 7025:                 }
 7026:                 $output .= '<span class="LC_nobreak"><label>'.
 7027:                            '<input type="checkbox" name="'.$context.$role.'_staff_'.$access.'" '.
 7028:                            'value="'.$user.'"'.$check.$disabled.' />'.$sorted[$i].
 7029:                            '</label></span></td>';
 7030:                 if ($i == $count-1) {
 7031:                     $output .= &Apache::loncommon::end_data_table_row();
 7032:                 }
 7033:             }
 7034:             $output .= &Apache::loncommon::end_data_table();
 7035:         }
 7036:     }
 7037:     return $output;
 7038: }
 7039: 
 7040: 
 7041: 1;
 7042: 

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