File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.211: download - view: text, annotated - select for diffs
Thu Nov 17 19:07:21 2022 UTC (17 months, 3 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Don't display "Manage Users" menu with "Helpdesk Access" link to course
  owner or co-owner for requests for /adm/createuser when course is being
  viewed as a student.

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

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