File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.184.4.5: download - view: text, annotated - select for diffs
Mon Aug 26 01:28:51 2019 UTC (4 years, 8 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.184: preferred, unified
- For 2.11
  Backport 1.202, 1.203

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

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