File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.194: download - view: text, annotated - select for diffs
Fri Mar 23 01:01:21 2018 UTC (6 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Provider
  - Creation of new LON-CAPA user account available from an LTI Consumer.
  - Creation of new LON-CAPA course available from an LTI Consumer.
  - Self-enrollment in a LON-CAPA course available from an LTI Consumer.

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

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