File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.184.4.10: download - view: text, annotated - select for diffs
Tue Aug 24 00:22:59 2021 UTC (2 years, 9 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_4_uiuc, version_2_11_4_msu, version_2_11_4
Diff to branchpoint 1.184: preferred, unified
- For 2.11
  Backport 1.208, 1.209

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

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