File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.458: download - view: text, annotated - select for diffs
Fri Dec 24 19:42:37 2021 UTC (2 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Provider.
  Users may be assigned right to create course after LTI launch.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.458 2021/12/24 19:42:37 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: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::loncreateuser;
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::loncreateuser.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40:     Handler to create users and custom roles
   41: 
   42:     Provides an Apache handler for creating users,
   43:     editing their login parameters, roles, and removing roles, and
   44:     also creating and assigning custom roles.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: =head2 Custom Roles
   49: 
   50: In LON-CAPA, roles are actually collections of privileges. "Teaching
   51: Assistant", "Course Coordinator", and other such roles are really just
   52: collection of privileges that are useful in many circumstances.
   53: 
   54: Custom roles can be defined by a Domain Coordinator, Course Coordinator
   55: or Community Coordinator via the Manage User functionality.
   56: The custom role editor screen will show all privileges which can be
   57: assigned to users. For a complete list of privileges, please see 
   58: C</home/httpd/lonTabs/rolesplain.tab>.
   59: 
   60: Custom role definitions are stored in the C<roles.db> file of the creator
   61: of the role.
   62: 
   63: =cut
   64: 
   65: use strict;
   66: use Apache::Constants qw(:common :http);
   67: use Apache::lonnet;
   68: use Apache::loncommon;
   69: use Apache::lonlocal;
   70: use Apache::longroup;
   71: use Apache::lonuserutils;
   72: use Apache::loncoursequeueadmin;
   73: use LONCAPA qw(:DEFAULT :match);
   74: use HTML::Entities;
   75: 
   76: my $loginscript; # piece of javascript used in two separate instances
   77: my $authformnop;
   78: my $authformkrb;
   79: my $authformint;
   80: my $authformfsys;
   81: my $authformloc;
   82: my $authformlti;
   83: 
   84: sub initialize_authen_forms {
   85:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   86:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   87:     my %param = ( formname => $formname,
   88:                   kerb_def_dom => $krbdefdom,
   89:                   kerb_def_auth => $krbdef,
   90:                   domain => $dom,
   91:                 );
   92:     my %abv_auth = &auth_abbrev();
   93:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix|lti):(.*)$/) {
   94:         my $long_auth = $1;
   95:         my $curr_autharg = $2;
   96:         my %abv_auth = &auth_abbrev();
   97:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   98:         if ($long_auth =~ /^krb(4|5)$/) {
   99:             $param{'curr_kerb_ver'} = $1;
  100:             $param{'curr_autharg'} = $curr_autharg;
  101:         }
  102:         if ($mode eq 'modifyuser') {
  103:             $param{'mode'} = $mode;
  104:         }
  105:     }
  106:     $loginscript  = &Apache::loncommon::authform_header(%param);
  107:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  108:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  109:     $authformint  = &Apache::loncommon::authform_internal(%param);
  110:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  111:     $authformloc  = &Apache::loncommon::authform_local(%param);
  112:     $authformlti  = &Apache::loncommon::authform_lti(%param);
  113: }
  114: 
  115: sub auth_abbrev {
  116:     my %abv_auth = (
  117:                      krb5      => 'krb',
  118:                      krb4      => 'krb',
  119:                      internal  => 'int',
  120:                      localauth => 'loc',
  121:                      unix      => 'fsys',
  122:                      lti       => 'lti',
  123:                    );
  124:     return %abv_auth;
  125: }
  126: 
  127: # ====================================================
  128: 
  129: sub user_quotas {
  130:     my ($ccuname,$ccdomain) = @_;
  131:     my %lt = &Apache::lonlocal::texthash(
  132:                    'usrt'      => "User Tools",
  133:                    'cust'      => "Custom quota",
  134:                    'chqu'      => "Change quota",
  135:     );
  136:    
  137:     my $quota_javascript = <<"END_SCRIPT";
  138: <script type="text/javascript">
  139: // <![CDATA[
  140: function quota_changes(caller,context) {
  141:     var customoff = document.getElementById('custom_'+context+'quota_off');
  142:     var customon = document.getElementById('custom_'+context+'quota_on');
  143:     var number = document.getElementById(context+'quota');
  144:     if (caller == "custom") {
  145:         if (customoff) {
  146:             if (customoff.checked) {
  147:                 number.value = "";
  148:             }
  149:         }
  150:     }
  151:     if (caller == "quota") {
  152:         if (customon) {
  153:             customon.checked = true;
  154:         }
  155:     }
  156:     return;
  157: }
  158: // ]]>
  159: </script>
  160: END_SCRIPT
  161:     my $longinsttype;
  162:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  163:     my $output = $quota_javascript."\n".
  164:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  165:                  &Apache::loncommon::start_data_table();
  166: 
  167:     if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
  168:         (&Apache::lonnet::allowed('udp',$ccdomain))) {
  169:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  170:     }
  171: 
  172:     my %titles = &Apache::lonlocal::texthash (
  173:                     portfolio => "Disk space allocated to user's portfolio files",
  174:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  175:                  );
  176:     foreach my $name ('portfolio','author') {
  177:         my ($currquota,$quotatype,$inststatus,$defquota) =
  178:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  179:         if ($longinsttype eq '') { 
  180:             if ($inststatus ne '') {
  181:                 if ($usertypes->{$inststatus} ne '') {
  182:                     $longinsttype = $usertypes->{$inststatus};
  183:                 }
  184:             }
  185:         }
  186:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  187:         $custom_on = ' ';
  188:         $custom_off = ' checked="checked" ';
  189:         if ($quotatype eq 'custom') {
  190:             $custom_on = $custom_off;
  191:             $custom_off = ' ';
  192:             $showquota = $currquota;
  193:             if ($longinsttype eq '') {
  194:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  195:                               .' MB.',$defquota);
  196:             } else {
  197:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  198:                                    " MB, as determined by the user's institutional".
  199:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  200:             }
  201:         } else {
  202:             if ($longinsttype eq '') {
  203:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  204:                               .' MB.',$defquota);
  205:             } else {
  206:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  207:                                    " MB, is determined by the user's institutional".
  208:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  209:             }
  210:         }
  211: 
  212:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  213:             $output .= '<tr class="LC_info_row">'."\n".
  214:                        '    <td>'.$titles{$name}.'</td>'."\n".
  215:                        '  </tr>'."\n".
  216:                        &Apache::loncommon::start_data_table_row()."\n".
  217:                        '  <td><span class="LC_nobreak">'.
  218:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  219:                        $defaultinfo.'</td>'."\n".
  220:                        &Apache::loncommon::end_data_table_row()."\n".
  221:                        &Apache::loncommon::start_data_table_row()."\n".
  222:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  223:                        ': <label>'.
  224:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  225:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  226:                        ' /><span class="LC_nobreak">'.
  227:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  228:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  229:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  230:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  231:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  232:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  233:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  234:                        &Apache::loncommon::end_data_table_row()."\n";
  235:         }
  236:     }
  237:     $output .= &Apache::loncommon::end_data_table();
  238:     return $output;
  239: }
  240: 
  241: sub build_tools_display {
  242:     my ($ccuname,$ccdomain,$context) = @_;
  243:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  244:         $colspan,$isadv,%domconfig);
  245:     my %lt = &Apache::lonlocal::texthash (
  246:                    'blog'       => "Personal User Blog",
  247:                    'aboutme'    => "Personal Information Page",
  248:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  249:                    'portfolio'  => "Personal User Portfolio",
  250:                    'avai'       => "Available",
  251:                    'cusa'       => "availability",
  252:                    'chse'       => "Change setting",
  253:                    'usde'       => "Use default",
  254:                    'uscu'       => "Use custom",
  255:                    'official'   => 'Can request creation of official courses',
  256:                    'unofficial' => 'Can request creation of unofficial courses',
  257:                    'community'  => 'Can request creation of communities',
  258:                    'textbook'   => 'Can request creation of textbook courses',
  259:                    'placement'  => 'Can request creation of placement tests',
  260:                    'lti'        => 'Can request creation of LTI courses',
  261:                    'requestauthor'  => 'Can request author space',
  262:     );
  263:     if ($context eq 'requestcourses') {
  264:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  265:                       'requestcourses.official','requestcourses.unofficial',
  266:                       'requestcourses.community','requestcourses.textbook',
  267:                       'requestcourses.placement','requestcourses.lti');
  268:         @usertools = ('official','unofficial','community','textbook','placement','lti');
  269:         @options =('norequest','approval','autolimit','validate');
  270:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  271:         %reqtitles = &courserequest_titles();
  272:         %reqdisplay = &courserequest_display();
  273:         $colspan = ' colspan="2"';
  274:         %domconfig =
  275:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  276:         $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  277:     } elsif ($context eq 'requestauthor') {
  278:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  279:                                                     'requestauthor');
  280:         @usertools = ('requestauthor');
  281:         @options =('norequest','approval','automatic');
  282:         %reqtitles = &requestauthor_titles();
  283:         %reqdisplay = &requestauthor_display();
  284:         $colspan = ' colspan="2"';
  285:         %domconfig =
  286:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  287:     } else {
  288:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  289:                           'tools.aboutme','tools.portfolio','tools.blog',
  290:                           'tools.webdav');
  291:         @usertools = ('aboutme','blog','webdav','portfolio');
  292:     }
  293:     foreach my $item (@usertools) {
  294:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  295:             $currdisp,$custdisp,$custradio);
  296:         $cust_off = 'checked="checked" ';
  297:         $tool_on = 'checked="checked" ';
  298:         $curr_access =  
  299:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  300:                                               $context);
  301:         if ($context eq 'requestauthor') {
  302:             if ($userenv{$context} ne '') {
  303:                 $cust_on = ' checked="checked" ';
  304:                 $cust_off = '';
  305:             }  
  306:         } elsif ($userenv{$context.'.'.$item} ne '') {
  307:             $cust_on = ' checked="checked" ';
  308:             $cust_off = '';
  309:         }
  310:         if ($context eq 'requestcourses') {
  311:             if ($userenv{$context.'.'.$item} eq '') {
  312:                 $custom_access = &mt('Currently from default setting.');
  313:             } else {
  314:                 $custom_access = &mt('Currently from custom setting.');
  315:             }
  316:         } elsif ($context eq 'requestauthor') {
  317:             if ($userenv{$context} eq '') {
  318:                 $custom_access = &mt('Currently from default setting.');
  319:             } else {
  320:                 $custom_access = &mt('Currently from custom setting.');
  321:             }
  322:         } else {
  323:             if ($userenv{$context.'.'.$item} eq '') {
  324:                 $custom_access =
  325:                     &mt('Availability determined currently from default setting.');
  326:                 if (!$curr_access) {
  327:                     $tool_off = 'checked="checked" ';
  328:                     $tool_on = '';
  329:                 }
  330:             } else {
  331:                 $custom_access =
  332:                     &mt('Availability determined currently from custom setting.');
  333:                 if ($userenv{$context.'.'.$item} == 0) {
  334:                     $tool_off = 'checked="checked" ';
  335:                     $tool_on = '';
  336:                 }
  337:             }
  338:         }
  339:         $output .= '  <tr class="LC_info_row">'."\n".
  340:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  341:                    '  </tr>'."\n".
  342:                    &Apache::loncommon::start_data_table_row()."\n";
  343:   
  344:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  345:             my ($curroption,$currlimit);
  346:             my $envkey = $context.'.'.$item;
  347:             if ($context eq 'requestauthor') {
  348:                 $envkey = $context;
  349:             }
  350:             if ($userenv{$envkey} ne '') {
  351:                 $curroption = $userenv{$envkey};
  352:             } else {
  353:                 my (@inststatuses);
  354:                 if ($context eq 'requestcourses') {
  355:                     $curroption =
  356:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  357:                                                                       $isadv,$ccdomain,$item,
  358:                                                                       \@inststatuses,\%domconfig);
  359:                 } else {
  360:                      $curroption = 
  361:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  362:                                                                        $isadv,$ccdomain,undef,
  363:                                                                        \@inststatuses,\%domconfig);
  364:                 }
  365:             }
  366:             if (!$curroption) {
  367:                 $curroption = 'norequest';
  368:             }
  369:             if ($curroption =~ /^autolimit=(\d*)$/) {
  370:                 $currlimit = $1;
  371:                 if ($currlimit eq '') {
  372:                     $currdisp = &mt('Yes, automatic creation');
  373:                 } else {
  374:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  375:                 }
  376:             } else {
  377:                 $currdisp = $reqdisplay{$curroption};
  378:             }
  379:             $custdisp = '<table>';
  380:             foreach my $option (@options) {
  381:                 my $val = $option;
  382:                 if ($option eq 'norequest') {
  383:                     $val = 0;
  384:                 }
  385:                 if ($option eq 'validate') {
  386:                     my $canvalidate = 0;
  387:                     if (ref($validations{$item}) eq 'HASH') {
  388:                         if ($validations{$item}{'_custom_'}) {
  389:                             $canvalidate = 1;
  390:                         }
  391:                     }
  392:                     next if (!$canvalidate);
  393:                 }
  394:                 my $checked = '';
  395:                 if ($option eq $curroption) {
  396:                     $checked = ' checked="checked"';
  397:                 } elsif ($option eq 'autolimit') {
  398:                     if ($curroption =~ /^autolimit/) {
  399:                         $checked = ' checked="checked"';
  400:                     }
  401:                 }
  402:                 my $name = 'crsreq_'.$item;
  403:                 if ($context eq 'requestauthor') {
  404:                     $name = $item;
  405:                 }
  406:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  407:                              '<input type="radio" name="'.$name.'" '.
  408:                              'value="'.$val.'"'.$checked.' />'.
  409:                              $reqtitles{$option}.'</label>&nbsp;';
  410:                 if ($option eq 'autolimit') {
  411:                     $custdisp .= '<input type="text" name="'.$name.
  412:                                  '_limit" size="1" '.
  413:                                  'value="'.$currlimit.'" /></span><br />'.
  414:                                  $reqtitles{'unlimited'};
  415:                 } else {
  416:                     $custdisp .= '</span>';
  417:                 }
  418:                 $custdisp .= '</td></tr>';
  419:             }
  420:             $custdisp .= '</table>';
  421:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  422:         } else {
  423:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  424:             my $name = $context.'_'.$item;
  425:             if ($context eq 'requestauthor') {
  426:                 $name = $context;
  427:             }
  428:             $custdisp = '<span class="LC_nobreak"><label>'.
  429:                         '<input type="radio" name="'.$name.'"'.
  430:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  431:                         '<input type="radio" name="'.$name.'" value="0" '.
  432:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  433:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  434:                           '</span>';
  435:         }
  436:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  437:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  438:                    &Apache::loncommon::end_data_table_row()."\n";
  439:         unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  440:             $output .=
  441:                    &Apache::loncommon::start_data_table_row()."\n".
  442:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  443:                    $lt{'chse'}.': <label>'.
  444:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  445:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  446:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  447:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  448:                    &Apache::loncommon::end_data_table_row()."\n";
  449:         }
  450:     }
  451:     return $output;
  452: }
  453: 
  454: sub coursereq_externaluser {
  455:     my ($ccuname,$ccdomain,$cdom) = @_;
  456:     my (@usertools,@options,%validations,%userenv,$output);
  457:     my %lt = &Apache::lonlocal::texthash (
  458:                    'official'   => 'Can request creation of official courses',
  459:                    'unofficial' => 'Can request creation of unofficial courses',
  460:                    'community'  => 'Can request creation of communities',
  461:                    'textbook'   => 'Can request creation of textbook courses',
  462:                    'placement'  => 'Can request creation of placement tests',
  463:     );
  464: 
  465:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  466:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  467:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  468:                       'reqcrsotherdom.placement');
  469:     @usertools = ('official','unofficial','community','textbook','placement');
  470:     @options = ('approval','validate','autolimit');
  471:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  472:     my $optregex = join('|',@options);
  473:     my %reqtitles = &courserequest_titles();
  474:     foreach my $item (@usertools) {
  475:         my ($curroption,$currlimit,$tooloff);
  476:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  477:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  478:             foreach my $req (@curr) {
  479:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  480:                     $curroption = $1;
  481:                     $currlimit = $2;
  482:                     last;
  483:                 }
  484:             }
  485:             if (!$curroption) {
  486:                 $curroption = 'norequest';
  487:                 $tooloff = ' checked="checked"';
  488:             }
  489:         } else {
  490:             $curroption = 'norequest';
  491:             $tooloff = ' checked="checked"';
  492:         }
  493:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  494:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  495:                   '<table><tr><td valign="top">'."\n".
  496:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  497:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  498:                   '</label></td>';
  499:         foreach my $option (@options) {
  500:             if ($option eq 'validate') {
  501:                 my $canvalidate = 0;
  502:                 if (ref($validations{$item}) eq 'HASH') {
  503:                     if ($validations{$item}{'_external_'}) {
  504:                         $canvalidate = 1;
  505:                     }
  506:                 }
  507:                 next if (!$canvalidate);
  508:             }
  509:             my $checked = '';
  510:             if ($option eq $curroption) {
  511:                 $checked = ' checked="checked"';
  512:             }
  513:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  514:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  515:                        '" value="'.$option.'"'.$checked.' />'.
  516:                        $reqtitles{$option}.'</label>';
  517:             if ($option eq 'autolimit') {
  518:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  519:                            $item.'_limit" size="1" '.
  520:                            'value="'.$currlimit.'" /></span>'.
  521:                            '<br />'.$reqtitles{'unlimited'};
  522:             } else {
  523:                 $output .= '</span>';
  524:             }
  525:             $output .= '</td>';
  526:         }
  527:         $output .= '</td></tr></table></td>'."\n".
  528:                    &Apache::loncommon::end_data_table_row()."\n";
  529:     }
  530:     return $output;
  531: }
  532: 
  533: sub domainrole_req {
  534:     my ($ccuname,$ccdomain) = @_;
  535:     return '<br /><h3>'.
  536:            &mt('User Can Request Assignment of Domain Roles?').
  537:            '</h3>'."\n".
  538:            &Apache::loncommon::start_data_table().
  539:            &build_tools_display($ccuname,$ccdomain,
  540:                                 'requestauthor').
  541:            &Apache::loncommon::end_data_table();
  542: }
  543: 
  544: sub courserequest_titles {
  545:     my %titles = &Apache::lonlocal::texthash (
  546:                                    official   => 'Official',
  547:                                    unofficial => 'Unofficial',
  548:                                    community  => 'Communities',
  549:                                    textbook   => 'Textbook',
  550:                                    placement  => 'Placement Tests',
  551:                                    lti        => 'LTI Provider',
  552:                                    norequest  => 'Not allowed',
  553:                                    approval   => 'Approval by Dom. Coord.',
  554:                                    validate   => 'With validation',
  555:                                    autolimit  => 'Numerical limit',
  556:                                    unlimited  => '(blank for unlimited)',
  557:                  );
  558:     return %titles;
  559: }
  560: 
  561: sub courserequest_display {
  562:     my %titles = &Apache::lonlocal::texthash (
  563:                                    approval   => 'Yes, need approval',
  564:                                    validate   => 'Yes, with validation',
  565:                                    norequest  => 'No',
  566:    );
  567:    return %titles;
  568: }
  569: 
  570: sub requestauthor_titles {
  571:     my %titles = &Apache::lonlocal::texthash (
  572:                                    norequest  => 'Not allowed',
  573:                                    approval   => 'Approval by Dom. Coord.',
  574:                                    automatic  => 'Automatic approval',
  575:                  );
  576:     return %titles;
  577: 
  578: }
  579: 
  580: sub requestauthor_display {
  581:     my %titles = &Apache::lonlocal::texthash (
  582:                                    approval   => 'Yes, need approval',
  583:                                    automatic  => 'Yes, automatic approval',
  584:                                    norequest  => 'No',
  585:    );
  586:    return %titles;
  587: }
  588: 
  589: sub requestchange_display {
  590:     my %titles = &Apache::lonlocal::texthash (
  591:                                    approval   => "availability set to 'on' (approval required)", 
  592:                                    automatic  => "availability set to 'on' (automatic approval)",
  593:                                    norequest  => "availability set to 'off'",
  594:    );
  595:    return %titles;
  596: }
  597: 
  598: sub curr_requestauthor {
  599:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  600:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  601:     if ($uname eq '' || $udom eq '') {
  602:         $uname = $env{'user.name'};
  603:         $udom = $env{'user.domain'};
  604:         $isadv = $env{'user.adv'};
  605:     }
  606:     my (%userenv,%settings,$val);
  607:     my @options = ('automatic','approval');
  608:     %userenv =
  609:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  610:     if ($userenv{'requestauthor'}) {
  611:         $val = $userenv{'requestauthor'};
  612:         @{$inststatuses} = ('_custom_');
  613:     } else {
  614:         my %alltasks;
  615:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  616:             %settings = %{$domconfig->{'requestauthor'}};
  617:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  618:                 $val = $settings{'_LC_adv'};
  619:                 @{$inststatuses} = ('_LC_adv_');
  620:             } else {
  621:                 if ($userenv{'inststatus'} ne '') {
  622:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  623:                 } else {
  624:                     @{$inststatuses} = ('default');
  625:                 }
  626:                 foreach my $status (@{$inststatuses}) {
  627:                     if (exists($settings{$status})) {
  628:                         my $value = $settings{$status};
  629:                         next unless ($value);
  630:                         unless (exists($alltasks{$value})) {
  631:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  632:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  633:                                     push(@{$alltasks{$value}},$status);
  634:                                 }
  635:                             } else {
  636:                                 @{$alltasks{$value}} = ($status);
  637:                             }
  638:                         }
  639:                     }
  640:                 }
  641:                 foreach my $option (@options) {
  642:                     if ($alltasks{$option}) {
  643:                         $val = $option;
  644:                         last;
  645:                     }
  646:                 }
  647:             }
  648:         }
  649:     }
  650:     return $val;
  651: }
  652: 
  653: # =================================================================== Phase one
  654: 
  655: sub print_username_entry_form {
  656:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  657:         $permission) = @_;
  658:     my $defdom=$env{'request.role.domain'};
  659:     my $formtoset = 'crtuser';
  660:     if (exists($env{'form.startrolename'})) {
  661:         $formtoset = 'docustom';
  662:         $env{'form.rolename'} = $env{'form.startrolename'};
  663:     } elsif ($env{'form.origform'} eq 'crtusername') {
  664:         $formtoset =  $env{'form.origform'};
  665:     }
  666: 
  667:     my ($jsback,$elements) = &crumb_utilities();
  668: 
  669:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  670:         '<script type="text/javascript">'."\n".
  671:         '// <![CDATA['."\n".
  672:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  673:         '// ]]>'."\n".
  674:         '</script>'."\n";
  675: 
  676:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  677:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  678:         && (&Apache::lonnet::allowed('mcr','/'))) {
  679:         $jscript .= &customrole_javascript();
  680:     }
  681:     my $helpitem = 'Course_Change_Privileges';
  682:     if ($env{'form.action'} eq 'custom') {
  683:         if ($context eq 'course') {
  684:             $helpitem = 'Course_Editing_Custom_Roles';
  685:         } elsif ($context eq 'domain') {
  686:             $helpitem = 'Domain_Editing_Custom_Roles';
  687:         }
  688:     } elsif ($env{'form.action'} eq 'singlestudent') {
  689:         $helpitem = 'Course_Add_Student';
  690:     } elsif ($env{'form.action'} eq 'accesslogs') {
  691:         $helpitem = 'Domain_User_Access_Logs';
  692:     } elsif ($context eq 'author') {
  693:         $helpitem = 'Author_Change_Privileges';
  694:     } elsif ($context eq 'domain') {
  695:         if ($permission->{'cusr'}) {
  696:             $helpitem = 'Domain_Change_Privileges';
  697:         } elsif ($permission->{'view'}) {
  698:             $helpitem = 'Domain_View_Privileges';
  699:         } else {
  700:             undef($helpitem);
  701:         }
  702:     }
  703:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  704:     if ($env{'form.action'} eq 'custom') {
  705:         push(@{$brcrum},
  706:                  {href=>"javascript:backPage(document.crtuser)",       
  707:                   text=>"Pick custom role",
  708:                   help => $helpitem,}
  709:                  );
  710:     } else {
  711:         push (@{$brcrum},
  712:                   {href => "javascript:backPage(document.crtuser)",
  713:                    text => $breadcrumb_text{'search'},
  714:                    help => $helpitem,
  715:                    faq  => 282,
  716:                    bug  => 'Instructor Interface',}
  717:                   );
  718:     }
  719:     my %loaditems = (
  720:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  721:                     );
  722:     my $args = {bread_crumbs           => $brcrum,
  723:                 bread_crumbs_component => 'User Management',
  724:                 add_entries            => \%loaditems,};
  725:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  726: 
  727:     my %lt=&Apache::lonlocal::texthash(
  728:                     'srst' => 'Search for a user and enroll as a student',
  729:                     'srme' => 'Search for a user and enroll as a member',
  730:                     'srad' => 'Search for a user and modify/add user information or roles',
  731:                     'srvu' => 'Search for a user and view user information and roles',
  732:                     'srva' => 'Search for a user and view access log information',
  733: 		    'usr'  => "Username",
  734:                     'dom'  => "Domain",
  735:                     'ecrp' => "Define or Edit Custom Role",
  736:                     'nr'   => "role name",
  737:                     'cre'  => "Next",
  738: 				       );
  739: 
  740:     if ($env{'form.action'} eq 'custom') {
  741:         if (&Apache::lonnet::allowed('mcr','/')) {
  742:             my $newroletext = &mt('Define new custom role:');
  743:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  744:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  745:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  746:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  747:                       &Apache::loncommon::start_data_table().
  748:                       &Apache::loncommon::start_data_table_row().
  749:                       '<td>');
  750:             if (keys(%existingroles) > 0) {
  751:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  752:             } else {
  753:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  754:             }
  755:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  756:                       &Apache::loncommon::end_data_table_row());
  757:             if (keys(%existingroles) > 0) {
  758:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  759:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  760:                           &mt('View/Modify existing role:').'</b></label></td>'.
  761:                           '<td align="center"><br />'.
  762:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  763:                           '<option value="" selected="selected">'.
  764:                           &mt('Select'));
  765:                 foreach my $role (sort(keys(%existingroles))) {
  766:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  767:                 }
  768:                 $r->print('</select>'.
  769:                           '</td>'.
  770:                           &Apache::loncommon::end_data_table_row());
  771:             }
  772:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  773:                       '<input name="customeditor" type="submit" value="'.
  774:                       $lt{'cre'}.'" /></p>'.
  775:                       '</form>');
  776:         }
  777:     } else {
  778:         my $actiontext = $lt{'srad'};
  779:         my $fixeddom;
  780:         if ($env{'form.action'} eq 'singlestudent') {
  781:             if ($crstype eq 'Community') {
  782:                 $actiontext = $lt{'srme'};
  783:             } else {
  784:                 $actiontext = $lt{'srst'};
  785:             }
  786:         } elsif ($env{'form.action'} eq 'accesslogs') {
  787:             $actiontext = $lt{'srva'};
  788:             $fixeddom = 1;
  789:         } elsif (($env{'form.action'} eq 'singleuser') &&
  790:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  791:             $actiontext = $lt{'srvu'};
  792:             $fixeddom = 1;
  793:         }
  794:         $r->print("<h3>$actiontext</h3>");
  795:         if ($env{'form.origform'} ne 'crtusername') {
  796:             if ($response) {
  797:                $r->print("\n<div>$response</div>".
  798:                          '<br clear="all" />');
  799:             }
  800:         }
  801:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
  802:     }
  803: }
  804: 
  805: sub customrole_javascript {
  806:     my $js = <<"END";
  807: <script type="text/javascript">
  808: // <![CDATA[
  809: 
  810: function setCustomFields() {
  811:     if (document.docustom.customroleaction.length > 0) {
  812:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  813:             if (document.docustom.customroleaction[i].checked) {
  814:                 if (document.docustom.customroleaction[i].value == 'new') {
  815:                     document.docustom.rolename.selectedIndex = 0;
  816:                 } else {
  817:                     document.docustom.newrolename.value = '';
  818:                 }
  819:             }
  820:         }
  821:     }
  822:     return;
  823: }
  824: 
  825: function setCustomAction(caller) {
  826:     if (document.docustom.customroleaction.length > 0) {
  827:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  828:             if (document.docustom.customroleaction[i].value == caller) {
  829:                 document.docustom.customroleaction[i].checked = true;
  830:             }
  831:         }
  832:     }
  833:     setCustomFields();
  834:     return;
  835: }
  836: 
  837: // ]]>
  838: </script>
  839: END
  840:     return $js;
  841: }
  842: 
  843: sub entry_form {
  844:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  845:     my ($usertype,$inexact);
  846:     if (ref($srch) eq 'HASH') {
  847:         if (($srch->{'srchin'} eq 'dom') &&
  848:             ($srch->{'srchby'} eq 'uname') &&
  849:             ($srch->{'srchtype'} eq 'exact') &&
  850:             ($srch->{'srchdomain'} ne '') &&
  851:             ($srch->{'srchterm'} ne '')) {
  852:             my (%curr_rules,%got_rules);
  853:             my ($rules,$ruleorder) =
  854:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  855:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  856:         } else {
  857:             $inexact = 1;
  858:         }
  859:     }
  860:     my ($cancreate,$noinstd);
  861:     if ($env{'form.action'} eq 'accesslogs') {
  862:         $noinstd = 1;
  863:     } else {
  864:         $cancreate =
  865:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  866:     }
  867:     my ($userpicker,$cansearch) = 
  868:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  869:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
  870:     my $srchbutton = &mt('Search');
  871:     if ($env{'form.action'} eq 'singlestudent') {
  872:         $srchbutton = &mt('Search and Enroll');
  873:     } elsif ($env{'form.action'} eq 'accesslogs') {
  874:         $srchbutton = &mt('Search');
  875:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  876:         $srchbutton = &mt('Search or Add New User');
  877:     }
  878:     my $output;
  879:     if ($cansearch) {
  880:         $output = <<"ENDBLOCK";
  881: <form action="/adm/createuser" method="post" name="crtuser">
  882: <input type="hidden" name="action" value="$env{'form.action'}" />
  883: <input type="hidden" name="phase" value="get_user_info" />
  884: $userpicker
  885: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  886: </form>
  887: ENDBLOCK
  888:     } else {
  889:         $output = '<p>'.$userpicker.'</p>';
  890:     }
  891:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  892:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
  893:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  894:         my $defdom=$env{'request.role.domain'};
  895:         my ($trusted,$untrusted);
  896:         if ($context eq 'course') {
  897:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
  898:         } elsif ($context eq 'author') {
  899:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
  900:         } elsif ($context eq 'domain') {
  901:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom); 
  902:         }
  903:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain',undef,undef,undef,$trusted,$untrusted);
  904:         my %lt=&Apache::lonlocal::texthash(
  905:                   'enro' => 'Enroll one student',
  906:                   'enrm' => 'Enroll one member',
  907:                   'admo' => 'Add/modify a single user',
  908:                   'crea' => 'create new user if required',
  909:                   'uskn' => "username is known",
  910:                   'crnu' => 'Create a new user',
  911:                   'usr'  => 'Username',
  912:                   'dom'  => 'in domain',
  913:                   'enrl' => 'Enroll',
  914:                   'cram'  => 'Create/Modify user',
  915:         );
  916:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  917:         my ($title,$buttontext,$showresponse);
  918:         if ($env{'form.action'} eq 'singlestudent') {
  919:             if ($crstype eq 'Community') {
  920:                 $title = $lt{'enrm'};
  921:             } else {
  922:                 $title = $lt{'enro'};
  923:             }
  924:             $buttontext = $lt{'enrl'};
  925:         } else {
  926:             $title = $lt{'admo'};
  927:             $buttontext = $lt{'cram'};
  928:         }
  929:         if ($cancreate) {
  930:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  931:         } else {
  932:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  933:         }
  934:         if ($env{'form.origform'} eq 'crtusername') {
  935:             $showresponse = $responsemsg;
  936:         }
  937:         $output .= <<"ENDDOCUMENT";
  938: <br />
  939: <form action="/adm/createuser" method="post" name="crtusername">
  940: <input type="hidden" name="action" value="$env{'form.action'}" />
  941: <input type="hidden" name="phase" value="createnewuser" />
  942: <input type="hidden" name="srchtype" value="exact" />
  943: <input type="hidden" name="srchby" value="uname" />
  944: <input type="hidden" name="srchin" value="dom" />
  945: <input type="hidden" name="forcenewuser" value="1" />
  946: <input type="hidden" name="origform" value="crtusername" />
  947: <h3>$title</h3>
  948: $showresponse
  949: <table>
  950:  <tr>
  951:   <td>$lt{'usr'}:</td>
  952:   <td><input type="text" size="15" name="srchterm" /></td>
  953:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  954:   <td>&nbsp;$sellink&nbsp;</td>
  955:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  956:  </tr>
  957: </table>
  958: </form>
  959: ENDDOCUMENT
  960:     }
  961:     return $output;
  962: }
  963: 
  964: sub user_modification_js {
  965:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  966:     
  967:     return <<END;
  968: <script type="text/javascript" language="Javascript">
  969: // <![CDATA[
  970: 
  971:     $pjump_def
  972:     $dc_setcourse_code
  973: 
  974:     function dateset() {
  975:         eval("document.cu."+document.cu.pres_marker.value+
  976:             ".value=document.cu.pres_value.value");
  977:         modalWindow.close();
  978:     }
  979: 
  980:     $nondc_setsection_code
  981: // ]]>
  982: </script>
  983: END
  984: }
  985: 
  986: # =================================================================== Phase two
  987: sub print_user_selection_page {
  988:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  989:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  990:     my $sortby = $env{'form.sortby'};
  991: 
  992:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  993:         $sortby = 'lastname';
  994:     }
  995: 
  996:     my ($jsback,$elements) = &crumb_utilities();
  997: 
  998:     my $jscript = (<<ENDSCRIPT);
  999: <script type="text/javascript">
 1000: // <![CDATA[
 1001: function pickuser(uname,udom) {
 1002:     document.usersrchform.seluname.value=uname;
 1003:     document.usersrchform.seludom.value=udom;
 1004:     document.usersrchform.phase.value="userpicked";
 1005:     document.usersrchform.submit();
 1006: }
 1007: 
 1008: $jsback
 1009: // ]]>
 1010: </script>
 1011: ENDSCRIPT
 1012: 
 1013:     my %lt=&Apache::lonlocal::texthash(
 1014:                                        'usrch'          => "User Search to add/modify roles",
 1015:                                        'stusrch'        => "User Search to enroll student",
 1016:                                        'memsrch'        => "User Search to enroll member",
 1017:                                        'srcva'          => "Search for a user and view access log information",
 1018:                                        'usrvu'          => "User Search to view user roles",
 1019:                                        'usel'           => "Select a user to add/modify roles",
 1020:                                        'suvr'           => "Select a user to view roles",
 1021:                                        'stusel'         => "Select a user to enroll as a student",
 1022:                                        'memsel'         => "Select a user to enroll as a member",
 1023:                                        'vacsel'         => "Select a user to view access log",
 1024:                                        'username'       => "username",
 1025:                                        'domain'         => "domain",
 1026:                                        'lastname'       => "last name",
 1027:                                        'firstname'      => "first name",
 1028:                                        'permanentemail' => "permanent e-mail",
 1029:                                       );
 1030:     if ($context eq 'requestcrs') {
 1031:         $r->print('<div>');
 1032:     } else {
 1033:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1034:         my $helpitem;
 1035:         if ($env{'form.action'} eq 'singleuser') {
 1036:             $helpitem = 'Course_Change_Privileges';
 1037:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1038:             $helpitem = 'Course_Add_Student';
 1039:         } elsif ($context eq 'author') {
 1040:             $helpitem = 'Author_Change_Privileges';
 1041:         } elsif ($context eq 'domain') {
 1042:             $helpitem = 'Domain_Change_Privileges';
 1043:         }
 1044:         push (@{$brcrum},
 1045:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1046:                    text => $breadcrumb_text{'search'},
 1047:                    faq  => 282,
 1048:                    bug  => 'Instructor Interface',},
 1049:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1050:                    text => $breadcrumb_text{'userpicked'},
 1051:                    faq  => 282,
 1052:                    bug  => 'Instructor Interface',
 1053:                    help => $helpitem}
 1054:                   );
 1055:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1056:         if ($env{'form.action'} eq 'singleuser') {
 1057:             my $readonly;
 1058:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1059:                 $readonly = 1;
 1060:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1061:             } else {
 1062:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1063:             }
 1064:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1065:             if ($readonly) {
 1066:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1067:             } else {
 1068:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1069:             }
 1070:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1071:             $r->print($jscript."<b>");
 1072:             if ($crstype eq 'Community') {
 1073:                 $r->print($lt{'memsrch'});
 1074:             } else {
 1075:                 $r->print($lt{'stusrch'});
 1076:             }
 1077:             $r->print("</b><br />");
 1078:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1079:             $r->print('</form><h3>');
 1080:             if ($crstype eq 'Community') {
 1081:                 $r->print($lt{'memsel'});
 1082:             } else {
 1083:                 $r->print($lt{'stusel'});
 1084:             }
 1085:             $r->print('</h3>');
 1086:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1087:             $r->print("<b>$lt{'srcva'}</b><br />");
 1088:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1089:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1090:         }
 1091:     }
 1092:     $r->print('<form name="usersrchform" method="post" action="">'.
 1093:               &Apache::loncommon::start_data_table()."\n".
 1094:               &Apache::loncommon::start_data_table_header_row()."\n".
 1095:               ' <th> </th>'."\n");
 1096:     foreach my $field (@fields) {
 1097:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1098:                   "'".$field."'".';document.usersrchform.submit();">'.
 1099:                   $lt{$field}.'</a></th>'."\n");
 1100:     }
 1101:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1102: 
 1103:     my @sorted_users = sort {
 1104:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1105:             ||
 1106:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1107:             ||
 1108:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1109: 	    ||
 1110: 	lc($a) cmp lc($b)
 1111:         } (keys(%$srch_results));
 1112: 
 1113:     foreach my $user (@sorted_users) {
 1114:         my ($uname,$udom) = split(/:/,$user);
 1115:         my $onclick;
 1116:         if ($context eq 'requestcrs') {
 1117:             $onclick =
 1118:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1119:                                                "'$srch_results->{$user}->{firstname}',".
 1120:                                                "'$srch_results->{$user}->{lastname}',".
 1121:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1122:         } else {
 1123:             $onclick =
 1124:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1125:         }
 1126:         $r->print(&Apache::loncommon::start_data_table_row().
 1127:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1128:                   $onclick.' /></td>'.
 1129:                   '<td><tt>'.$uname.'</tt></td>'.
 1130:                   '<td><tt>'.$udom.'</tt></td>');
 1131:         foreach my $field ('lastname','firstname','permanentemail') {
 1132:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1133:         }
 1134:         $r->print(&Apache::loncommon::end_data_table_row());
 1135:     }
 1136:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1137:     if (ref($srcharray) eq 'ARRAY') {
 1138:         foreach my $item (@{$srcharray}) {
 1139:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1140:         }
 1141:     }
 1142:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1143:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1144:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1145:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1146:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1147:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1148:     if ($context eq 'requestcrs') {
 1149:         $r->print($opener_elements.'</form></div>');
 1150:     } else {
 1151:         $r->print($response.'</form>');
 1152:     }
 1153: }
 1154: 
 1155: sub print_user_query_page {
 1156:     my ($r,$caller,$brcrum) = @_;
 1157: # FIXME - this is for a network-wide name search (similar to catalog search)
 1158: # To use frames with similar behavior to catalog/portfolio search.
 1159: # To be implemented. 
 1160:     return;
 1161: }
 1162: 
 1163: sub print_user_modification_page {
 1164:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1165:         $brcrum,$showcredits) = @_;
 1166:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1167:         my $usermsg = &mt('No username and/or domain provided.');
 1168:         $env{'form.phase'} = '';
 1169: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1170:                                    $permission);
 1171:         return;
 1172:     }
 1173:     my ($form,$formname);
 1174:     if ($env{'form.action'} eq 'singlestudent') {
 1175:         $form = 'document.enrollstudent';
 1176:         $formname = 'enrollstudent';
 1177:     } else {
 1178:         $form = 'document.cu';
 1179:         $formname = 'cu';
 1180:     }
 1181:     my %abv_auth = &auth_abbrev();
 1182:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1183:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1184:     if ($uhome eq 'no_host') {
 1185:         my $usertype;
 1186:         my ($rules,$ruleorder) =
 1187:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1188:             $usertype =
 1189:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1190:                                                       \%curr_rules,\%got_rules);
 1191:         my $cancreate =
 1192:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1193:                                                    $usertype);
 1194:         if (!$cancreate) {
 1195:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1196:             my %usertypetext = (
 1197:                 official   => 'institutional',
 1198:                 unofficial => 'non-institutional',
 1199:             );
 1200:             my $response;
 1201:             if ($env{'form.origform'} eq 'crtusername') {
 1202:                 $response = '<span class="LC_warning">'.
 1203:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1204:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1205:                             '</span><br />';
 1206:             }
 1207:             $response .= '<p class="LC_warning">'
 1208:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1209:                         .' ';
 1210:             if ($context eq 'domain') {
 1211:                 $response .= &mt('Please contact a [_1] for assistance.',
 1212:                                  &Apache::lonnet::plaintext('dc'));
 1213:             } else {
 1214:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1215:                                 ,'<a href="'.$helplink.'">','</a>');
 1216:             }
 1217:             $response .= '</p><br />';
 1218:             $env{'form.phase'} = '';
 1219:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1220:                                        $permission);
 1221:             return;
 1222:         }
 1223:         $newuser = 1;
 1224:         my $checkhash;
 1225:         my $checks = { 'username' => 1 };
 1226:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1227:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1228:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1229:         if (ref($alerts{'username'}) eq 'HASH') {
 1230:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1231:                 my $domdesc =
 1232:                     &Apache::lonnet::domain($ccdomain,'description');
 1233:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1234:                     my $userchkmsg;
 1235:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1236:                         $userchkmsg = 
 1237:                             &Apache::loncommon::instrule_disallow_msg('username',
 1238:                                                                  $domdesc,1).
 1239:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1240:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1241:                             'username');
 1242:                     }
 1243:                     $env{'form.phase'} = '';
 1244:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1245:                                                $permission);
 1246:                     return;
 1247:                 }
 1248:             }
 1249:         }
 1250:     } else {
 1251:         $newuser = 0;
 1252:     }
 1253:     if ($response) {
 1254:         $response = '<br />'.$response;
 1255:     }
 1256: 
 1257:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1258:     my $dc_setcourse_code = '';
 1259:     my $nondc_setsection_code = '';                                        
 1260:     my %loaditem;
 1261: 
 1262:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1263: 
 1264:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1265:                                $groupslist,$newuser,$formname,\%loaditem);
 1266:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1267:     my $helpitem = 'Course_Change_Privileges';
 1268:     if ($env{'form.action'} eq 'singlestudent') {
 1269:         $helpitem = 'Course_Add_Student';
 1270:     } elsif ($context eq 'author') {
 1271:         $helpitem = 'Author_Change_Privileges';
 1272:     } elsif ($context eq 'domain') {
 1273:         $helpitem = 'Domain_Change_Privileges';
 1274:     }
 1275:     push (@{$brcrum},
 1276:         {href => "javascript:backPage($form)",
 1277:          text => $breadcrumb_text{'search'},
 1278:          faq  => 282,
 1279:          bug  => 'Instructor Interface',});
 1280:     if ($env{'form.phase'} eq 'userpicked') {
 1281:        push(@{$brcrum},
 1282:               {href => "javascript:backPage($form,'get_user_info','select')",
 1283:                text => $breadcrumb_text{'userpicked'},
 1284:                faq  => 282,
 1285:                bug  => 'Instructor Interface',});
 1286:     }
 1287:     push(@{$brcrum},
 1288:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1289:              text => $breadcrumb_text{'modify'},
 1290:              faq  => 282,
 1291:              bug  => 'Instructor Interface',
 1292:              help => $helpitem});
 1293:     my $args = {'add_entries'           => \%loaditem,
 1294:                 'bread_crumbs'          => $brcrum,
 1295:                 'bread_crumbs_component' => 'User Management'};
 1296:     if ($env{'form.popup'}) {
 1297:         $args->{'no_nav_bar'} = 1;
 1298:     }
 1299:     my $start_page =
 1300:         &Apache::loncommon::start_page('User Management',$js,$args);
 1301: 
 1302:     my $forminfo =<<"ENDFORMINFO";
 1303: <form action="/adm/createuser" method="post" name="$formname">
 1304: <input type="hidden" name="phase" value="update_user_data" />
 1305: <input type="hidden" name="ccuname" value="$ccuname" />
 1306: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1307: <input type="hidden" name="pres_value"  value="" />
 1308: <input type="hidden" name="pres_type"   value="" />
 1309: <input type="hidden" name="pres_marker" value="" />
 1310: ENDFORMINFO
 1311:     my (%inccourses,$roledom,$defaultcredits);
 1312:     if ($context eq 'course') {
 1313:         $inccourses{$env{'request.course.id'}}=1;
 1314:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1315:         if ($showcredits) {
 1316:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1317:         }
 1318:     } elsif ($context eq 'author') {
 1319:         $roledom = $env{'request.role.domain'};
 1320:     } elsif ($context eq 'domain') {
 1321:         foreach my $key (keys(%env)) {
 1322:             $roledom = $env{'request.role.domain'};
 1323:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1324:                 $inccourses{$1.'_'.$2}=1;
 1325:             }
 1326:         }
 1327:     } else {
 1328:         foreach my $key (keys(%env)) {
 1329: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1330: 	        $inccourses{$1.'_'.$2}=1;
 1331:             }
 1332:         }
 1333:     }
 1334:     my $title = '';
 1335:     if ($newuser) {
 1336:         my ($portfolioform,$domroleform);
 1337:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1338:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1339:             # Current user has quota or user tools modification privileges
 1340:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1341:         }
 1342:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1343:             ($ccdomain eq $env{'request.role.domain'})) {
 1344:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1345:         }
 1346:         &initialize_authen_forms($ccdomain,$formname);
 1347:         my %lt=&Apache::lonlocal::texthash(
 1348:                 'lg'             => 'Login Data',
 1349:                 'hs'             => "Home Server",
 1350:         );
 1351: 	$r->print(<<ENDTITLE);
 1352: $start_page
 1353: $response
 1354: $forminfo
 1355: <script type="text/javascript" language="Javascript">
 1356: // <![CDATA[
 1357: $loginscript
 1358: // ]]>
 1359: </script>
 1360: <input type='hidden' name='makeuser' value='1' />
 1361: ENDTITLE
 1362:         if ($env{'form.action'} eq 'singlestudent') {
 1363:             if ($crstype eq 'Community') {
 1364:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1365:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1366:             } else {
 1367:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1368:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1369:             }
 1370:         } else {
 1371:                 $title = &mt('Create New User [_1] in domain [_2]',
 1372:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1373:         }
 1374:         $r->print('<h2>'.$title.'</h2>'."\n");
 1375:         $r->print('<div class="LC_left_float">');
 1376:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1377:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1378:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1379:         my ($home_server_pick,$numlib) = 
 1380:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1381:                                                       'default','hide');
 1382:         if ($numlib > 1) {
 1383:             $r->print("
 1384: <br />
 1385: $lt{'hs'}: $home_server_pick
 1386: <br />");
 1387:         } else {
 1388:             $r->print($home_server_pick);
 1389:         }
 1390:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1391:             $r->print('<br /><h3>'.
 1392:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1393:                       &Apache::loncommon::start_data_table().
 1394:                       &build_tools_display($ccuname,$ccdomain,
 1395:                                            'requestcourses').
 1396:                       &Apache::loncommon::end_data_table());
 1397:         }
 1398:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1399:                   $lt{'lg'}.'</h3>');
 1400:         my ($fixedauth,$varauth,$authmsg); 
 1401:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1402:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1403:             my ($rules,$ruleorder) = 
 1404:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1405:             if (ref($rules) eq 'HASH') {
 1406:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1407:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1408:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1409:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1410:                     } else { 
 1411:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1412:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1413:                         if ($authtype =~ /^krb(4|5)$/) {
 1414:                             my $ver = $1;
 1415:                             if ($authparm ne '') {
 1416:                                 $fixedauth = <<"KERB"; 
 1417: <input type="hidden" name="login" value="krb" />
 1418: <input type="hidden" name="krbver" value="$ver" />
 1419: <input type="hidden" name="krbarg" value="$authparm" />
 1420: KERB
 1421:                             }
 1422:                         } else {
 1423:                             $fixedauth = 
 1424: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1425:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1426:                                 $fixedauth .=    
 1427: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1428:                             } else {
 1429:                                 if ($authtype eq 'int') {
 1430:                                     $varauth = '<br />'.
 1431: &mt('[_1] Internally authenticated (with initial password [_2])','','<input type="password" size="10" name="intarg" value="" />')."<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
 1432:                                 } elsif ($authtype eq 'loc') {
 1433:                                     $varauth = '<br />'.
 1434: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1435:                                 } else {
 1436:                                     $varauth =
 1437: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1438:                                 }
 1439:                             }
 1440:                         }
 1441:                     }
 1442:                 } else {
 1443:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1444:                 }
 1445:             }
 1446:             if ($authmsg) {
 1447:                 $r->print(<<ENDAUTH);
 1448: $fixedauth
 1449: $authmsg
 1450: $varauth
 1451: ENDAUTH
 1452:             }
 1453:         } else {
 1454:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1455:         }
 1456:         $r->print($portfolioform.$domroleform);
 1457:         if ($env{'form.action'} eq 'singlestudent') {
 1458:             $r->print(&date_sections_select($context,$newuser,$formname,
 1459:                                             $permission,$crstype,$ccuname,
 1460:                                             $ccdomain,$showcredits));
 1461:         }
 1462:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1463:     } else { # user already exists
 1464: 	$r->print($start_page.$forminfo);
 1465:         if ($env{'form.action'} eq 'singlestudent') {
 1466:             if ($crstype eq 'Community') {
 1467:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1468:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1469:             } else {
 1470:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1471:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1472:             }
 1473:         } else {
 1474:             if ($permission->{'cusr'}) {
 1475:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1476:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1477:             } else {
 1478:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1479:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1480:             }
 1481:         }
 1482:         $r->print('<h2>'.$title.'</h2>'."\n");
 1483:         $r->print('<div class="LC_left_float">');
 1484:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1485:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1486:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1487:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1488:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'."\n");
 1489:             if (($env{'request.role.domain'} eq $ccdomain) ||
 1490:                 (&Apache::lonnet::will_trust('reqcrs',$ccdomain,$env{'request.role.domain'}))) {
 1491:                 $r->print(&Apache::loncommon::start_data_table());
 1492:                 if ($env{'request.role.domain'} eq $ccdomain) {
 1493:                     $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1494:                 } else {
 1495:                     $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1496:                                                       $env{'request.role.domain'}));
 1497:                 }
 1498:                 $r->print(&Apache::loncommon::end_data_table());
 1499:             } else {
 1500:                 $r->print(&mt('Domain configuration for this domain prohibits course creation by users from domain: "[_1]"',
 1501:                               &Apache::lonnet::domain($ccdomain,'description')));
 1502:             }
 1503:         }
 1504:         $r->print('</div>');
 1505:         my @order = ('auth','quota','tools','requestauthor');
 1506:         my %user_text;
 1507:         my ($isadv,$isauthor) = 
 1508:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1509:         if ((!$isauthor) && 
 1510:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1511:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1512:              ($env{'request.role.domain'} eq $ccdomain)) {
 1513:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1514:         }
 1515:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1516:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1517:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1518:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1519:             # Current user has quota modification privileges
 1520:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1521:         }
 1522:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1523:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1524:                 my %lt=&Apache::lonlocal::texthash(
 1525:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1526:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1527:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1528:                 );
 1529:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1530: <h3>$lt{'dska'}</h3>
 1531: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1532: ENDNOPORTPRIV
 1533:             }
 1534:         }
 1535:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1536:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1537:                 my %lt=&Apache::lonlocal::texthash(
 1538:                     'utav'  => "User Tools Availability",
 1539:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1540:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1541:                 );
 1542:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1543: <h3>$lt{'utav'}</h3>
 1544: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1545: ENDNOTOOLSPRIV
 1546:             }
 1547:         }
 1548:         my $gotdiv = 0; 
 1549:         foreach my $item (@order) {
 1550:             if ($user_text{$item} ne '') {
 1551:                 unless ($gotdiv) {
 1552:                     $r->print('<div class="LC_left_float">');
 1553:                     $gotdiv = 1;
 1554:                 }
 1555:                 $r->print('<br />'.$user_text{$item});
 1556:             }
 1557:         }
 1558:         if ($env{'form.action'} eq 'singlestudent') {
 1559:             unless ($gotdiv) {
 1560:                 $r->print('<div class="LC_left_float">');
 1561:             }
 1562:             my $credits;
 1563:             if ($showcredits) {
 1564:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1565:                 if ($credits eq '') {
 1566:                     $credits = $defaultcredits;
 1567:                 }
 1568:             }
 1569:             $r->print(&date_sections_select($context,$newuser,$formname,
 1570:                                             $permission,$crstype,$ccuname,
 1571:                                             $ccdomain,$showcredits));
 1572:         }
 1573:         if ($gotdiv) {
 1574:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1575:         }
 1576:         my $statuses;
 1577:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1578:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1579:             $statuses = ['active'];
 1580:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1581:                  ($env{'request.course.sec'} &&
 1582:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1583:             $statuses = ['active'];
 1584:         }
 1585:         if ($env{'form.action'} ne 'singlestudent') {
 1586:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1587:                                     $roledom,$crstype,$showcredits,$statuses);
 1588:         }
 1589:     } ## End of new user/old user logic
 1590:     if ($env{'form.action'} eq 'singlestudent') {
 1591:         my $btntxt;
 1592:         if ($crstype eq 'Community') {
 1593:             $btntxt = &mt('Enroll Member');
 1594:         } else {
 1595:             $btntxt = &mt('Enroll Student');
 1596:         }
 1597:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1598:     } elsif ($permission->{'cusr'}) {
 1599:         $r->print('<div class="LC_left_float">'.
 1600:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1601:         my $addrolesdisplay = 0;
 1602:         if ($context eq 'domain' || $context eq 'author') {
 1603:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1604:         }
 1605:         if ($context eq 'domain') {
 1606:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1607:             if (!$addrolesdisplay) {
 1608:                 $addrolesdisplay = $add_domainroles;
 1609:             }
 1610:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1611:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1612:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1613:         } elsif ($context eq 'author') {
 1614:             if ($addrolesdisplay) {
 1615:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1616:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1617:                 if ($newuser) {
 1618:                     $r->print(' onclick="auth_check()" \>'."\n");
 1619:                 } else {
 1620:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1621:                 }
 1622:             } else {
 1623:                 $r->print('</fieldset></div>'.
 1624:                           '<div class="LC_clear_float_footer"></div>'.
 1625:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1626:                           &mt('Back to previous page').'</a>');
 1627:             }
 1628:         } else {
 1629:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1630:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1631:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1632:         }
 1633:     }
 1634:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1635:     $r->print('<input type="hidden" name="currstate" value="" />');
 1636:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1637:     return;
 1638: }
 1639: 
 1640: sub singleuser_breadcrumb {
 1641:     my ($crstype,$context,$domain) = @_;
 1642:     my %breadcrumb_text;
 1643:     if ($env{'form.action'} eq 'singlestudent') {
 1644:         if ($crstype eq 'Community') {
 1645:             $breadcrumb_text{'search'} = 'Enroll a member';
 1646:         } else {
 1647:             $breadcrumb_text{'search'} = 'Enroll a student';
 1648:         }
 1649:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1650:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1651:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1652:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1653:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1654:         $breadcrumb_text{'activity'} = 'Activity';
 1655:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1656:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1657:         $breadcrumb_text{'search'} = "View user's roles";
 1658:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1659:         $breadcrumb_text{'modify'} = 'User roles';
 1660:     } else {
 1661:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1662:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1663:         $breadcrumb_text{'modify'} = 'Set user role';
 1664:     }
 1665:     return %breadcrumb_text;
 1666: }
 1667: 
 1668: sub date_sections_select {
 1669:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1670:         $showcredits) = @_;
 1671:     my $credits;
 1672:     if ($showcredits) {
 1673:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1674:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1675:         if ($credits eq '') {
 1676:             $credits = $defaultcredits;
 1677:         }
 1678:     }
 1679:     my $cid = $env{'request.course.id'};
 1680:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1681:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1682:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1683:                                                   undef,$formname,$permission);
 1684:     my $rowtitle = 'Section';
 1685:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1686:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1687:                                               $permission,$context,'',$crstype,
 1688:                                               $showcredits,$credits);
 1689:     my $output = $date_table.$secbox;
 1690:     return $output;
 1691: }
 1692: 
 1693: sub validation_javascript {
 1694:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1695:         $loaditem) = @_;
 1696:     my $dc_setcourse_code = '';
 1697:     my $nondc_setsection_code = '';
 1698:     if ($context eq 'domain') {
 1699:         my $dcdom = $env{'request.role.domain'};
 1700:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1701:         $dc_setcourse_code = 
 1702:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1703:     } else {
 1704:         my $checkauth; 
 1705:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1706:             $checkauth = 1;
 1707:         }
 1708:         if ($context eq 'course') {
 1709:             $nondc_setsection_code =
 1710:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1711:                                                               undef,$checkauth,
 1712:                                                               $crstype);
 1713:         }
 1714:         if ($checkauth) {
 1715:             $nondc_setsection_code .= 
 1716:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1717:         }
 1718:     }
 1719:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1720:                                    $nondc_setsection_code,$groupslist);
 1721:     my ($jsback,$elements) = &crumb_utilities();
 1722:     $js .= "\n".
 1723:            '<script type="text/javascript">'."\n".
 1724:            '// <![CDATA['."\n".
 1725:            $jsback."\n".
 1726:            '// ]]>'."\n".
 1727:            '</script>'."\n";
 1728:     return $js;
 1729: }
 1730: 
 1731: sub display_existing_roles {
 1732:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1733:         $showcredits,$statuses) = @_;
 1734:     my $now=time;
 1735:     my $showall = 1;
 1736:     my ($showexpired,$showactive);
 1737:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1738:         $showall = 0;
 1739:         if (grep(/^expired$/,@{$statuses})) {
 1740:             $showexpired = 1;
 1741:         }
 1742:         if (grep(/^active$/,@{$statuses})) {
 1743:             $showactive = 1;
 1744:         }
 1745:         if ($showexpired && $showactive) {
 1746:             $showall = 1;
 1747:         }
 1748:     }
 1749:     my %lt=&Apache::lonlocal::texthash(
 1750:                     'rer'  => "Existing Roles",
 1751:                     'rev'  => "Revoke",
 1752:                     'del'  => "Delete",
 1753:                     'ren'  => "Re-Enable",
 1754:                     'rol'  => "Role",
 1755:                     'ext'  => "Extent",
 1756:                     'crd'  => "Credits",
 1757:                     'sta'  => "Start",
 1758:                     'end'  => "End",
 1759:                                        );
 1760:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1761:     if ($context eq 'course' || $context eq 'author') {
 1762:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1763:         my %roleshash = 
 1764:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1765:                               ['active','previous','future'],\@roles,$roledom,1);
 1766:         foreach my $key (keys(%roleshash)) {
 1767:             my ($start,$end) = split(':',$roleshash{$key});
 1768:             next if ($start eq '-1' || $end eq '-1');
 1769:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1770:             if ($context eq 'course') {
 1771:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1772:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1773:             } elsif ($context eq 'author') {
 1774:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1775:             }
 1776:             my ($newkey,$newvalue,$newrole);
 1777:             $newkey = '/'.$rdom.'/'.$rnum;
 1778:             if ($sec ne '') {
 1779:                 $newkey .= '/'.$sec;
 1780:             }
 1781:             $newvalue = $role;
 1782:             if ($role =~ /^cr/) {
 1783:                 $newrole = 'cr';
 1784:             } else {
 1785:                 $newrole = $role;
 1786:             }
 1787:             $newkey .= '_'.$newrole;
 1788:             if ($start ne '' && $end ne '') {
 1789:                 $newvalue .= '_'.$end.'_'.$start;
 1790:             } elsif ($end ne '') {
 1791:                 $newvalue .= '_'.$end;
 1792:             }
 1793:             $rolesdump{$newkey} = $newvalue;
 1794:         }
 1795:     } else {
 1796:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1797:     }
 1798:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1799:     my ($tmp) = keys(%rolesdump);
 1800:     return if ($tmp =~ /^(con_lost|error)/i);
 1801:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1802:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1803:                                 return $a1 cmp $b1;
 1804:                             } keys(%rolesdump)) {
 1805:         next if ($area =~ /^rolesdef/);
 1806:         my $envkey=$area;
 1807:         my $role = $rolesdump{$area};
 1808:         my $thisrole=$area;
 1809:         $area =~ s/\_\w\w$//;
 1810:         my ($role_code,$role_end_time,$role_start_time) =
 1811:             split(/_/,$role);
 1812:         my $active=1;
 1813:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1814:         if ($active) {
 1815:             next unless($showall || $showactive);
 1816:         } else {
 1817:             next unless($showall || $showexpired);
 1818:         }
 1819: # Is this a custom role? Get role owner and title.
 1820:         my ($croleudom,$croleuname,$croletitle)=
 1821:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1822:         my $allowed=0;
 1823:         my $delallowed=0;
 1824:         my $sortkey=$role_code;
 1825:         my $class='Unknown';
 1826:         my $credits='';
 1827:         my $csec;
 1828:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1829:             $class='Course';
 1830:             my ($coursedom,$coursedir) = ($1,$2);
 1831:             my $cid = $1.'_'.$2;
 1832:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1833:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1834:             my %coursedata=
 1835:                 &Apache::lonnet::coursedescription($cid);
 1836:             if ($coursedir =~ /^$match_community$/) {
 1837:                 $class='Community';
 1838:             }
 1839:             $sortkey.="\0$coursedom";
 1840:             my $carea;
 1841:             if (defined($coursedata{'description'})) {
 1842:                 $carea=$coursedata{'description'}.
 1843:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1844:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1845:                 $sortkey.="\0".$coursedata{'description'};
 1846:             } else {
 1847:                 if ($class eq 'Community') {
 1848:                     $carea=&mt('Unavailable community').': '.$area;
 1849:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1850:                 } else {
 1851:                     $carea=&mt('Unavailable course').': '.$area;
 1852:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1853:                 }
 1854:             }
 1855:             $sortkey.="\0$coursedir";
 1856:             $inccourses->{$cid}=1;
 1857:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1858:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1859:                 $credits =
 1860:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1861:                                       $coursedom,$coursedir);
 1862:                 if ($credits eq '') {
 1863:                     $credits = $defaultcredits;
 1864:                 }
 1865:             }
 1866:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1867:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1868:                 $allowed=1;
 1869:             }
 1870:             unless ($allowed) {
 1871:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1872:                 if ($isowner) {
 1873:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1874:                         $allowed = 1;
 1875:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1876:                         $allowed = 1;
 1877:                     }
 1878:                 }
 1879:             } 
 1880:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1881:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1882:                 $delallowed=1;
 1883:             }
 1884: # - custom role. Needs more info, too
 1885:             if ($croletitle) {
 1886:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1887:                     $allowed=1;
 1888:                     $thisrole.='.'.$role_code;
 1889:                 }
 1890:             }
 1891:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1892:                 $csec = $2;
 1893:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1894:                 $sortkey.="\0$csec";
 1895:                 if (!$allowed) {
 1896:                     if ($env{'request.course.sec'} eq $csec) {
 1897:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1898:                             $allowed = 1;
 1899:                         }
 1900:                     }
 1901:                 }
 1902:             }
 1903:             $area=$carea;
 1904:         } else {
 1905:             $sortkey.="\0".$area;
 1906:             # Determine if current user is able to revoke privileges
 1907:             if ($area=~m{^/($match_domain)/}) {
 1908:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1909:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1910:                    $allowed=1;
 1911:                 }
 1912:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1913:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1914:                     ($role_code ne 'dc')) {
 1915:                     $delallowed=1;
 1916:                 }
 1917:             } else {
 1918:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1919:                     $allowed=1;
 1920:                 }
 1921:             }
 1922:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1923:                 $class='Authoring Space';
 1924:             } elsif ($role_code eq 'su') {
 1925:                 $class='System';
 1926:             } else {
 1927:                 $class='Domain';
 1928:             }
 1929:         }
 1930:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1931:             $area=~m{/($match_domain)/($match_username)};
 1932:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1933:                 $allowed=1;
 1934:             } else {
 1935:                 $allowed=0;
 1936:             }
 1937:         }
 1938:         my $row = '';
 1939:         if ($showall) {
 1940:             $row.= '<td>';
 1941:             if (($active) && ($allowed)) {
 1942:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1943:             } else {
 1944:                 if ($active) {
 1945:                     $row.='&nbsp;';
 1946:                 } else {
 1947:                     $row.=&mt('expired or revoked');
 1948:                 }
 1949:             }
 1950:             $row.='</td><td>';
 1951:             if ($allowed && !$active) {
 1952:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1953:             } else {
 1954:                 $row.='&nbsp;';
 1955:             }
 1956:             $row.='</td><td>';
 1957:             if ($delallowed) {
 1958:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1959:             } else {
 1960:                 $row.='&nbsp;';
 1961:             }
 1962:             $row.= '</td>';
 1963:         }
 1964:         my $plaintext='';
 1965:         if (!$croletitle) {
 1966:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1967:             if (($showcredits) && ($credits ne '')) {
 1968:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1969:                               '<span class="LC_fontsize_small">'.
 1970:                               &mt('Credits: [_1]',$credits).
 1971:                               '</span></span>';
 1972:             }
 1973:         } else {
 1974:             $plaintext=
 1975:                 &mt('Custom role [_1][_2]defined by [_3]',
 1976:                         '"'.$croletitle.'"',
 1977:                         '<br />',
 1978:                         $croleuname.':'.$croleudom);
 1979:         }
 1980:         $row.= '<td>'.$plaintext.'</td>'.
 1981:                '<td>'.$area.'</td>'.
 1982:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1983:                                             : '&nbsp;' ).'</td>'.
 1984:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1985:                                             : '&nbsp;' ).'</td>';
 1986:         $sortrole{$sortkey}=$envkey;
 1987:         $roletext{$envkey}=$row;
 1988:         $roleclass{$envkey}=$class;
 1989:         if ($allowed) {
 1990:             $rolepriv{$envkey}='edit';
 1991:         } else {
 1992:             if ($context eq 'domain') {
 1993:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 1994:                     ($envkey=~m{^/$ccdomain/})) {
 1995:                     $rolepriv{$envkey}='view';
 1996:                 }
 1997:             } elsif ($context eq 'course') {
 1998:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1999:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 2000:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2001:                     $rolepriv{$envkey}='view';
 2002:                 }
 2003:             }
 2004:         }
 2005:     } # end of foreach        (table building loop)
 2006: 
 2007:     my $rolesdisplay = 0;
 2008:     my %output = ();
 2009:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2010:         $output{$type} = '';
 2011:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2012:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2013:                  $output{$type}.=
 2014:                       &Apache::loncommon::start_data_table_row().
 2015:                       $roletext{$sortrole{$which}}.
 2016:                       &Apache::loncommon::end_data_table_row();
 2017:             }
 2018:         }
 2019:         unless($output{$type} eq '') {
 2020:             $output{$type} = '<tr class="LC_info_row">'.
 2021:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2022:                       $output{$type};
 2023:             $rolesdisplay = 1;
 2024:         }
 2025:     }
 2026:     if ($rolesdisplay == 1) {
 2027:         my $contextrole='';
 2028:         if ($env{'request.course.id'}) {
 2029:             if (&Apache::loncommon::course_type() eq 'Community') {
 2030:                 $contextrole = &mt('Existing Roles in this Community');
 2031:             } else {
 2032:                 $contextrole = &mt('Existing Roles in this Course');
 2033:             }
 2034:         } elsif ($env{'request.role'} =~ /^au\./) {
 2035:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2036:         } else {
 2037:             if ($showall) {
 2038:                 $contextrole = &mt('Existing Roles in this Domain');
 2039:             } elsif ($showactive) {
 2040:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2041:             } elsif ($showexpired) {
 2042:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2043:             }
 2044:         }
 2045:         $r->print('<div class="LC_left_float">'.
 2046: '<fieldset><legend>'.$contextrole.'</legend>'.
 2047: &Apache::loncommon::start_data_table("LC_createuser").
 2048: &Apache::loncommon::start_data_table_header_row());
 2049:         if ($showall) {
 2050:             $r->print(
 2051: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2052:             );
 2053:         } elsif ($showexpired) {
 2054:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2055:         }
 2056:         $r->print(
 2057: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2058: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2059: &Apache::loncommon::end_data_table_header_row());
 2060:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2061:             if ($output{$type}) {
 2062:                 $r->print($output{$type}."\n");
 2063:             }
 2064:         }
 2065:         $r->print(&Apache::loncommon::end_data_table().
 2066:                   '</fieldset></div>');
 2067:     }
 2068:     return;
 2069: }
 2070: 
 2071: sub new_coauthor_roles {
 2072:     my ($r,$ccuname,$ccdomain) = @_;
 2073:     my $addrolesdisplay = 0;
 2074:     #
 2075:     # Co-Author
 2076:     #
 2077:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2078:                                           $env{'request.role.domain'}) &&
 2079:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2080:         # No sense in assigning co-author role to yourself
 2081:         $addrolesdisplay = 1;
 2082:         my $cuname=$env{'user.name'};
 2083:         my $cudom=$env{'request.role.domain'};
 2084:         my %lt=&Apache::lonlocal::texthash(
 2085:                     'cs'   => "Authoring Space",
 2086:                     'act'  => "Activate",
 2087:                     'rol'  => "Role",
 2088:                     'ext'  => "Extent",
 2089:                     'sta'  => "Start",
 2090:                     'end'  => "End",
 2091:                     'cau'  => "Co-Author",
 2092:                     'caa'  => "Assistant Co-Author",
 2093:                     'ssd'  => "Set Start Date",
 2094:                     'sed'  => "Set End Date"
 2095:                                        );
 2096:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2097:                   &Apache::loncommon::start_data_table()."\n".
 2098:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2099:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2100:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2101:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2102:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2103:                   &Apache::loncommon::start_data_table_row().'
 2104:            <td>
 2105:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2106:            </td>
 2107:            <td>'.$lt{'cau'}.'</td>
 2108:            <td>'.$cudom.'_'.$cuname.'</td>
 2109:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2110:              <a href=
 2111: "javascript:pjump('."'date_start','Start Date Co-Author',document.cu.start_$cudom\_$cuname\_ca.value,'start_$cudom\_$cuname\_ca','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2112: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2113: <a href=
 2114: "javascript:pjump('."'date_end','End Date Co-Author',document.cu.end_$cudom\_$cuname\_ca.value,'end_$cudom\_$cuname\_ca','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'."\n".
 2115:               &Apache::loncommon::end_data_table_row()."\n".
 2116:               &Apache::loncommon::start_data_table_row()."\n".
 2117: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2118: <td>'.$lt{'caa'}.'</td>
 2119: <td>'.$cudom.'_'.$cuname.'</td>
 2120: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2121: <a href=
 2122: "javascript:pjump('."'date_start','Start Date Assistant Co-Author',document.cu.start_$cudom\_$cuname\_aa.value,'start_$cudom\_$cuname\_aa','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2123: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2124: <a href=
 2125: "javascript:pjump('."'date_end','End Date Assistant Co-Author',document.cu.end_$cudom\_$cuname\_aa.value,'end_$cudom\_$cuname\_aa','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'."\n".
 2126:              &Apache::loncommon::end_data_table_row()."\n".
 2127:              &Apache::loncommon::end_data_table());
 2128:     } elsif ($env{'request.role'} =~ /^au\./) {
 2129:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2130:                                                 $env{'request.role.domain'}))) {
 2131:             $r->print('<span class="LC_error">'.
 2132:                       &mt('You do not have privileges to assign co-author roles.').
 2133:                       '</span>');
 2134:         } elsif (($env{'user.name'} eq $ccuname) &&
 2135:              ($env{'user.domain'} eq $ccdomain)) {
 2136:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2137:         }
 2138:     }
 2139:     return $addrolesdisplay;;
 2140: }
 2141: 
 2142: sub new_domain_roles {
 2143:     my ($r,$ccdomain) = @_;
 2144:     my $addrolesdisplay = 0;
 2145:     #
 2146:     # Domain level
 2147:     #
 2148:     my $num_domain_level = 0;
 2149:     my $domaintext =
 2150:     '<h4>'.&mt('Domain Level').'</h4>'.
 2151:     &Apache::loncommon::start_data_table().
 2152:     &Apache::loncommon::start_data_table_header_row().
 2153:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2154:     &mt('Extent').'</th>'.
 2155:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2156:     &Apache::loncommon::end_data_table_header_row();
 2157:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2158:     my $uprimary = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 2159:     my $uintdom = &Apache::lonnet::internet_dom($uprimary);
 2160:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2161:         foreach my $role (@allroles) {
 2162:             next if ($role eq 'ad');
 2163:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2164:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2165:                if ($role eq 'dc') {
 2166:                    unless ($thisdomain eq $env{'request.role.domain'}) {
 2167:                        my $domprim = &Apache::lonnet::domain($thisdomain,'primary');
 2168:                        my $intdom = &Apache::lonnet::internet_dom($domprim);
 2169:                        next unless ($uintdom eq $intdom);
 2170:                    }
 2171:                }
 2172:                my $plrole=&Apache::lonnet::plaintext($role);
 2173:                my %lt=&Apache::lonlocal::texthash(
 2174:                     'ssd'  => "Set Start Date",
 2175:                     'sed'  => "Set End Date"
 2176:                                        );
 2177:                $num_domain_level ++;
 2178:                $domaintext .=
 2179: &Apache::loncommon::start_data_table_row().
 2180: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2181: <td>'.$plrole.'</td>
 2182: <td>'.$thisdomain.'</td>
 2183: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2184: <a href=
 2185: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2186: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2187: <a href=
 2188: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2189: &Apache::loncommon::end_data_table_row();
 2190:             }
 2191:         }
 2192:     }
 2193:     $domaintext.= &Apache::loncommon::end_data_table();
 2194:     if ($num_domain_level > 0) {
 2195:         $r->print($domaintext);
 2196:         $addrolesdisplay = 1;
 2197:     }
 2198:     return $addrolesdisplay;
 2199: }
 2200: 
 2201: sub user_authentication {
 2202:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2203:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2204:     my $outcome;
 2205:     my %lt=&Apache::lonlocal::texthash(
 2206:                    'err'   => "ERROR",
 2207:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2208:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2209:                    'sldb'  => "Please specify login data below",
 2210:                    'ld'    => "Login Data"
 2211:     );
 2212:     # Check for a bad authentication type
 2213:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth|lti):/) {
 2214:         # bad authentication scheme
 2215:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2216:             &initialize_authen_forms($ccdomain,$formname);
 2217: 
 2218:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2219:             $outcome = <<ENDBADAUTH;
 2220: <script type="text/javascript" language="Javascript">
 2221: // <![CDATA[
 2222: $loginscript
 2223: // ]]>
 2224: </script>
 2225: <span class="LC_error">$lt{'err'}:
 2226: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2227: <h3>$lt{'ld'}</h3>
 2228: $choices
 2229: ENDBADAUTH
 2230:         } else {
 2231:             # This user is not allowed to modify the user's
 2232:             # authentication scheme, so just notify them of the problem
 2233:             $outcome = <<ENDBADAUTH;
 2234: <span class="LC_error"> $lt{'err'}: 
 2235: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2236: </span>
 2237: ENDBADAUTH
 2238:         }
 2239:     } else { # Authentication type is valid
 2240:         
 2241:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2242:         my ($authformcurrent,$can_modify,@authform_others) =
 2243:             &modify_login_block($ccdomain,$currentauth);
 2244:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2245:             # Current user has login modification privileges
 2246:             $outcome =
 2247:                        '<script type="text/javascript" language="Javascript">'."\n".
 2248:                        '// <![CDATA['."\n".
 2249:                        $loginscript."\n".
 2250:                        '// ]]>'."\n".
 2251:                        '</script>'."\n".
 2252:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2253:                        &Apache::loncommon::start_data_table().
 2254:                        &Apache::loncommon::start_data_table_row().
 2255:                        '<td>'.$authformnop;
 2256:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2257:                 $outcome .= '</td>'."\n".
 2258:                             &Apache::loncommon::end_data_table_row().
 2259:                             &Apache::loncommon::start_data_table_row().
 2260:                             '<td>'.$authformcurrent.'</td>'.
 2261:                             &Apache::loncommon::end_data_table_row()."\n";
 2262:             } else {
 2263:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2264:                             &Apache::loncommon::end_data_table_row()."\n";
 2265:             }
 2266:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2267:                 foreach my $item (@authform_others) { 
 2268:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2269:                                 '<td>'.$item.'</td>'.
 2270:                                 &Apache::loncommon::end_data_table_row()."\n";
 2271:                 }
 2272:             }
 2273:             $outcome .= &Apache::loncommon::end_data_table();
 2274:         } else {
 2275:             if (($currentauth =~ /^internal:/) &&
 2276:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2277:                 $outcome = <<"ENDJS";
 2278: <script type="text/javascript">
 2279: // <![CDATA[
 2280: function togglePwd(form) {
 2281:     if (form.newintpwd.length) {
 2282:         if (document.getElementById('LC_ownersetpwd')) {
 2283:             for (var i=0; i<form.newintpwd.length; i++) {
 2284:                 if (form.newintpwd[i].checked) {
 2285:                     if (form.newintpwd[i].value == 1) {
 2286:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2287:                     } else {
 2288:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2289:                     }
 2290:                 }
 2291:             }
 2292:         }
 2293:     }
 2294: }
 2295: // ]]>
 2296: </script>
 2297: ENDJS
 2298: 
 2299:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2300:                             &Apache::loncommon::start_data_table().
 2301:                             &Apache::loncommon::start_data_table_row().
 2302:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2303:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2304:                             &mt('No').'</label>'.('&nbsp;'x2).
 2305:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2306:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2307:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2308:                             '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }" />'.&mt('Visible input').'</label></div></td>'.
 2309:                             &Apache::loncommon::end_data_table_row().
 2310:                             &Apache::loncommon::end_data_table();
 2311:             }
 2312:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2313:                 # Current user has rights to view domain preferences for user's domain
 2314:                 my $result;
 2315:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2316:                     my ($krbver,$krbrealm) = ($1,$2);
 2317:                     if ($krbrealm eq '') {
 2318:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2319:                     } else {
 2320:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2321:                                       $krbrealm,$krbver);
 2322:                     }
 2323:                 } elsif ($currentauth =~ /^internal:/) {
 2324:                     $result = &mt('Currently internally authenticated.');
 2325:                 } elsif ($currentauth =~ /^localauth:/) {
 2326:                     $result = &mt('Currently using local (institutional) authentication.');
 2327:                 } elsif ($currentauth =~ /^unix:/) {
 2328:                     $result = &mt('Currently Filesystem Authenticated.');
 2329:                 } elsif ($currentauth =~ /^lti:/) {
 2330:                     $result = &mt('Currently LTI authenticated.');
 2331:                 }
 2332:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2333:                            &Apache::loncommon::start_data_table().
 2334:                            &Apache::loncommon::start_data_table_row().
 2335:                            '<td>'.$result.'</td>'.
 2336:                            &Apache::loncommon::end_data_table_row()."\n".
 2337:                            &Apache::loncommon::end_data_table();
 2338:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2339:                 my %lt=&Apache::lonlocal::texthash(
 2340:                            'ccld'  => "Change Current Login Data",
 2341:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2342:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2343:                 );
 2344:                 $outcome .= <<ENDNOPRIV;
 2345: <h3>$lt{'ccld'}</h3>
 2346: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2347: <input type="hidden" name="login" value="nochange" />
 2348: ENDNOPRIV
 2349:             }
 2350:         }
 2351:     }  ## End of "check for bad authentication type" logic
 2352:     return $outcome;
 2353: }
 2354: 
 2355: sub modify_login_block {
 2356:     my ($dom,$currentauth) = @_;
 2357:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2358:     my ($authnum,%can_assign) =
 2359:         &Apache::loncommon::get_assignable_auth($dom);
 2360:     my ($authformcurrent,@authform_others,$show_override_msg);
 2361:     if ($currentauth=~/^krb(4|5):/) {
 2362:         $authformcurrent=$authformkrb;
 2363:         if ($can_assign{'int'}) {
 2364:             push(@authform_others,$authformint);
 2365:         }
 2366:         if ($can_assign{'loc'}) {
 2367:             push(@authform_others,$authformloc);
 2368:         }
 2369:         if ($can_assign{'lti'}) {
 2370:             push(@authform_others,$authformlti);
 2371:         }
 2372:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2373:             $show_override_msg = 1;
 2374:         }
 2375:     } elsif ($currentauth=~/^internal:/) {
 2376:         $authformcurrent=$authformint;
 2377:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2378:             push(@authform_others,$authformkrb);
 2379:         }
 2380:         if ($can_assign{'loc'}) {
 2381:             push(@authform_others,$authformloc);
 2382:         }
 2383:         if ($can_assign{'lti'}) {
 2384:             push(@authform_others,$authformlti);
 2385:         }
 2386:         if ($can_assign{'int'}) {
 2387:             $show_override_msg = 1;
 2388:         }
 2389:     } elsif ($currentauth=~/^unix:/) {
 2390:         $authformcurrent=$authformfsys;
 2391:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2392:             push(@authform_others,$authformkrb);
 2393:         }
 2394:         if ($can_assign{'int'}) {
 2395:             push(@authform_others,$authformint);
 2396:         }
 2397:         if ($can_assign{'loc'}) {
 2398:             push(@authform_others,$authformloc);
 2399:         }
 2400:         if ($can_assign{'lti'}) {
 2401:             push(@authform_others,$authformlti);
 2402:         }
 2403:         if ($can_assign{'fsys'}) {
 2404:             $show_override_msg = 1;
 2405:         }
 2406:     } elsif ($currentauth=~/^localauth:/) {
 2407:         $authformcurrent=$authformloc;
 2408:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2409:             push(@authform_others,$authformkrb);
 2410:         }
 2411:         if ($can_assign{'int'}) {
 2412:             push(@authform_others,$authformint);
 2413:         }
 2414:         if ($can_assign{'lti'}) {
 2415:             push(@authform_others,$authformlti);
 2416:         }
 2417:         if ($can_assign{'loc'}) {
 2418:             $show_override_msg = 1;
 2419:         }
 2420:     } elsif ($currentauth=~/^lti:/) {
 2421:         $authformcurrent=$authformlti;
 2422:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2423:             push(@authform_others,$authformkrb);
 2424:         }
 2425:         if ($can_assign{'int'}) {
 2426:             push(@authform_others,$authformint);
 2427:         }
 2428:         if ($can_assign{'loc'}) {
 2429:             push(@authform_others,$authformloc);
 2430:         }
 2431:     }
 2432:     if ($show_override_msg) {
 2433:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2434:                            '</td></tr>'."\n".
 2435:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2436:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2437:                            '<td align="right"><span class="LC_cusr_emph">'.
 2438:                             &mt('will override current values').
 2439:                             '</span></td></tr></table>';
 2440:     }
 2441:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2442: }
 2443: 
 2444: sub personal_data_display {
 2445:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,$now,
 2446:         $captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded,$showsubmit) = @_;
 2447:     my ($output,%userenv,%canmodify,%canmodify_status);
 2448:     my @userinfo = ('firstname','middlename','lastname','generation',
 2449:                     'permanentemail','id');
 2450:     my $rowcount = 0;
 2451:     my $editable = 0;
 2452:     my %textboxsize = (
 2453:                        firstname      => '15',
 2454:                        middlename     => '15',
 2455:                        lastname       => '15',
 2456:                        generation     => '5',
 2457:                        permanentemail => '25',
 2458:                        id             => '15',
 2459:                       );
 2460: 
 2461:     my %lt=&Apache::lonlocal::texthash(
 2462:                 'pd'             => "Personal Data",
 2463:                 'firstname'      => "First Name",
 2464:                 'middlename'     => "Middle Name",
 2465:                 'lastname'       => "Last Name",
 2466:                 'generation'     => "Generation",
 2467:                 'permanentemail' => "Permanent e-mail address",
 2468:                 'id'             => "Student/Employee ID",
 2469:                 'lg'             => "Login Data",
 2470:                 'inststatus'     => "Affiliation",
 2471:                 'email'          => 'E-mail address',
 2472:                 'valid'          => 'Validation',
 2473:                 'username'       => 'Username',
 2474:     );
 2475: 
 2476:     %canmodify_status =
 2477:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2478:                                                    ['inststatus'],$rolesarray);
 2479:     if (!$newuser) {
 2480:         # Get the users information
 2481:         %userenv = &Apache::lonnet::get('environment',
 2482:                    ['firstname','middlename','lastname','generation',
 2483:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2484:         %canmodify =
 2485:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2486:                                                        \@userinfo,$rolesarray);
 2487:     } elsif ($context eq 'selfcreate') {
 2488:         if ($newuser eq 'email') {
 2489:             if (ref($emailusername) eq 'HASH') {
 2490:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2491:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2492:                     @userinfo = ();
 2493:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2494:                         foreach my $field (@{$infofields}) { 
 2495:                             if ($emailusername->{$usertype}->{$field}) {
 2496:                                 push(@userinfo,$field);
 2497:                                 $canmodify{$field} = 1;
 2498:                                 unless ($textboxsize{$field}) {
 2499:                                     $textboxsize{$field} = 25;
 2500:                                 }
 2501:                                 unless ($lt{$field}) {
 2502:                                     $lt{$field} = $infotitles->{$field};
 2503:                                 }
 2504:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2505:                                     $lt{$field} .= '<b>*</b>';
 2506:                                 }
 2507:                             }
 2508:                         }
 2509:                     }
 2510:                 }
 2511:             }
 2512:         } else {
 2513:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2514:                                                $inst_results,$rolesarray);
 2515:         }
 2516:     }
 2517: 
 2518:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2519:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2520:               &Apache::lonhtmlcommon::start_pick_box();
 2521:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2522:         my $size = 25;
 2523:         if ($condition) {
 2524:             if ($condition =~ /^\@[^\@]+$/) {
 2525:                 $size = 10;
 2526:             } else {
 2527:                 undef($condition);
 2528:             }
 2529:         } 
 2530:         if ($excluded) {
 2531:             unless ($excluded =~ /^\@[^\@]+$/) {
 2532:                 undef($condition);
 2533:             }
 2534:         }
 2535:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2536:                                                      'LC_oddrow_value')."\n".
 2537:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2538:         if ($condition) {
 2539:             $output .= $condition;
 2540:         } elsif ($excluded) {
 2541:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2542:                                                                      $excluded).'</span>';
 2543:         }
 2544:         if ($usernameset eq 'first') {
 2545:             $output .= '<br /><span style="font-size: smaller">';
 2546:             if ($condition) {
 2547:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2548:                                       $condition);
 2549:             } else {
 2550:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2551:             }
 2552:             $output .= '</span>';
 2553:         }
 2554:         $rowcount ++;
 2555:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2556:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2557:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2558:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2559:                                                     'LC_pick_box_title',
 2560:                                                     'LC_oddrow_value')."\n".
 2561:                    $upassone."\n".
 2562:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2563:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2564:                                                      'LC_pick_box_title',
 2565:                                                      'LC_oddrow_value')."\n".
 2566:                    $upasstwo.
 2567:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2568:         if ($usernameset eq 'free') {
 2569:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2570:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2571:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2572:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2573:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2574:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2575:                        &mt('No').'</label></span>'."\n".
 2576:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2577:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2578:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2579:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2580:             $rowcount ++;
 2581:         }
 2582:     }
 2583:     foreach my $item (@userinfo) {
 2584:         my $rowtitle = $lt{$item};
 2585:         my $hiderow = 0;
 2586:         if ($item eq 'generation') {
 2587:             $rowtitle = $genhelp.$rowtitle;
 2588:         }
 2589:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2590:         if ($newuser) {
 2591:             if (ref($inst_results) eq 'HASH') {
 2592:                 if ($inst_results->{$item} ne '') {
 2593:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2594:                 } else {
 2595:                     if ($context eq 'selfcreate') {
 2596:                         if ($canmodify{$item}) {
 2597:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2598:                             $editable ++;
 2599:                         } else {
 2600:                             $hiderow = 1;
 2601:                         }
 2602:                     } else {
 2603:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2604:                     }
 2605:                 }
 2606:             } else {
 2607:                 if ($context eq 'selfcreate') {
 2608:                     if ($canmodify{$item}) {
 2609:                         if ($newuser eq 'email') {
 2610:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2611:                         } else {
 2612:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2613:                         }
 2614:                         $editable ++;
 2615:                     } else {
 2616:                         $hiderow = 1;
 2617:                     }
 2618:                 } else {
 2619:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2620:                 }
 2621:             }
 2622:         } else {
 2623:             if ($canmodify{$item}) {
 2624:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2625:                 if (($item eq 'id') && (!$newuser)) {
 2626:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2627:                 }
 2628:             } else {
 2629:                 $row .= $userenv{$item};
 2630:             }
 2631:         }
 2632:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2633:         if (!$hiderow) {
 2634:             $output .= $row;
 2635:             $rowcount ++;
 2636:         }
 2637:     }
 2638:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2639:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2640:         if (ref($types) eq 'ARRAY') {
 2641:             if (@{$types} > 0) {
 2642:                 my ($hiderow,$shown);
 2643:                 if ($canmodify_status{'inststatus'}) {
 2644:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2645:                 } else {
 2646:                     if ($userenv{'inststatus'} eq '') {
 2647:                         $hiderow = 1;
 2648:                     } else {
 2649:                         my @showitems;
 2650:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2651:                             if (exists($usertypes->{$item})) {
 2652:                                 push(@showitems,$usertypes->{$item});
 2653:                             } else {
 2654:                                 push(@showitems,$item);
 2655:                             }
 2656:                         }
 2657:                         if (@showitems) {
 2658:                             $shown = join(', ',@showitems);
 2659:                         } else {
 2660:                             $hiderow = 1;
 2661:                         }
 2662:                     }
 2663:                 }
 2664:                 if (!$hiderow) {
 2665:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2666:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2667:                     if ($context eq 'selfcreate') {
 2668:                         $rowcount ++;
 2669:                     }
 2670:                     $output .= $row;
 2671:                 }
 2672:             }
 2673:         }
 2674:     }
 2675:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2676:         if ($captchaform) {
 2677:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2678:                                                          'LC_pick_box_title')."\n".
 2679:                        $captchaform."\n".'<br /><br />'.
 2680:                        &Apache::lonhtmlcommon::row_closure(1); 
 2681:             $rowcount ++;
 2682:         }
 2683:         if ($showsubmit) {
 2684:             my $submit_text = &mt('Create account');
 2685:             $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2686:                        '<br /><input type="submit" name="createaccount" value="'.
 2687:                        $submit_text.'" />';
 2688:             if ($usertype ne '') {
 2689:                 $output .= '<input type="hidden" name="type" value="'.
 2690:                            &HTML::Entities::encode($usertype,'\'<>"&').'" />';
 2691:             }
 2692:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 2693:         }
 2694:     }
 2695:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2696:     if (wantarray) {
 2697:         if ($context eq 'selfcreate') {
 2698:             return($output,$rowcount,$editable);
 2699:         } else {
 2700:             return $output;
 2701:         }
 2702:     } else {
 2703:         return $output;
 2704:     }
 2705: }
 2706: 
 2707: sub pick_inst_statuses {
 2708:     my ($curr,$usertypes,$types) = @_;
 2709:     my ($output,$rem,@currtypes);
 2710:     if ($curr ne '') {
 2711:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2712:     }
 2713:     my $numinrow = 2;
 2714:     if (ref($types) eq 'ARRAY') {
 2715:         $output = '<table>';
 2716:         my $lastcolspan; 
 2717:         for (my $i=0; $i<@{$types}; $i++) {
 2718:             if (defined($usertypes->{$types->[$i]})) {
 2719:                 my $rem = $i%($numinrow);
 2720:                 if ($rem == 0) {
 2721:                     if ($i<@{$types}-1) {
 2722:                         if ($i > 0) { 
 2723:                             $output .= '</tr>';
 2724:                         }
 2725:                         $output .= '<tr>';
 2726:                     }
 2727:                 } elsif ($i==@{$types}-1) {
 2728:                     my $colsleft = $numinrow - $rem;
 2729:                     if ($colsleft > 1) {
 2730:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2731:                     }
 2732:                 }
 2733:                 my $check = ' ';
 2734:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2735:                     $check = ' checked="checked" ';
 2736:                 }
 2737:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2738:                            '<span class="LC_nobreak"><label>'.
 2739:                            '<input type="checkbox" name="inststatus" '.
 2740:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2741:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2742:             }
 2743:         }
 2744:         $output .= '</tr></table>';
 2745:     }
 2746:     return $output;
 2747: }
 2748: 
 2749: sub selfcreate_canmodify {
 2750:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2751:     if (ref($inst_results) eq 'HASH') {
 2752:         my @inststatuses = &get_inststatuses($inst_results);
 2753:         if (@inststatuses == 0) {
 2754:             @inststatuses = ('default');
 2755:         }
 2756:         $rolesarray = \@inststatuses;
 2757:     }
 2758:     my %canmodify =
 2759:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2760:                                                    $rolesarray);
 2761:     return %canmodify;
 2762: }
 2763: 
 2764: sub get_inststatuses {
 2765:     my ($insthashref) = @_;
 2766:     my @inststatuses = ();
 2767:     if (ref($insthashref) eq 'HASH') {
 2768:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2769:             @inststatuses = @{$insthashref->{'inststatus'}};
 2770:         }
 2771:     }
 2772:     return @inststatuses;
 2773: }
 2774: 
 2775: # ================================================================= Phase Three
 2776: sub update_user_data {
 2777:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 2778:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2779:                                           $env{'form.ccdomain'});
 2780:     # Error messages
 2781:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2782:     my $end       = '</span><br /><br />';
 2783:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2784:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2785:                     &mt('Return to previous page').'</a>'.
 2786:                     &Apache::loncommon::end_page();
 2787:     my $now = time;
 2788:     my $title;
 2789:     if (exists($env{'form.makeuser'})) {
 2790: 	$title='Set Privileges for New User';
 2791:     } else {
 2792:         $title='Modify User Privileges';
 2793:     }
 2794:     my $newuser = 0;
 2795:     my ($jsback,$elements) = &crumb_utilities();
 2796:     my $jscript = '<script type="text/javascript">'."\n".
 2797:                   '// <![CDATA['."\n".
 2798:                   $jsback."\n".
 2799:                   '// ]]>'."\n".
 2800:                   '</script>'."\n";
 2801:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2802:     push (@{$brcrum},
 2803:              {href => "javascript:backPage(document.userupdate)",
 2804:               text => $breadcrumb_text{'search'},
 2805:               faq  => 282,
 2806:               bug  => 'Instructor Interface',}
 2807:              );
 2808:     if ($env{'form.prevphase'} eq 'userpicked') {
 2809:         push(@{$brcrum},
 2810:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2811:                 text => $breadcrumb_text{'userpicked'},
 2812:                 faq  => 282,
 2813:                 bug  => 'Instructor Interface',});
 2814:     }
 2815:     my $helpitem = 'Course_Change_Privileges';
 2816:     if ($env{'form.action'} eq 'singlestudent') {
 2817:         $helpitem = 'Course_Add_Student';
 2818:     } elsif ($context eq 'author') {
 2819:         $helpitem = 'Author_Change_Privileges';
 2820:     } elsif ($context eq 'domain') {
 2821:         $helpitem = 'Domain_Change_Privileges';
 2822:     }
 2823:     push(@{$brcrum}, 
 2824:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2825:              text => $breadcrumb_text{'modify'},
 2826:              faq  => 282,
 2827:              bug  => 'Instructor Interface',},
 2828:             {href => "/adm/createuser",
 2829:              text => "Result",
 2830:              faq  => 282,
 2831:              bug  => 'Instructor Interface',
 2832:              help => $helpitem});
 2833:     my $args = {bread_crumbs          => $brcrum,
 2834:                 bread_crumbs_component => 'User Management'};
 2835:     if ($env{'form.popup'}) {
 2836:         $args->{'no_nav_bar'} = 1;
 2837:     }
 2838:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2839:     $r->print(&update_result_form($uhome));
 2840:     # Check Inputs
 2841:     if (! $env{'form.ccuname'} ) {
 2842: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2843: 	return;
 2844:     }
 2845:     if (  $env{'form.ccuname'} ne 
 2846: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2847: 	$r->print($error.&mt('Invalid login name.').'  '.
 2848: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2849: 		  $end.$rtnlink);
 2850: 	return;
 2851:     }
 2852:     if (! $env{'form.ccdomain'}       ) {
 2853: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2854: 	return;
 2855:     }
 2856:     if (  $env{'form.ccdomain'} ne
 2857: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2858: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2859: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2860: 		  $end.$rtnlink);
 2861: 	return;
 2862:     }
 2863:     if ($uhome eq 'no_host') {
 2864:         $newuser = 1;
 2865:     }
 2866:     if (! exists($env{'form.makeuser'})) {
 2867:         # Modifying an existing user, so check the validity of the name
 2868:         if ($uhome eq 'no_host') {
 2869:             $r->print(
 2870:                 $error
 2871:                .'<p class="LC_error">'
 2872:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2873:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2874:                .'</p>');
 2875:             return;
 2876:         }
 2877:     }
 2878:     # Determine authentication method and password for the user being modified
 2879:     my $amode='';
 2880:     my $genpwd='';
 2881:     if ($env{'form.login'} eq 'krb') {
 2882: 	$amode='krb';
 2883: 	$amode.=$env{'form.krbver'};
 2884: 	$genpwd=$env{'form.krbarg'};
 2885:     } elsif ($env{'form.login'} eq 'int') {
 2886: 	$amode='internal';
 2887: 	$genpwd=$env{'form.intarg'};
 2888:     } elsif ($env{'form.login'} eq 'fsys') {
 2889: 	$amode='unix';
 2890: 	$genpwd=$env{'form.fsysarg'};
 2891:     } elsif ($env{'form.login'} eq 'loc') {
 2892: 	$amode='localauth';
 2893: 	$genpwd=$env{'form.locarg'};
 2894: 	$genpwd=" " if (!$genpwd);
 2895:     } elsif ($env{'form.login'} eq 'lti') {
 2896:         $amode='lti';
 2897:         $genpwd=" ";
 2898:     } elsif (($env{'form.login'} eq 'nochange') ||
 2899:              ($env{'form.login'} eq ''        )) { 
 2900:         # There is no need to tell the user we did not change what they
 2901:         # did not ask us to change.
 2902:         # If they are creating a new user but have not specified login
 2903:         # information this will be caught below.
 2904:     } else {
 2905:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2906:             return;
 2907:     }
 2908: 
 2909:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2910:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2911:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2912:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2913: 
 2914:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2915:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2916:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2917:     my @requestcourses = ('official','unofficial','community','textbook','placement','lti');
 2918:     my @requestauthor = ('requestauthor');
 2919:     my ($othertitle,$usertypes,$types) = 
 2920:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2921:     my %canmodify_status =
 2922:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2923:                                                    ['inststatus']);
 2924:     if ($env{'form.makeuser'}) {
 2925: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2926:         # Check for the authentication mode and password
 2927:         if (! $amode || ! $genpwd) {
 2928: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2929: 	    return;
 2930: 	}
 2931:         # Determine desired host
 2932:         my $desiredhost = $env{'form.hserver'};
 2933:         if (lc($desiredhost) eq 'default') {
 2934:             $desiredhost = undef;
 2935:         } else {
 2936:             my %home_servers = 
 2937: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2938:             if (! exists($home_servers{$desiredhost})) {
 2939:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2940:                 return;
 2941:             }
 2942:         }
 2943:         # Check ID format
 2944:         my %checkhash;
 2945:         my %checks = ('id' => 1);
 2946:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2947:             'newuser' => $newuser, 
 2948:             'id' => $env{'form.cid'},
 2949:         );
 2950:         if ($env{'form.cid'} ne '') {
 2951:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2952:                                           \%rulematch,\%inst_results,\%curr_rules);
 2953:             if (ref($alerts{'id'}) eq 'HASH') {
 2954:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2955:                     my $domdesc =
 2956:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2957:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2958:                         my $userchkmsg;
 2959:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2960:                             $userchkmsg  = 
 2961:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2962:                                                                     $domdesc,1).
 2963:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2964:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2965:                         }
 2966:                         $r->print($error.&mt('Invalid ID format').$end.
 2967:                                   $userchkmsg.$rtnlink);
 2968:                         return;
 2969:                     }
 2970:                 }
 2971:             }
 2972:         }
 2973:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2974: 	# Call modifyuser
 2975: 	my $result = &Apache::lonnet::modifyuser
 2976: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2977:              $amode,$genpwd,$env{'form.cfirstname'},
 2978:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2979:              $env{'form.cgeneration'},undef,$desiredhost,
 2980:              $env{'form.cpermanentemail'});
 2981: 	$r->print(&mt('Generating user').': '.$result);
 2982:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2983:                                                $env{'form.ccdomain'});
 2984:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2985:         if ($uhome ne 'no_host') {
 2986:             if ($context eq 'domain') {
 2987:                 foreach my $name ('portfolio','author') {
 2988:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2989:                         if ($env{'form.'.$name.'quota'} eq '') {
 2990:                             $newcustom{$name.'quota'} = 0;
 2991:                         } else {
 2992:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2993:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2994:                         }
 2995:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2996:                             $changed{$name.'quota'} = 1;
 2997:                         }
 2998:                     }
 2999:                 }
 3000:                 foreach my $item (@usertools) {
 3001:                     if ($env{'form.custom'.$item} == 1) {
 3002:                         $newcustom{$item} = $env{'form.tools_'.$item};
 3003:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3004:                                                      \%changeHash,'tools');
 3005:                     }
 3006:                 }
 3007:                 foreach my $item (@requestcourses) {
 3008:                     if ($env{'form.custom'.$item} == 1) {
 3009:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 3010:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 3011:                             $newcustom{$item} .= '=';
 3012:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 3013:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 3014:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 3015:                             }
 3016:                         }
 3017:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3018:                                                       \%changeHash,'requestcourses');
 3019:                     }
 3020:                 }
 3021:                 if ($env{'form.customrequestauthor'} == 1) {
 3022:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 3023:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 3024:                                                     $newcustom{'requestauthor'},
 3025:                                                     \%changeHash,'requestauthor');
 3026:                 }
 3027:             }
 3028:             if ($canmodify_status{'inststatus'}) {
 3029:                 if (exists($env{'form.inststatus'})) {
 3030:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3031:                     if (@inststatuses > 0) {
 3032:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 3033:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 3034:                     }
 3035:                 }
 3036:             }
 3037:             if (keys(%changed)) {
 3038:                 foreach my $item (@userinfo) {
 3039:                     $changeHash{$item}  = $env{'form.c'.$item};
 3040:                 }
 3041:                 my $chgresult =
 3042:                      &Apache::lonnet::put('environment',\%changeHash,
 3043:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3044:             } 
 3045:         }
 3046:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 3047:                   &Apache::lonnet::hostname($uhome));
 3048:     } elsif (($env{'form.login'} ne 'nochange') &&
 3049:              ($env{'form.login'} ne ''        )) {
 3050: 	# Modify user privileges
 3051:         if (! $amode || ! $genpwd) {
 3052: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3053: 	    return;
 3054: 	}
 3055: 	# Only allow authentication modification if the person has authority
 3056: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3057: 	    $r->print('Modifying authentication: '.
 3058:                       &Apache::lonnet::modifyuserauth(
 3059: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3060:                        $amode,$genpwd));
 3061:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3062: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3063: 	} else {
 3064: 	    # Okay, this is a non-fatal error.
 3065: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);
 3066: 	}
 3067:     } elsif (($env{'form.intarg'} ne '') &&
 3068:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3069:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3070:         $r->print('Modifying authentication: '.
 3071:                   &Apache::lonnet::modifyuserauth(
 3072:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3073:                   'internal',$env{'form.intarg'}));
 3074:     }
 3075:     $r->rflush(); # Finish display of header before time consuming actions start
 3076:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3077:     ##
 3078:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3079:     if ($context eq 'course') {
 3080:         ($cnum,$cdom) =
 3081:             &Apache::lonuserutils::get_course_identity();
 3082:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3083:         if ($showcredits) {
 3084:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3085:         }
 3086:     }
 3087:     if (! $env{'form.makeuser'} ) {
 3088:         # Check for need to change
 3089:         my %userenv = &Apache::lonnet::get
 3090:             ('environment',['firstname','middlename','lastname','generation',
 3091:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3092:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 3093:              'requestcourses.official','requestcourses.unofficial',
 3094:              'requestcourses.community','requestcourses.textbook',
 3095:              'requestcourses.lti','requestauthor',
 3096:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3097:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3098:              'reqcrsotherdom.placement'],
 3099:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3100:         my ($tmp) = keys(%userenv);
 3101:         if ($tmp =~ /^(con_lost|error)/i) { 
 3102:             %userenv = ();
 3103:         }
 3104:         my $no_forceid_alert;
 3105:         # Check to see if user information can be changed
 3106:         my %domconfig =
 3107:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3108:                                      $env{'form.ccdomain'});
 3109:         my @statuses = ('active','future');
 3110:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3111:         my ($auname,$audom);
 3112:         if ($context eq 'author') {
 3113:             $auname = $env{'user.name'};
 3114:             $audom = $env{'user.domain'};     
 3115:         }
 3116:         foreach my $item (keys(%roles)) {
 3117:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3118:             if ($context eq 'course') {
 3119:                 if ($cnum ne '' && $cdom ne '') {
 3120:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3121:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3122:                             push(@userroles,$role);
 3123:                         }
 3124:                     }
 3125:                 }
 3126:             } elsif ($context eq 'author') {
 3127:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3128:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 3129:                         push(@userroles,$role);
 3130:                     }
 3131:                 }
 3132:             }
 3133:         }
 3134:         if ($env{'form.action'} eq 'singlestudent') {
 3135:             if (!grep(/^st$/,@userroles)) {
 3136:                 push(@userroles,'st');
 3137:             }
 3138:         } else {
 3139:             # Check for course or co-author roles being activated or re-enabled
 3140:             if ($context eq 'author' || $context eq 'course') {
 3141:                 foreach my $key (keys(%env)) {
 3142:                     if ($context eq 'author') {
 3143:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3144:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3145:                                 push(@userroles,$1);
 3146:                             }
 3147:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3148:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3149:                                 push(@userroles,$1);
 3150:                             }
 3151:                         }
 3152:                     } elsif ($context eq 'course') {
 3153:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3154:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3155:                                 push(@userroles,$1);
 3156:                             }
 3157:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3158:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3159:                                 push(@userroles,$1);
 3160:                             }
 3161:                         }
 3162:                     }
 3163:                 }
 3164:             }
 3165:         }
 3166:         #Check to see if we can change personal data for the user 
 3167:         my (@mod_disallowed,@longroles);
 3168:         foreach my $role (@userroles) {
 3169:             if ($role eq 'cr') {
 3170:                 push(@longroles,'Custom');
 3171:             } else {
 3172:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3173:             }
 3174:         }
 3175:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3176:         foreach my $item (@userinfo) {
 3177:             # Strip leading and trailing whitespace
 3178:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3179:             if (!$canmodify{$item}) {
 3180:                 if (defined($env{'form.c'.$item})) {
 3181:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3182:                         push(@mod_disallowed,$item);
 3183:                     }
 3184:                 }
 3185:                 $env{'form.c'.$item} = $userenv{$item};
 3186:             }
 3187:         }
 3188:         # Check to see if we can change the Student/Employee ID
 3189:         my $forceid = $env{'form.forceid'};
 3190:         my $recurseid = $env{'form.recurseid'};
 3191:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3192:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3193:                                             $env{'form.ccuname'});
 3194:         if (($uidhash{$env{'form.ccuname'}}) && 
 3195:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3196:             (!$forceid)) {
 3197:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3198:                 $env{'form.cid'} = $userenv{'id'};
 3199:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3200:                                    .'<br />'
 3201:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3202:                                    .'<br />'."\n";
 3203:             }
 3204:         }
 3205:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3206:             my $checkhash;
 3207:             my $checks = { 'id' => 1 };
 3208:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3209:                    { 'newuser' => $newuser,
 3210:                      'id'  => $env{'form.cid'}, 
 3211:                    };
 3212:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3213:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3214:             if (ref($alerts{'id'}) eq 'HASH') {
 3215:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3216:                    $env{'form.cid'} = $userenv{'id'};
 3217:                 }
 3218:             }
 3219:         }
 3220:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3221:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3222:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3223:             %oldsettingstatus,%newsettingstatus);
 3224:         @disporder = ('inststatus');
 3225:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3226:             push(@disporder,'requestcourses','requestauthor');
 3227:         } else {
 3228:             push(@disporder,'reqcrsotherdom');
 3229:         }
 3230:         push(@disporder,('quota','tools'));
 3231:         $oldinststatus = $userenv{'inststatus'};
 3232:         foreach my $name ('portfolio','author') {
 3233:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3234:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3235:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3236:         }
 3237:         my %canshow;
 3238:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3239:             $canshow{'quota'} = 1;
 3240:         }
 3241:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3242:             $canshow{'tools'} = 1;
 3243:         }
 3244:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3245:             $canshow{'requestcourses'} = 1;
 3246:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3247:             $canshow{'reqcrsotherdom'} = 1;
 3248:         }
 3249:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3250:             $canshow{'inststatus'} = 1;
 3251:         }
 3252:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3253:             $canshow{'requestauthor'} = 1;
 3254:         }
 3255:         my (%changeHash,%changed);
 3256:         if ($oldinststatus eq '') {
 3257:             $oldsettings{'inststatus'} = $othertitle; 
 3258:         } else {
 3259:             if (ref($usertypes) eq 'HASH') {
 3260:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3261:             } else {
 3262:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3263:             }
 3264:         }
 3265:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3266:         if ($canmodify_status{'inststatus'}) {
 3267:             $canshow{'inststatus'} = 1;
 3268:             if (exists($env{'form.inststatus'})) {
 3269:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3270:                 if (@inststatuses > 0) {
 3271:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3272:                     $changeHash{'inststatus'} = $newinststatus;
 3273:                     if ($newinststatus ne $oldinststatus) {
 3274:                         $changed{'inststatus'} = $newinststatus;
 3275:                         foreach my $name ('portfolio','author') {
 3276:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3277:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3278:                         }
 3279:                     }
 3280:                     if (ref($usertypes) eq 'HASH') {
 3281:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3282:                     } else {
 3283:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3284:                     }
 3285:                 }
 3286:             } else {
 3287:                 $newinststatus = '';
 3288:                 $changeHash{'inststatus'} = $newinststatus;
 3289:                 $newsettings{'inststatus'} = $othertitle;
 3290:                 if ($newinststatus ne $oldinststatus) {
 3291:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3292:                     foreach my $name ('portfolio','author') {
 3293:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3294:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3295:                     }
 3296:                 }
 3297:             }
 3298:         } elsif ($context ne 'selfcreate') {
 3299:             $canshow{'inststatus'} = 1;
 3300:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3301:         }
 3302:         foreach my $name ('portfolio','author') {
 3303:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3304:         }
 3305:         if ($context eq 'domain') {
 3306:             foreach my $name ('portfolio','author') {
 3307:                 if ($userenv{$name.'quota'} ne '') {
 3308:                     $oldquota{$name} = $userenv{$name.'quota'};
 3309:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3310:                         if ($env{'form.'.$name.'quota'} eq '') {
 3311:                             $newquota{$name} = 0;
 3312:                         } else {
 3313:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3314:                             $newquota{$name} =~ s/[^\d\.]//g;
 3315:                         }
 3316:                         if ($newquota{$name} != $oldquota{$name}) {
 3317:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3318:                                 $changed{$name.'quota'} = 1;
 3319:                             }
 3320:                         }
 3321:                     } else {
 3322:                         if (&quota_admin('',\%changeHash,$name)) {
 3323:                             $changed{$name.'quota'} = 1;
 3324:                             $newquota{$name} = $newdefquota{$name};
 3325:                             $newisdefault{$name} = 1;
 3326:                         }
 3327:                     }
 3328:                 } else {
 3329:                     $oldisdefault{$name} = 1;
 3330:                     $oldquota{$name} = $olddefquota{$name};
 3331:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3332:                         if ($env{'form.'.$name.'quota'} eq '') {
 3333:                             $newquota{$name} = 0;
 3334:                         } else {
 3335:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3336:                             $newquota{$name} =~ s/[^\d\.]//g;
 3337:                         }
 3338:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3339:                             $changed{$name.'quota'} = 1;
 3340:                         }
 3341:                     } else {
 3342:                         $newquota{$name} = $newdefquota{$name};
 3343:                         $newisdefault{$name} = 1;
 3344:                     }
 3345:                 }
 3346:                 if ($oldisdefault{$name}) {
 3347:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3348:                 }  else {
 3349:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3350:                 }
 3351:                 if ($newisdefault{$name}) {
 3352:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3353:                 } else {
 3354:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3355:                 }
 3356:             }
 3357:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3358:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3359:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3360:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3361:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3362:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3363:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3364:             } else {
 3365:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3366:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3367:             }
 3368:         }
 3369:         foreach my $item (@userinfo) {
 3370:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3371:                 $namechanged{$item} = 1;
 3372:             }
 3373:         }
 3374:         foreach my $name ('portfolio','author') {
 3375:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3376:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3377:         }
 3378:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3379:             my ($chgresult,$namechgresult);
 3380:             if (keys(%changed) > 0) {
 3381:                 $chgresult = 
 3382:                     &Apache::lonnet::put('environment',\%changeHash,
 3383:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3384:                 if ($chgresult eq 'ok') {
 3385:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3386:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3387:                         my %newenvhash;
 3388:                         foreach my $key (keys(%changed)) {
 3389:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3390:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3391:                                 ($key eq 'placement') || ($key eq 'lti')) {
 3392:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3393:                                     $changeHash{'requestcourses.'.$key};
 3394:                                 if ($changeHash{'requestcourses.'.$key}) {
 3395:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3396:                                 } else {
 3397:                                     $newenvhash{'environment.canrequest.'.$key} =
 3398:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3399:                                             $key,'reload','requestcourses');
 3400:                                 }
 3401:                             } elsif ($key eq 'requestauthor') {
 3402:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3403:                                 if ($changeHash{$key}) {
 3404:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3405:                                 } else {
 3406:                                     $newenvhash{'environment.canrequest.author'} =
 3407:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3408:                                             $key,'reload','requestauthor');
 3409:                                 }
 3410:                             } elsif ($key ne 'quota') {
 3411:                                 $newenvhash{'environment.tools.'.$key} = 
 3412:                                     $changeHash{'tools.'.$key};
 3413:                                 if ($changeHash{'tools.'.$key} ne '') {
 3414:                                     $newenvhash{'environment.availabletools.'.$key} =
 3415:                                         $changeHash{'tools.'.$key};
 3416:                                 } else {
 3417:                                     $newenvhash{'environment.availabletools.'.$key} =
 3418:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3419:           $key,'reload','tools');
 3420:                                 }
 3421:                             }
 3422:                         }
 3423:                         if (keys(%newenvhash)) {
 3424:                             &Apache::lonnet::appenv(\%newenvhash);
 3425:                         }
 3426:                     }
 3427:                 }
 3428:             }
 3429:             if (keys(%namechanged) > 0) {
 3430:                 foreach my $field (@userinfo) {
 3431:                     $changeHash{$field}  = $env{'form.c'.$field};
 3432:                 }
 3433: # Make the change
 3434:                 $namechgresult =
 3435:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3436:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3437:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3438:                         $changeHash{'lastname'},$changeHash{'generation'},
 3439:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3440:                 %userupdate = (
 3441:                                lastname   => $env{'form.clastname'},
 3442:                                middlename => $env{'form.cmiddlename'},
 3443:                                firstname  => $env{'form.cfirstname'},
 3444:                                generation => $env{'form.cgeneration'},
 3445:                                id         => $env{'form.cid'},
 3446:                              );
 3447:             }
 3448:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3449:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3450:             # Tell the user we changed the name
 3451:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3452:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3453:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3454:                                   \%newsettingstext);
 3455:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3456:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3457:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3458:                     if (($recurseid) &&
 3459:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3460:                         my $idresult = 
 3461:                             &Apache::lonuserutils::propagate_id_change(
 3462:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3463:                                 \%userupdate);
 3464:                         $r->print('<br />'.$idresult.'<br />');
 3465:                     }
 3466:                 }
 3467:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3468:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3469:                     my %newenvhash;
 3470:                     foreach my $key (keys(%changeHash)) {
 3471:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3472:                     }
 3473:                     &Apache::lonnet::appenv(\%newenvhash);
 3474:                 }
 3475:             } else { # error occurred
 3476:                 $r->print(
 3477:                     '<p class="LC_error">'
 3478:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3479:                             '"'.$env{'form.ccuname'}.'"',
 3480:                             '"'.$env{'form.ccdomain'}.'"')
 3481:                    .'</p>');
 3482:             }
 3483:         } else { # End of if ($env ... ) logic
 3484:             # They did not want to change the users name, quota, tool availability,
 3485:             # or ability to request creation of courses, 
 3486:             # but we can still tell them what the name and quota and availabilities are  
 3487:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3488:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3489:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3490:         }
 3491:         if (@mod_disallowed) {
 3492:             my ($rolestr,$contextname);
 3493:             if (@longroles > 0) {
 3494:                 $rolestr = join(', ',@longroles);
 3495:             } else {
 3496:                 $rolestr = &mt('No roles');
 3497:             }
 3498:             if ($context eq 'course') {
 3499:                 $contextname = 'course';
 3500:             } elsif ($context eq 'author') {
 3501:                 $contextname = 'co-author';
 3502:             }
 3503:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3504:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3505:             foreach my $field (@mod_disallowed) {
 3506:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3507:             }
 3508:             $r->print('</ul>');
 3509:             if (@mod_disallowed == 1) {
 3510:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3511:             } else {
 3512:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3513:             }
 3514:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3515:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3516:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3517:                          ,'<a href="'.$helplink.'">','</a>')
 3518:                       .'<br />');
 3519:         }
 3520:         $r->print('<span class="LC_warning">'
 3521:                   .$no_forceid_alert
 3522:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3523:                   .'</span>');
 3524:     }
 3525:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3526:     if ($env{'form.action'} eq 'singlestudent') {
 3527:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3528:                                $crstype,$showcredits,$defaultcredits);
 3529:         my $linktext = ($crstype eq 'Community' ?
 3530:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3531:         $r->print(
 3532:             &Apache::lonhtmlcommon::actionbox([
 3533:                 '<a href="javascript:backPage(document.userupdate)">'
 3534:                .($crstype eq 'Community' ? 
 3535:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3536:                .'</a>']));
 3537:     } else {
 3538:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3539:         if (keys(%namechanged) > 0) {
 3540:             if ($context eq 'course') {
 3541:                 if (@userroles > 0) {
 3542:                     if ((@rolechanges == 0) || 
 3543:                         (!(grep(/^st$/,@rolechanges)))) {
 3544:                         if (grep(/^st$/,@userroles)) {
 3545:                             my $classlistupdated =
 3546:                                 &Apache::lonuserutils::update_classlist($cdom,
 3547:                                               $cnum,$env{'form.ccdomain'},
 3548:                                        $env{'form.ccuname'},\%userupdate);
 3549:                         }
 3550:                     }
 3551:                 }
 3552:             }
 3553:         }
 3554:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3555:                                                      $env{'form.ccdomain'});
 3556:         if ($env{'form.popup'}) {
 3557:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3558:         } else {
 3559:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3560:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3561:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3562:         }
 3563:     }
 3564: }
 3565: 
 3566: sub display_userinfo {
 3567:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3568:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3569:         $newsetting,$newsettingtext) = @_;
 3570:     return unless (ref($order) eq 'ARRAY' &&
 3571:                    ref($canshow) eq 'HASH' && 
 3572:                    ref($requestcourses) eq 'ARRAY' && 
 3573:                    ref($requestauthor) eq 'ARRAY' &&
 3574:                    ref($usertools) eq 'ARRAY' && 
 3575:                    ref($userenv) eq 'HASH' &&
 3576:                    ref($changedhash) eq 'HASH' &&
 3577:                    ref($oldsetting) eq 'HASH' &&
 3578:                    ref($oldsettingtext) eq 'HASH' &&
 3579:                    ref($newsetting) eq 'HASH' &&
 3580:                    ref($newsettingtext) eq 'HASH');
 3581:     my %lt=&Apache::lonlocal::texthash(
 3582:          'ui'             => 'User Information',
 3583:          'uic'            => 'User Information Changed',
 3584:          'firstname'      => 'First Name',
 3585:          'middlename'     => 'Middle Name',
 3586:          'lastname'       => 'Last Name',
 3587:          'generation'     => 'Generation',
 3588:          'id'             => 'Student/Employee ID',
 3589:          'permanentemail' => 'Permanent e-mail address',
 3590:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3591:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3592:          'blog'           => 'Blog Availability',
 3593:          'webdav'         => 'WebDAV Availability',
 3594:          'aboutme'        => 'Personal Information Page Availability',
 3595:          'portfolio'      => 'Portfolio Availability',
 3596:          'official'       => 'Can Request Official Courses',
 3597:          'unofficial'     => 'Can Request Unofficial Courses',
 3598:          'community'      => 'Can Request Communities',
 3599:          'textbook'       => 'Can Request Textbook Courses',
 3600:          'placement'      => 'Can Request Placement Tests',
 3601:          'lti'            => 'Can Request LTI Courses',
 3602:          'requestauthor'  => 'Can Request Author Role',
 3603:          'inststatus'     => "Affiliation",
 3604:          'prvs'           => 'Previous Value:',
 3605:          'chto'           => 'Changed To:'
 3606:     );
 3607:     if ($changed) {
 3608:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3609:                 &Apache::loncommon::start_data_table().
 3610:                 &Apache::loncommon::start_data_table_header_row());
 3611:         $r->print("<th>&nbsp;</th>\n");
 3612:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3613:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3614:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3615:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3616: 
 3617:         foreach my $item (@userinfo) {
 3618:             my $value = $env{'form.c'.$item};
 3619:             #show changes only:
 3620:             unless ($value eq $userenv->{$item}){
 3621:                 $r->print(&Apache::loncommon::start_data_table_row());
 3622:                 $r->print("<td>$lt{$item}</td>\n");
 3623:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3624:                 $r->print("<td>$value </td>\n");
 3625:                 $r->print(&Apache::loncommon::end_data_table_row());
 3626:             }
 3627:         }
 3628:         foreach my $entry (@{$order}) {
 3629:             if ($canshow->{$entry}) {
 3630:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3631:                     my @items;
 3632:                     if ($entry eq 'requestauthor') {
 3633:                         @items = ($entry);
 3634:                     } else {
 3635:                         @items = @{$requestcourses};
 3636:                     }
 3637:                     foreach my $item (@items) {
 3638:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3639:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3640:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3641:                             $r->print("<td>$lt{$item}</td>\n");
 3642:                             $r->print("<td>".$oldsetting->{$item});
 3643:                             if ($oldsettingtext->{$item}) {
 3644:                                 if ($oldsetting->{$item}) {
 3645:                                     $r->print(' -- ');
 3646:                                 }
 3647:                                 $r->print($oldsettingtext->{$item});
 3648:                             }
 3649:                             $r->print("</td>\n");
 3650:                             $r->print("<td>".$newsetting->{$item});
 3651:                             if ($newsettingtext->{$item}) {
 3652:                                 if ($newsetting->{$item}) {
 3653:                                     $r->print(' -- ');
 3654:                                 }
 3655:                                 $r->print($newsettingtext->{$item});
 3656:                             }
 3657:                             $r->print("</td>\n");
 3658:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3659:                         }
 3660:                     }
 3661:                 } elsif ($entry eq 'tools') {
 3662:                     foreach my $item (@{$usertools}) {
 3663:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3664:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3665:                             $r->print("<td>$lt{$item}</td>\n");
 3666:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3667:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3668:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3669:                         }
 3670:                     }
 3671:                 } elsif ($entry eq 'quota') {
 3672:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3673:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3674:                         foreach my $name ('portfolio','author') {
 3675:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3676:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3677:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3678:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3679:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3680:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3681:                             }
 3682:                         }
 3683:                     }
 3684:                 } else {
 3685:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3686:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3687:                         $r->print("<td>$lt{$entry}</td>\n");
 3688:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3689:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3690:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3691:                     }
 3692:                 }
 3693:             }
 3694:         }
 3695:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3696:     } else {
 3697:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3698:                   '<p>'.&mt('No changes made to user information').'</p>');
 3699:     }
 3700:     return;
 3701: }
 3702: 
 3703: sub tool_changes {
 3704:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3705:         $changed,$newaccess,$newaccesstext) = @_;
 3706:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3707:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3708:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3709:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3710:         return;
 3711:     }
 3712:     my %reqdisplay = &requestchange_display();
 3713:     if ($context eq 'reqcrsotherdom') {
 3714:         my @options = ('approval','validate','autolimit');
 3715:         my $optregex = join('|',@options);
 3716:         my $cdom = $env{'request.role.domain'};
 3717:         foreach my $tool (@{$usertools}) {
 3718:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3719:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3720:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3721:             my ($newop,$limit);
 3722:             if ($env{'form.'.$context.'_'.$tool}) {
 3723:                 $newop = $env{'form.'.$context.'_'.$tool};
 3724:                 if ($newop eq 'autolimit') {
 3725:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3726:                     $limit =~ s/\D+//g;
 3727:                     $newop .= '='.$limit;
 3728:                 }
 3729:             }
 3730:             if ($userenv->{$context.'.'.$tool} eq '') {
 3731:                 if ($newop) {
 3732:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3733:                                                   $changeHash,$context);
 3734:                     if ($changed->{$tool}) {
 3735:                         if ($newop =~ /^autolimit/) {
 3736:                             if ($limit) {
 3737:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3738:                             } else {
 3739:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3740:                             }
 3741:                         } else {
 3742:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3743:                         }
 3744:                     } else {
 3745:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3746:                     }
 3747:                 }
 3748:             } else {
 3749:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3750:                 my @new;
 3751:                 my $changedoms;
 3752:                 foreach my $req (@curr) {
 3753:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3754:                         my $oldop = $1;
 3755:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3756:                             my $limit = $1;
 3757:                             if ($limit) {
 3758:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3759:                             } else {
 3760:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3761:                             }
 3762:                         } else {
 3763:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3764:                         }
 3765:                         if ($oldop ne $newop) {
 3766:                             $changedoms = 1;
 3767:                             foreach my $item (@curr) {
 3768:                                 my ($reqdom,$option) = split(':',$item);
 3769:                                 unless ($reqdom eq $cdom) {
 3770:                                     push(@new,$item);
 3771:                                 }
 3772:                             }
 3773:                             if ($newop) {
 3774:                                 push(@new,$cdom.':'.$newop);
 3775:                             }
 3776:                             @new = sort(@new);
 3777:                         }
 3778:                         last;
 3779:                     }
 3780:                 }
 3781:                 if ((!$changedoms) && ($newop)) {
 3782:                     $changedoms = 1;
 3783:                     @new = sort(@curr,$cdom.':'.$newop);
 3784:                 }
 3785:                 if ($changedoms) {
 3786:                     my $newdomstr;
 3787:                     if (@new) {
 3788:                         $newdomstr = join(',',@new);
 3789:                     }
 3790:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3791:                                                   $context);
 3792:                     if ($changed->{$tool}) {
 3793:                         if ($env{'form.'.$context.'_'.$tool}) {
 3794:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3795:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3796:                                 $limit =~ s/\D+//g;
 3797:                                 if ($limit) {
 3798:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3799:                                 } else {
 3800:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3801:                                 }
 3802:                             } else {
 3803:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3804:                             }
 3805:                         } else {
 3806:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3807:                         }
 3808:                     }
 3809:                 }
 3810:             }
 3811:         }
 3812:         return;
 3813:     }
 3814:     foreach my $tool (@{$usertools}) {
 3815:         my ($newval,$limit,$envkey);
 3816:         $envkey = $context.'.'.$tool;
 3817:         if ($context eq 'requestcourses') {
 3818:             $newval = $env{'form.crsreq_'.$tool};
 3819:             if ($newval eq 'autolimit') {
 3820:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3821:                 $limit =~ s/\D+//g;
 3822:                 $newval .= '='.$limit;
 3823:             }
 3824:         } elsif ($context eq 'requestauthor') {
 3825:             $newval = $env{'form.'.$context};
 3826:             $envkey = $context;
 3827:         } else {
 3828:             $newval = $env{'form.'.$context.'_'.$tool};
 3829:         }
 3830:         if ($userenv->{$envkey} ne '') {
 3831:             $oldaccess->{$tool} = &mt('custom');
 3832:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3833:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3834:                     my $currlimit = $1;
 3835:                     if ($currlimit eq '') {
 3836:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3837:                     } else {
 3838:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3839:                     }
 3840:                 } elsif ($userenv->{$envkey}) {
 3841:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3842:                 } else {
 3843:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3844:                 }
 3845:             } else {
 3846:                 if ($userenv->{$envkey}) {
 3847:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3848:                 } else {
 3849:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3850:                 }
 3851:             }
 3852:             $changeHash->{$envkey} = $userenv->{$envkey};
 3853:             if ($env{'form.custom'.$tool} == 1) {
 3854:                 if ($newval ne $userenv->{$envkey}) {
 3855:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3856:                                                     $context);
 3857:                     if ($changed->{$tool}) {
 3858:                         $newaccess->{$tool} = &mt('custom');
 3859:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3860:                             if ($newval =~ /^autolimit/) {
 3861:                                 if ($limit) {
 3862:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3863:                                 } else {
 3864:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3865:                                 }
 3866:                             } elsif ($newval) {
 3867:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3868:                             } else {
 3869:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3870:                             }
 3871:                         } else {
 3872:                             if ($newval) {
 3873:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3874:                             } else {
 3875:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3876:                             }
 3877:                         }
 3878:                     } else {
 3879:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3880:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3881:                             if ($newval =~ /^autolimit/) {
 3882:                                 if ($limit) {
 3883:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3884:                                 } else {
 3885:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3886:                                 }
 3887:                             } elsif ($newval) {
 3888:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3889:                             } else {
 3890:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3891:                             }
 3892:                         } else {
 3893:                             if ($userenv->{$context.'.'.$tool}) {
 3894:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3895:                             } else {
 3896:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3897:                             }
 3898:                         }
 3899:                     }
 3900:                 } else {
 3901:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3902:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3903:                 }
 3904:             } else {
 3905:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3906:                 if ($changed->{$tool}) {
 3907:                     $newaccess->{$tool} = &mt('default');
 3908:                 } else {
 3909:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3910:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3911:                         if ($newval =~ /^autolimit/) {
 3912:                             if ($limit) {
 3913:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3914:                             } else {
 3915:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3916:                             }
 3917:                         } elsif ($newval) {
 3918:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3919:                         } else {
 3920:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3921:                         }
 3922:                     } else {
 3923:                         if ($userenv->{$context.'.'.$tool}) {
 3924:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3925:                         } else {
 3926:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3927:                         }
 3928:                     }
 3929:                 }
 3930:             }
 3931:         } else {
 3932:             $oldaccess->{$tool} = &mt('default');
 3933:             if ($env{'form.custom'.$tool} == 1) {
 3934:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3935:                                                 $context);
 3936:                 if ($changed->{$tool}) {
 3937:                     $newaccess->{$tool} = &mt('custom');
 3938:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3939:                         if ($newval =~ /^autolimit/) {
 3940:                             if ($limit) {
 3941:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3942:                             } else {
 3943:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3944:                             }
 3945:                         } elsif ($newval) {
 3946:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3947:                         } else {
 3948:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3949:                         }
 3950:                     } else {
 3951:                         if ($newval) {
 3952:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3953:                         } else {
 3954:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3955:                         }
 3956:                     }
 3957:                 } else {
 3958:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3959:                 }
 3960:             } else {
 3961:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3962:             }
 3963:         }
 3964:     }
 3965:     return;
 3966: }
 3967: 
 3968: sub update_roles {
 3969:     my ($r,$context,$showcredits) = @_;
 3970:     my $now=time;
 3971:     my @rolechanges;
 3972:     my %disallowed;
 3973:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3974:     foreach my $key (keys(%env)) {
 3975: 	next if (! $env{$key});
 3976:         next if ($key eq 'form.action');
 3977: 	# Revoke roles
 3978: 	if ($key=~/^form\.rev/) {
 3979: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3980: # Revoke standard role
 3981: 		my ($scope,$role) = ($1,$2);
 3982: 		my $result =
 3983: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3984: 						$env{'form.ccuname'},
 3985: 						$scope,$role,'','',$context);
 3986:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3987:                             &mt('Revoking [_1] in [_2]',
 3988:                                 &Apache::lonnet::plaintext($role),
 3989:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3990:                                 $result ne "ok").'<br />');
 3991:                 if ($result ne "ok") {
 3992:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3993:                 }
 3994: 		if ($role eq 'st') {
 3995: 		    my $result = 
 3996:                         &Apache::lonuserutils::classlist_drop($scope,
 3997:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3998: 			    $now);
 3999:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4000: 		}
 4001:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4002:                     push(@rolechanges,$role);
 4003:                 }
 4004: 	    }
 4005: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 4006: # Revoke custom role
 4007:                 my $result = &Apache::lonnet::revokecustomrole(
 4008:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 4009:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4010:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 4011:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4012:                             $result ne 'ok').'<br />');
 4013:                 if ($result ne "ok") {
 4014:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4015:                 }
 4016:                 if (!grep(/^cr$/,@rolechanges)) {
 4017:                     push(@rolechanges,'cr');
 4018:                 }
 4019: 	    }
 4020: 	} elsif ($key=~/^form\.del/) {
 4021: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4022: # Delete standard role
 4023: 		my ($scope,$role) = ($1,$2);
 4024: 		my $result =
 4025: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4026: 						$env{'form.ccuname'},
 4027: 						$scope,$role,$now,0,1,'',
 4028:                                                 $context);
 4029:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4030:                             &mt('Deleting [_1] in [_2]',
 4031:                                 &Apache::lonnet::plaintext($role),
 4032:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4033:                             $result ne 'ok').'<br />');
 4034:                 if ($result ne "ok") {
 4035:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4036:                 }
 4037: 
 4038: 		if ($role eq 'st') {
 4039: 		    my $result = 
 4040:                         &Apache::lonuserutils::classlist_drop($scope,
 4041:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4042: 			    $now);
 4043: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4044: 		}
 4045:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4046:                     push(@rolechanges,$role);
 4047:                 }
 4048:             }
 4049: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4050:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4051: # Delete custom role
 4052:                 my $result =
 4053:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4054:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4055:                         0,1,$context);
 4056:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4057:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4058:                       $result ne "ok").'<br />');
 4059:                 if ($result ne "ok") {
 4060:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4061:                 }
 4062: 
 4063:                 if (!grep(/^cr$/,@rolechanges)) {
 4064:                     push(@rolechanges,'cr');
 4065:                 }
 4066:             }
 4067: 	} elsif ($key=~/^form\.ren/) {
 4068:             my $udom = $env{'form.ccdomain'};
 4069:             my $uname = $env{'form.ccuname'};
 4070: # Re-enable standard role
 4071: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4072:                 my $url = $1;
 4073:                 my $role = $2;
 4074:                 my $logmsg;
 4075:                 my $output;
 4076:                 if ($role eq 'st') {
 4077:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4078:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4079:                         my $credits;
 4080:                         if ($showcredits) {
 4081:                             my $defaultcredits = 
 4082:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4083:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4084:                         }
 4085:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4086:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4087:                             if ($result eq 'refused' && $logmsg) {
 4088:                                 $output = $logmsg;
 4089:                             } else { 
 4090:                                 $output = &mt('Error: [_1]',$result)."\n";
 4091:                             }
 4092:                         } else {
 4093:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4094:                                         &Apache::lonnet::plaintext($role),
 4095:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4096:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4097:                         }
 4098:                     }
 4099:                 } else {
 4100: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4101:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4102:                                $context);
 4103:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4104:                                         &Apache::lonnet::plaintext($role),
 4105:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4106:                     if ($result ne "ok") {
 4107:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4108:                     }
 4109:                 }
 4110:                 $r->print($output);
 4111:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4112:                     push(@rolechanges,$role);
 4113:                 }
 4114: 	    }
 4115: # Re-enable custom role
 4116: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4117:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4118:                 my $result = &Apache::lonnet::assigncustomrole(
 4119:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4120:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4121:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4122:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4123:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4124:                     $result ne "ok").'<br />');
 4125:                 if ($result ne "ok") {
 4126:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4127:                 }
 4128:                 if (!grep(/^cr$/,@rolechanges)) {
 4129:                     push(@rolechanges,'cr');
 4130:                 }
 4131:             }
 4132: 	} elsif ($key=~/^form\.act/) {
 4133:             my $udom = $env{'form.ccdomain'};
 4134:             my $uname = $env{'form.ccuname'};
 4135: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4136:                 # Activate a custom role
 4137: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4138: 		my $url='/'.$one.'/'.$two;
 4139: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4140: 
 4141:                 my $start = ( $env{'form.start_'.$full} ?
 4142:                               $env{'form.start_'.$full} :
 4143:                               $now );
 4144:                 my $end   = ( $env{'form.end_'.$full} ?
 4145:                               $env{'form.end_'.$full} :
 4146:                               0 );
 4147:                                                                                      
 4148:                 # split multiple sections
 4149:                 my %sections = ();
 4150:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 4151:                 if ($num_sections == 0) {
 4152:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4153:                 } else {
 4154: 		    my %curr_groups =
 4155: 			&Apache::longroup::coursegroups($one,$two);
 4156:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4157:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4158:                             exists($curr_groups{$sec})) {
 4159:                             $disallowed{$sec} = $url;
 4160:                             next;
 4161:                         }
 4162:                         my $securl = $url.'/'.$sec;
 4163: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4164:                     }
 4165:                 }
 4166:                 if (!grep(/^cr$/,@rolechanges)) {
 4167:                     push(@rolechanges,'cr');
 4168:                 }
 4169: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4170: 		# Activate roles for sections with 3 id numbers
 4171: 		# set start, end times, and the url for the class
 4172: 		my ($one,$two,$three)=($1,$2,$3);
 4173: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4174: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4175: 			      $now );
 4176: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4177: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4178: 			      0 );
 4179: 		my $url='/'.$one.'/'.$two;
 4180:                 my $type = 'three';
 4181:                 # split multiple sections
 4182:                 my %sections = ();
 4183:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4184:                 my $credits;
 4185:                 if ($three eq 'st') {
 4186:                     if ($showcredits) { 
 4187:                         my $defaultcredits = 
 4188:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4189:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4190:                         $credits =~ s/[^\d\.]//g;
 4191:                         if ($credits eq $defaultcredits) {
 4192:                             undef($credits);
 4193:                         }
 4194:                     }
 4195:                 }
 4196:                 if ($num_sections == 0) {
 4197:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4198:                 } else {
 4199:                     my %curr_groups = 
 4200: 			&Apache::longroup::coursegroups($one,$two);
 4201:                     my $emptysec = 0;
 4202:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4203:                         $sec =~ s/\W//g;
 4204:                         if ($sec ne '') {
 4205:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4206:                                 exists($curr_groups{$sec})) {
 4207:                                 $disallowed{$sec} = $url;
 4208:                                 next;
 4209:                             }
 4210:                             my $securl = $url.'/'.$sec;
 4211:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4212:                         } else {
 4213:                             $emptysec = 1;
 4214:                         }
 4215:                     }
 4216:                     if ($emptysec) {
 4217:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4218:                     }
 4219:                 }
 4220:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4221:                     push(@rolechanges,$three);
 4222:                 }
 4223: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4224: 		# Activate roles for sections with two id numbers
 4225: 		# set start, end times, and the url for the class
 4226: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4227: 			      $env{'form.start_'.$1.'_'.$2} : 
 4228: 			      $now );
 4229: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4230: 			      $env{'form.end_'.$1.'_'.$2} :
 4231: 			      0 );
 4232:                 my $one = $1;
 4233:                 my $two = $2;
 4234: 		my $url='/'.$one.'/';
 4235:                 # split multiple sections
 4236:                 my %sections = ();
 4237:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4238:                 if ($num_sections == 0) {
 4239:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4240:                 } else {
 4241:                     my $emptysec = 0;
 4242:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4243:                         if ($sec ne '') {
 4244:                             my $securl = $url.'/'.$sec;
 4245:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4246:                         } else {
 4247:                             $emptysec = 1;
 4248:                         }
 4249:                     }
 4250:                     if ($emptysec) {
 4251:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4252:                     }
 4253:                 }
 4254:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4255:                     push(@rolechanges,$two);
 4256:                 }
 4257: 	    } else {
 4258: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4259:             }
 4260:             foreach my $key (sort(keys(%disallowed))) {
 4261:                 $r->print('<p class="LC_warning">');
 4262:                 if (($key eq 'none') || ($key eq 'all')) {  
 4263:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4264:                 } else {
 4265:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is the name of a course group.','<tt>'.$key.'</tt>'));
 4266:                 }
 4267:                 $r->print('</p><p>'
 4268:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4269:                              ,'<a href="javascript:history.go(-1)'
 4270:                              ,'</a>')
 4271:                          .'</p><br />'
 4272:                 );
 4273:             }
 4274: 	}
 4275:     } # End of foreach (keys(%env))
 4276: # Flush the course logs so reverse user roles immediately updated
 4277:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4278:     if (@rolechanges == 0) {
 4279:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4280:     }
 4281:     return @rolechanges;
 4282: }
 4283: 
 4284: sub get_user_credits {
 4285:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4286:     if ($cdom eq '' || $cnum eq '') {
 4287:         return unless ($env{'request.course.id'});
 4288:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4289:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4290:     }
 4291:     my $credits;
 4292:     my %currhash =
 4293:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4294:     if (keys(%currhash) > 0) {
 4295:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4296:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4297:         $credits = $items[$crdidx];
 4298:         $credits =~ s/[^\d\.]//g;
 4299:     }
 4300:     if ($credits eq $defaultcredits) {
 4301:         undef($credits);
 4302:     }
 4303:     return $credits;
 4304: }
 4305: 
 4306: sub enroll_single_student {
 4307:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4308:         $showcredits,$defaultcredits) = @_;
 4309:     $r->print('<h3>');
 4310:     if ($crstype eq 'Community') {
 4311:         $r->print(&mt('Enrolling Member'));
 4312:     } else {
 4313:         $r->print(&mt('Enrolling Student'));
 4314:     }
 4315:     $r->print('</h3>');
 4316: 
 4317:     # Remove non alphanumeric values from section
 4318:     $env{'form.sections'}=~s/\W//g;
 4319: 
 4320:     my $credits;
 4321:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4322:         $credits = $env{'form.credits'};
 4323:         $credits =~ s/[^\d\.]//g;
 4324:         if ($credits ne '') {
 4325:             if ($credits eq $defaultcredits) {
 4326:                 undef($credits);
 4327:             }
 4328:         }
 4329:     }
 4330: 
 4331:     # Clean out any old student roles the user has in this class.
 4332:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4333:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4334:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4335:     my $enroll_result =
 4336:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4337:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4338:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4339:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4340:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4341:             $credits);
 4342:     if ($enroll_result =~ /^ok/) {
 4343:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4344:         if ($env{'form.sections'} ne '') {
 4345:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4346:         }
 4347:         my ($showstart,$showend);
 4348:         if ($startdate <= $now) {
 4349:             $showstart = &mt('Access starts immediately');
 4350:         } else {
 4351:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4352:         }
 4353:         if ($enddate == 0) {
 4354:             $showend = &mt('ends: no ending date');
 4355:         } else {
 4356:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4357:         }
 4358:         $r->print('.<br />'.$showstart.'; '.$showend);
 4359:         if ($startdate <= $now && !$newuser) {
 4360:             $r->print('<p class="LC_info">');
 4361:             if ($crstype eq 'Community') {
 4362:                 $r->print(&mt('If the member is currently logged-in to LON-CAPA, the new role can be displayed by using the "Check for changes" link on the Roles/Courses page.'));
 4363:             } else {
 4364:                 $r->print(&mt('If the student is currently logged-in to LON-CAPA, the new role can be displayed by using the "Check for changes" link on the Roles/Courses page.'));
 4365:            }
 4366:            $r->print('</p>');
 4367:         }
 4368:     } else {
 4369:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4370:     }
 4371:     return;
 4372: }
 4373: 
 4374: sub get_defaultquota_text {
 4375:     my ($settingstatus) = @_;
 4376:     my $defquotatext; 
 4377:     if ($settingstatus eq '') {
 4378:         $defquotatext = &mt('default');
 4379:     } else {
 4380:         my ($usertypes,$order) =
 4381:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4382:         if ($usertypes->{$settingstatus} eq '') {
 4383:             $defquotatext = &mt('default');
 4384:         } else {
 4385:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4386:         }
 4387:     }
 4388:     return $defquotatext;
 4389: }
 4390: 
 4391: sub update_result_form {
 4392:     my ($uhome) = @_;
 4393:     my $outcome = 
 4394:     '<form name="userupdate" method="post" action="">'."\n";
 4395:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4396:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4397:     }
 4398:     if ($env{'form.origname'} ne '') {
 4399:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4400:     }
 4401:     foreach my $item ('sortby','seluname','seludom') {
 4402:         if (exists($env{'form.'.$item})) {
 4403:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4404:         }
 4405:     }
 4406:     if ($uhome eq 'no_host') {
 4407:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4408:     }
 4409:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4410:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4411:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4412:                 '</form>';
 4413:     return $outcome;
 4414: }
 4415: 
 4416: sub quota_admin {
 4417:     my ($setquota,$changeHash,$name) = @_;
 4418:     my $quotachanged;
 4419:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4420:         # Current user has quota modification privileges
 4421:         if (ref($changeHash) eq 'HASH') {
 4422:             $quotachanged = 1;
 4423:             $changeHash->{$name.'quota'} = $setquota;
 4424:         }
 4425:     }
 4426:     return $quotachanged;
 4427: }
 4428: 
 4429: sub tool_admin {
 4430:     my ($tool,$settool,$changeHash,$context) = @_;
 4431:     my $canchange = 0; 
 4432:     if ($context eq 'requestcourses') {
 4433:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4434:             $canchange = 1;
 4435:         }
 4436:     } elsif ($context eq 'reqcrsotherdom') {
 4437:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4438:             $canchange = 1;
 4439:         }
 4440:     } elsif ($context eq 'requestauthor') {
 4441:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4442:             $canchange = 1;
 4443:         }
 4444:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4445:         # Current user has quota modification privileges
 4446:         $canchange = 1;
 4447:     }
 4448:     my $toolchanged;
 4449:     if ($canchange) {
 4450:         if (ref($changeHash) eq 'HASH') {
 4451:             $toolchanged = 1;
 4452:             if ($tool eq 'requestauthor') {
 4453:                 $changeHash->{$context} = $settool;
 4454:             } else {
 4455:                 $changeHash->{$context.'.'.$tool} = $settool;
 4456:             }
 4457:         }
 4458:     }
 4459:     return $toolchanged;
 4460: }
 4461: 
 4462: sub build_roles {
 4463:     my ($sectionstr,$sections,$role) = @_;
 4464:     my $num_sections = 0;
 4465:     if ($sectionstr=~ /,/) {
 4466:         my @secnums = split/,/,$sectionstr;
 4467:         if ($role eq 'st') {
 4468:             $secnums[0] =~ s/\W//g;
 4469:             $$sections{$secnums[0]} = 1;
 4470:             $num_sections = 1;
 4471:         } else {
 4472:             foreach my $sec (@secnums) {
 4473:                 $sec =~ ~s/\W//g;
 4474:                 if (!($sec eq "")) {
 4475:                     if (exists($$sections{$sec})) {
 4476:                         $$sections{$sec} ++;
 4477:                     } else {
 4478:                         $$sections{$sec} = 1;
 4479:                         $num_sections ++;
 4480:                     }
 4481:                 }
 4482:             }
 4483:         }
 4484:     } else {
 4485:         $sectionstr=~s/\W//g;
 4486:         unless ($sectionstr eq '') {
 4487:             $$sections{$sectionstr} = 1;
 4488:             $num_sections ++;
 4489:         }
 4490:     }
 4491: 
 4492:     return $num_sections;
 4493: }
 4494: 
 4495: # ========================================================== Custom Role Editor
 4496: 
 4497: sub custom_role_editor {
 4498:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4499:     my $action = $env{'form.customroleaction'};
 4500:     my ($rolename,$helpitem);
 4501:     if ($action eq 'new') {
 4502:         $rolename=$env{'form.newrolename'};
 4503:     } else {
 4504:         $rolename=$env{'form.rolename'};
 4505:     }
 4506: 
 4507:     my ($crstype,$context);
 4508:     if ($env{'request.course.id'}) {
 4509:         $crstype = &Apache::loncommon::course_type();
 4510:         $context = 'course';
 4511:         $helpitem = 'Course_Editing_Custom_Roles';
 4512:     } else {
 4513:         $context = 'domain';
 4514:         $crstype = 'course';
 4515:         $helpitem = 'Domain_Editing_Custom_Roles';
 4516:     }
 4517: 
 4518:     $rolename=~s/[^A-Za-z0-9]//gs;
 4519:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4520: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 4521:                                    $permission);
 4522:         return;
 4523:     }
 4524: 
 4525:     my $formname = 'form1';
 4526:     my %privs=();
 4527:     my $body_top = '<h2>';
 4528: # ------------------------------------------------------- Does this role exist?
 4529:     my ($rdummy,$roledef)=
 4530: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4531:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4532:         $body_top .= &mt('Existing Role').' "';
 4533: # ------------------------------------------------- Get current role privileges
 4534:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4535:         if ($privs{'system'} =~ /bre\&S/) {
 4536:             if ($context eq 'domain') {
 4537:                 $crstype = 'Course';
 4538:             } elsif ($crstype eq 'Community') {
 4539:                 $privs{'system'} =~ s/bre\&S//;
 4540:             }
 4541:         } elsif ($context eq 'domain') {
 4542:             $crstype = 'Course';
 4543:         }
 4544:     } else {
 4545:         $body_top .= &mt('New Role').' "';
 4546:         $roledef='';
 4547:     }
 4548:     $body_top .= $rolename.'"</h2>';
 4549: 
 4550: # ------------------------------------------------------- What can be assigned?
 4551:     my %full=();
 4552:     my %levels=(
 4553:                  course => {},
 4554:                  domain => {},
 4555:                  system => {},
 4556:                );
 4557:     my %levelscurrent=(
 4558:                         course => {},
 4559:                         domain => {},
 4560:                         system => {},
 4561:                       );
 4562:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4563:     my ($jsback,$elements) = &crumb_utilities();
 4564:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4565:     my $head_script =
 4566:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4567:                                                   \%full,\@templateroles,$jsback);
 4568:     push (@{$brcrum},
 4569:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4570:                text => "Pick custom role",
 4571:                faq  => 282,bug=>'Instructor Interface',},
 4572:               {href => "javascript:backPage(document.$formname,'','')",
 4573:                text => "Edit custom role",
 4574:                faq  => 282,
 4575:                bug  => 'Instructor Interface',
 4576:                help => $helpitem}
 4577:               );
 4578:     my $args = { bread_crumbs          => $brcrum,
 4579:                  bread_crumbs_component => 'User Management'};
 4580:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4581:                                              $head_script,$args).
 4582:               $body_top);
 4583:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4584:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4585:                                                         \@templateroles,$prefix));
 4586: 
 4587:     $r->print(<<ENDCCF);
 4588: <input type="hidden" name="phase" value="set_custom_roles" />
 4589: <input type="hidden" name="rolename" value="$rolename" />
 4590: ENDCCF
 4591:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4592:                                                        \%levelscurrent,$prefix));
 4593:     $r->print(&Apache::loncommon::end_data_table().
 4594:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4595:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4596:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4597:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4598:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4599: }
 4600: 
 4601: # ---------------------------------------------------------- Call to definerole
 4602: sub set_custom_role {
 4603:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4604:     my $rolename=$env{'form.rolename'};
 4605:     $rolename=~s/[^A-Za-z0-9]//gs;
 4606:     if (!$rolename) {
 4607: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4608:         return;
 4609:     }
 4610:     my ($jsback,$elements) = &crumb_utilities();
 4611:     my $jscript = '<script type="text/javascript">'
 4612:                  .'// <![CDATA['."\n"
 4613:                  .$jsback."\n"
 4614:                  .'// ]]>'."\n"
 4615:                  .'</script>'."\n";
 4616:     my $helpitem = 'Course_Editing_Custom_Roles';
 4617:     if ($context eq 'domain') {
 4618:         $helpitem = 'Domain_Editing_Custom_Roles';
 4619:     }
 4620:     push(@{$brcrum},
 4621:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4622:          text => "Pick custom role",
 4623:          faq  => 282,
 4624:          bug  => 'Instructor Interface',},
 4625:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4626:          text => "Edit custom role",
 4627:          faq  => 282,
 4628:          bug  => 'Instructor Interface',},
 4629:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4630:          text => "Result",
 4631:          faq  => 282,
 4632:          bug  => 'Instructor Interface',
 4633:          help => $helpitem,}
 4634:         );
 4635:     my $args = { bread_crumbs           => $brcrum,
 4636:                  bread_crumbs_component => 'User Management'};
 4637:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4638: 
 4639:     my $newrole;
 4640:     my ($rdummy,$roledef)=
 4641: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4642: 
 4643: # ------------------------------------------------------- Does this role exist?
 4644:     $r->print('<h3>');
 4645:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4646: 	$r->print(&mt('Existing Role').' "');
 4647:     } else {
 4648: 	$r->print(&mt('New Role').' "');
 4649: 	$roledef='';
 4650:         $newrole = 1;
 4651:     }
 4652:     $r->print($rolename.'"</h3>');
 4653: # ------------------------------------------------- Assign role and show result
 4654: 
 4655:     my $errmsg;
 4656:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4657:     # Assign role and return result
 4658:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4659:                                              $newprivs{'c'});
 4660:     if ($result ne 'ok') {
 4661:         $errmsg = ': '.$result;
 4662:     }
 4663:     my $message =
 4664:         &Apache::lonhtmlcommon::confirm_success(
 4665:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4666:     if ($env{'request.course.id'}) {
 4667:         my $url='/'.$env{'request.course.id'};
 4668:         $url=~s/\_/\//g;
 4669:         $result =
 4670:             &Apache::lonnet::assigncustomrole(
 4671:                 $env{'user.domain'},$env{'user.name'},
 4672:                 $url,
 4673:                 $env{'user.domain'},$env{'user.name'},
 4674:                 $rolename,undef,undef,undef,$context);
 4675:         if ($result ne 'ok') {
 4676:             $errmsg = ': '.$result;
 4677:         }
 4678:         $message .=
 4679:             '<br />'
 4680:            .&Apache::lonhtmlcommon::confirm_success(
 4681:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4682:     }
 4683:     $r->print(
 4684:         &Apache::loncommon::confirmwrapper($message)
 4685:        .'<br />'
 4686:        .&Apache::lonhtmlcommon::actionbox([
 4687:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4688:            .&mt('Create or edit another custom role')
 4689:            .'</a>'])
 4690:        .'<form name="customresult" method="post" action="">'
 4691:        .&Apache::lonhtmlcommon::echo_form_input([])
 4692:        .'</form>'
 4693:     );
 4694: }
 4695: 
 4696: # ================================================================ Main Handler
 4697: sub handler {
 4698:     my $r = shift;
 4699:     if ($r->header_only) {
 4700:        &Apache::loncommon::content_type($r,'text/html');
 4701:        $r->send_http_header;
 4702:        return OK;
 4703:     }
 4704:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 4705: 
 4706:     if ($env{'request.course.id'}) {
 4707:         $context = 'course';
 4708:         $crstype = &Apache::loncommon::course_type();
 4709:     } elsif ($env{'request.role'} =~ /^au\./) {
 4710:         $context = 'author';
 4711:     } else {
 4712:         $context = 'domain';
 4713:     }
 4714: 
 4715:     my ($permission,$allowed) =
 4716:         &Apache::lonuserutils::get_permission($context,$crstype);
 4717: 
 4718:     if ($allowed) {
 4719:         my @allhelp;
 4720:         if ($context eq 'course') {
 4721:             $cid = $env{'request.course.id'};
 4722:             $cdom = $env{'course.'.$cid.'.domain'};
 4723:             $cnum = $env{'course.'.$cid.'.num'};
 4724: 
 4725:             if ($permission->{'cusr'}) {
 4726:                 push(@allhelp,'Course_Create_Class_List');
 4727:             }
 4728:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4729:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 4730:             }
 4731:             if ($permission->{'custom'}) {
 4732:                 push(@allhelp,'Course_Editing_Custom_Roles');
 4733:             }
 4734:             if ($permission->{'cusr'}) {
 4735:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 4736:             }
 4737:             unless ($permission->{'cusr_section'}) {
 4738:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 4739:                     push(@allhelp,'Course_Automated_Enrollment');
 4740:                 }
 4741:                 if ($permission->{'selfenrolladmin'}) {
 4742:                     push(@allhelp,'Course_Approve_Selfenroll');
 4743:                 }
 4744:             }
 4745:             if ($permission->{'grp_manage'}) {
 4746:                 push(@allhelp,'Course_Manage_Group');
 4747:             }
 4748:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4749:                 push(@allhelp,'Course_User_Logs');
 4750:             }
 4751:         } elsif ($context eq 'author') {
 4752:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 4753:                            'Author_View_Coauthor_List','Author_User_Logs'));
 4754:         } else {
 4755:             if ($permission->{'cusr'}) {
 4756:                 push(@allhelp,'Domain_Change_Privileges');
 4757:                 if ($permission->{'activity'}) {
 4758:                     push(@allhelp,'Domain_User_Access_Logs');
 4759:                 }
 4760:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 4761:                 if ($permission->{'custom'}) {
 4762:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 4763:                 }
 4764:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 4765:             } elsif ($permission->{'view'}) {
 4766:                 push(@allhelp,'Domain_View_Privileges');
 4767:                 if ($permission->{'activity'}) {
 4768:                     push(@allhelp,'Domain_User_Access_Logs');
 4769:                 }
 4770:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 4771:             }
 4772:         }
 4773:         if (@allhelp) {
 4774:             $allhelpitems = join(',',@allhelp);
 4775:         }
 4776:     }
 4777: 
 4778:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4779:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4780:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4781:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4782:     my $args;
 4783:     my $brcrum = [];
 4784:     my $bread_crumbs_component = 'User Management';
 4785:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4786:         $brcrum = [{href=>"/adm/createuser",
 4787:                     text=>"User Management",
 4788:                     help=>$allhelpitems}
 4789:                   ];
 4790:     }
 4791:     if (!$allowed) {
 4792:         if ($context eq 'course') {
 4793:             $r->internal_redirect('/adm/viewclasslist');
 4794:             return OK;
 4795:         }
 4796:         $env{'user.error.msg'}=
 4797:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4798:                                  "or view user status.";
 4799:         return HTTP_NOT_ACCEPTABLE;
 4800:     }
 4801: 
 4802:     &Apache::loncommon::content_type($r,'text/html');
 4803:     $r->send_http_header;
 4804: 
 4805:     my $showcredits;
 4806:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4807:          ($context eq 'domain')) {
 4808:         my %domdefaults = 
 4809:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4810:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4811:             $showcredits = 1;
 4812:         }
 4813:     }
 4814: 
 4815:     # Main switch on form.action and form.state, as appropriate
 4816:     if (! exists($env{'form.action'})) {
 4817:         $args = {bread_crumbs => $brcrum,
 4818:                  bread_crumbs_component => $bread_crumbs_component}; 
 4819:         $r->print(&header(undef,$args));
 4820:         $r->print(&print_main_menu($permission,$context,$crstype));
 4821:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4822:         my $helpitem = 'Course_Create_Class_List';
 4823:         if ($context eq 'author') {
 4824:             $helpitem = 'Author_Create_Coauthor_List';
 4825:         } elsif ($context eq 'domain') {
 4826:             $helpitem = 'Domain_Create_Users';
 4827:         }
 4828:         push(@{$brcrum},
 4829:               { href => '/adm/createuser?action=upload&state=',
 4830:                 text => 'Upload Users List',
 4831:                 help => $helpitem,
 4832:               });
 4833:         $bread_crumbs_component = 'Upload Users List';
 4834:         $args = {bread_crumbs           => $brcrum,
 4835:                  bread_crumbs_component => $bread_crumbs_component};
 4836:         $r->print(&header(undef,$args));
 4837:         $r->print('<form name="studentform" method="post" '.
 4838:                   'enctype="multipart/form-data" '.
 4839:                   ' action="/adm/createuser">'."\n");
 4840:         if (! exists($env{'form.state'})) {
 4841:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4842:         } elsif ($env{'form.state'} eq 'got_file') {
 4843:             my $result = 
 4844:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 4845:                                                                  $permission,
 4846:                                                                  $crstype,$showcredits);
 4847:             if ($result eq 'missingdata') {
 4848:                 delete($env{'form.state'});
 4849:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4850:             }
 4851:         } elsif ($env{'form.state'} eq 'enrolling') {
 4852:             if ($env{'form.datatoken'}) {
 4853:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 4854:                                                                     $permission,
 4855:                                                                     $showcredits);
 4856:                 if ($result eq 'missingdata') {
 4857:                     delete($env{'form.state'});
 4858:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4859:                 } elsif ($result eq 'invalidhome') {
 4860:                     $env{'form.state'} = 'got_file';
 4861:                     delete($env{'form.lcserver'});
 4862:                     my $result =
 4863:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4864:                                                                          $crstype,$showcredits);
 4865:                     if ($result eq 'missingdata') {
 4866:                         delete($env{'form.state'});
 4867:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4868:                     }
 4869:                 }
 4870:             } else {
 4871:                 delete($env{'form.state'});
 4872:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4873:             }
 4874:         } else {
 4875:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4876:         }
 4877:         $r->print('</form>');
 4878:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4879:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4880:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4881:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4882:         my $phase = $env{'form.phase'};
 4883:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4884: 	&Apache::loncreateuser::restore_prev_selections();
 4885: 	my $srch;
 4886: 	foreach my $item (@search) {
 4887: 	    $srch->{$item} = $env{'form.'.$item};
 4888: 	}
 4889:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4890:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4891:             if ($env{'form.phase'} eq 'createnewuser') {
 4892:                 my $response;
 4893:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4894:                     my $response =
 4895:                         '<span class="LC_warning">'
 4896:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4897:                            .' letters numbers - . @')
 4898:                        .'</span>';
 4899:                     $env{'form.phase'} = '';
 4900:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4901:                                                $crstype,$brcrum,$permission);
 4902:                 } else {
 4903:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4904:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4905:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4906:                                                   $srch,$response,$context,
 4907:                                                   $permission,$crstype,$brcrum,
 4908:                                                   $showcredits);
 4909:                 }
 4910:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4911:                 my ($currstate,$response,$forcenewuser,$results) = 
 4912:                     &user_search_result($context,$srch);
 4913:                 if ($env{'form.currstate'} eq 'modify') {
 4914:                     $currstate = $env{'form.currstate'};
 4915:                 }
 4916:                 if ($currstate eq 'select') {
 4917:                     &print_user_selection_page($r,$response,$srch,$results,
 4918:                                                \@search,$context,undef,$crstype,
 4919:                                                $brcrum);
 4920:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4921:                     my ($ccuname,$ccdomain,$uhome);
 4922:                     if (($srch->{'srchby'} eq 'uname') && 
 4923:                         ($srch->{'srchtype'} eq 'exact')) {
 4924:                         $ccuname = $srch->{'srchterm'};
 4925:                         $ccdomain= $srch->{'srchdomain'};
 4926:                     } else {
 4927:                         my @matchedunames = keys(%{$results});
 4928:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4929:                     }
 4930:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4931:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4932:                     if ($env{'form.action'} eq 'accesslogs') {
 4933:                         my $uhome;
 4934:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4935:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4936:                         }
 4937:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4938:                             $env{'form.phase'} = '';
 4939:                             undef($forcenewuser);
 4940:                             #if ($response) {
 4941:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4942:                             #        $response .= '<br /><br />';
 4943:                             #    }
 4944:                             #}
 4945:                             &print_username_entry_form($r,$context,$response,$srch,
 4946:                                                        $forcenewuser,$crstype,$brcrum,
 4947:                                                        $permission);
 4948:                         } else {
 4949:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4950:                         }
 4951:                     } else {
 4952:                         if ($env{'form.forcenewuser'}) {
 4953:                             $response = '';
 4954:                         }
 4955:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4956:                                                       $srch,$response,$context,
 4957:                                                       $permission,$crstype,$brcrum);
 4958:                     }
 4959:                 } elsif ($currstate eq 'query') {
 4960:                     &print_user_query_page($r,'createuser',$brcrum);
 4961:                 } else {
 4962:                     $env{'form.phase'} = '';
 4963:                     &print_username_entry_form($r,$context,$response,$srch,
 4964:                                                $forcenewuser,$crstype,$brcrum,
 4965:                                                $permission);
 4966:                 }
 4967:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4968:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4969:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4970:                 if ($env{'form.action'} eq 'accesslogs') {
 4971:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4972:                 } else {
 4973:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4974:                                                   $context,$permission,$crstype,
 4975:                                                   $brcrum);
 4976:                 }
 4977:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4978:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4979:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4980:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4981:             }
 4982:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4983:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 4984:         } else {
 4985:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4986:                                        $brcrum,$permission);
 4987:         }
 4988:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4989:         my $prefix;
 4990:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4991:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 4992:         } else {
 4993:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4994:         }
 4995:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4996:              ($permission->{'cusr'}) && 
 4997:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4998:         push(@{$brcrum},
 4999:                  {href => '/adm/createuser?action=processauthorreq',
 5000:                   text => 'Authoring Space requests',
 5001:                   help => 'Domain_Role_Approvals'});
 5002:         $bread_crumbs_component = 'Authoring requests';
 5003:         if ($env{'form.state'} eq 'done') {
 5004:             push(@{$brcrum},
 5005:                      {href => '/adm/createuser?action=authorreqqueue',
 5006:                       text => 'Result',
 5007:                       help => 'Domain_Role_Approvals'});
 5008:             $bread_crumbs_component = 'Authoring request result';
 5009:         }
 5010:         $args = { bread_crumbs           => $brcrum,
 5011:                   bread_crumbs_component => $bread_crumbs_component};
 5012:         my $js = &usernamerequest_javascript();
 5013:         $r->print(&header(&add_script($js),$args));
 5014:         if (!exists($env{'form.state'})) {
 5015:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 5016:                                                                             $env{'request.role.domain'}));
 5017:         } elsif ($env{'form.state'} eq 'done') {
 5018:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 5019:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 5020:                                                                          $env{'request.role.domain'}));
 5021:         }
 5022:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 5023:              ($permission->{'cusr'}) &&
 5024:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5025:         push(@{$brcrum},
 5026:                  {href => '/adm/createuser?action=processusernamereq',
 5027:                   text => 'LON-CAPA account requests',
 5028:                   help => 'Domain_Username_Approvals'});
 5029:         $bread_crumbs_component = 'Account requests';
 5030:         if ($env{'form.state'} eq 'done') {
 5031:             push(@{$brcrum},
 5032:                      {href => '/adm/createuser?action=usernamereqqueue',
 5033:                       text => 'Result',
 5034:                       help => 'Domain_Username_Approvals'});
 5035:             $bread_crumbs_component = 'LON-CAPA account request result';
 5036:         }
 5037:         $args = { bread_crumbs           => $brcrum,
 5038:                   bread_crumbs_component => $bread_crumbs_component};
 5039:         my $js = &usernamerequest_javascript();
 5040:         $r->print(&header(&add_script($js),$args));
 5041:         if (!exists($env{'form.state'})) {
 5042:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 5043:                                                                             $env{'request.role.domain'}));
 5044:         } elsif ($env{'form.state'} eq 'done') {
 5045:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 5046:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 5047:                                                                          $env{'request.role.domain'}));
 5048:         }
 5049:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 5050:              ($permission->{'cusr'})) {
 5051:         my $dom = $env{'form.domain'};
 5052:         my $uname = $env{'form.username'};
 5053:         my $warning;
 5054:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 5055:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 5056:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 5057:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 5058:                     if ($uhome eq 'no_host') {
 5059:                         my $queue = $env{'form.queue'};
 5060:                         my $reqkey = &escape($uname).'_'.$queue; 
 5061:                         my $namespace = 'usernamequeue';
 5062:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 5063:                         my %queued =
 5064:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 5065:                         unless ($queued{$reqkey}) {
 5066:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 5067:                         }
 5068:                     } else {
 5069:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 5070:                     }
 5071:                 } else {
 5072:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 5073:                 }
 5074:             } else {
 5075:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 5076:             }
 5077:         } else {
 5078:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 5079:         }
 5080:         my $args = { only_body => 1 };
 5081:         $r->print(&header(undef,$args).
 5082:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 5083:         if ($warning ne '') {
 5084:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 5085:         } else {
 5086:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 5087:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 5088:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 5089:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 5090:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 5091:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 5092:                         my %info =
 5093:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 5094:                         if (ref($info{$uname}) eq 'HASH') {
 5095:                             my $usertype = $info{$uname}{'inststatus'};
 5096:                             unless ($usertype) {
 5097:                                 $usertype = 'default';
 5098:                             }
 5099:                             my ($showstatus,$showemail,$pickstart);
 5100:                             my $numextras = 0;
 5101:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5102:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 5103:                                 if (ref($usertypes) eq 'HASH') {
 5104:                                     if ($usertypes->{$usertype}) {
 5105:                                         $showstatus = $usertypes->{$usertype};
 5106:                                     } else {
 5107:                                         $showstatus = $othertitle;
 5108:                                     }
 5109:                                     if ($showstatus) {
 5110:                                         $numextras ++;
 5111:                                     }
 5112:                                 }
 5113:                             }
 5114:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 5115:                                 $showemail = $info{$uname}{'email'};
 5116:                                 $numextras ++;
 5117:                             }
 5118:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 5119:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 5120:                                     $pickstart = 1;
 5121:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5122:                                     my ($num,$count);
 5123:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 5124:                                     $count += $numextras;
 5125:                                     foreach my $field (@{$infofields}) {
 5126:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 5127:                                         next unless ($infotitles->{$field});
 5128:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 5129:                                                   $info{$uname}{$field});
 5130:                                         $num ++;
 5131:                                         unless ($count == $num) {
 5132:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 5133:                                         }
 5134:                                     }
 5135:                                 }
 5136:                             }
 5137:                             if ($numextras) {
 5138:                                 unless ($pickstart) {
 5139:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5140:                                     $pickstart = 1;
 5141:                                 }
 5142:                                 if ($showemail) {
 5143:                                     my $closure = '';
 5144:                                     unless ($showstatus) {
 5145:                                         $closure = 1;
 5146:                                     }
 5147:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 5148:                                               $showemail.
 5149:                                               &Apache::lonhtmlcommon::row_closure($closure));
 5150:                                 }
 5151:                                 if ($showstatus) {
 5152:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 5153:                                               $showstatus.
 5154:                                               &Apache::lonhtmlcommon::row_closure(1));
 5155:                                 }
 5156:                             }
 5157:                             if ($pickstart) { 
 5158:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 5159:                             } else {
 5160:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 5161:                             }
 5162:                         } else {
 5163:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 5164:                         }
 5165:                     }
 5166:                 }
 5167:             }
 5168:         }
 5169:         $r->print(&close_popup_form());
 5170:     } elsif (($env{'form.action'} eq 'listusers') && 
 5171:              ($permission->{'view'} || $permission->{'cusr'})) {
 5172:         my $helpitem = 'Course_View_Class_List';
 5173:         if ($context eq 'author') {
 5174:             $helpitem = 'Author_View_Coauthor_List';
 5175:         } elsif ($context eq 'domain') {
 5176:             $helpitem = 'Domain_View_Users_List';
 5177:         }
 5178:         if ($env{'form.phase'} eq 'bulkchange') {
 5179:             push(@{$brcrum},
 5180:                     {href => '/adm/createuser?action=listusers',
 5181:                      text => "List Users"},
 5182:                     {href => "/adm/createuser",
 5183:                      text => "Result",
 5184:                      help => $helpitem});
 5185:             $bread_crumbs_component = 'Update Users';
 5186:             $args = {bread_crumbs           => $brcrum,
 5187:                      bread_crumbs_component => $bread_crumbs_component};
 5188:             $r->print(&header(undef,$args));
 5189:             my $setting = $env{'form.roletype'};
 5190:             my $choice = $env{'form.bulkaction'};
 5191:             if ($permission->{'cusr'}) {
 5192:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 5193:             } else {
 5194:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 5195:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 5196:             }
 5197:         } else {
 5198:             push(@{$brcrum},
 5199:                     {href => '/adm/createuser?action=listusers',
 5200:                      text => "List Users",
 5201:                      help => $helpitem});
 5202:             $bread_crumbs_component = 'List Users';
 5203:             $args = {bread_crumbs           => $brcrum,
 5204:                      bread_crumbs_component => $bread_crumbs_component};
 5205:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5206:             my $formname = 'studentform';
 5207:             my $hidecall = "hide_searching();";
 5208:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5209:                 ($env{'form.roletype'} eq 'community'))) {
 5210:                 if ($env{'form.roletype'} eq 'course') {
 5211:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5212:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5213:                                                                 $formname);
 5214:                 } elsif ($env{'form.roletype'} eq 'community') {
 5215:                     $cb_jscript = 
 5216:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5217:                     my %elements = (
 5218:                                       coursepick => 'radio',
 5219:                                       coursetotal => 'text',
 5220:                                       courselist => 'text',
 5221:                                    );
 5222:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5223:                 }
 5224:                 $jscript .= &verify_user_display($context)."\n".
 5225:                             &Apache::loncommon::check_uncheck_jscript();
 5226:                 my $js = &add_script($jscript).$cb_jscript;
 5227:                 my $loadcode = 
 5228:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5229:                 if ($loadcode ne '') {
 5230:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5231:                 } else {
 5232:                     $args->{add_entries} = {onload => $hidecall};
 5233:                 }
 5234:                 $r->print(&header($js,$args));
 5235:             } else {
 5236:                 $args->{add_entries} = {onload => $hidecall};
 5237:                 $jscript = &verify_user_display($context).
 5238:                            &Apache::loncommon::check_uncheck_jscript(); 
 5239:                 $r->print(&header(&add_script($jscript),$args));
 5240:             }
 5241:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5242:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5243:                          $showcredits);
 5244:         }
 5245:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5246:         my $brtext;
 5247:         if ($crstype eq 'Community') {
 5248:             $brtext = 'Drop Members';
 5249:         } else {
 5250:             $brtext = 'Drop Students';
 5251:         }
 5252:         push(@{$brcrum},
 5253:                 {href => '/adm/createuser?action=drop',
 5254:                  text => $brtext,
 5255:                  help => 'Course_Drop_Student'});
 5256:         if ($env{'form.state'} eq 'done') {
 5257:             push(@{$brcrum},
 5258:                      {href=>'/adm/createuser?action=drop',
 5259:                       text=>"Result"});
 5260:         }
 5261:         $bread_crumbs_component = $brtext;
 5262:         $args = {bread_crumbs           => $brcrum,
 5263:                  bread_crumbs_component => $bread_crumbs_component}; 
 5264:         $r->print(&header(undef,$args));
 5265:         if (!exists($env{'form.state'})) {
 5266:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5267:         } elsif ($env{'form.state'} eq 'done') {
 5268:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5269:                                                     $env{'form.action'});
 5270:         }
 5271:     } elsif ($env{'form.action'} eq 'dateselect') {
 5272:         if ($permission->{'cusr'}) {
 5273:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5274:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5275:                                                                    $crstype,$showcredits));
 5276:         } else {
 5277:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5278:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5279:         }
 5280:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5281:         if ($permission->{selfenrolladmin}) {
 5282:             my %currsettings = (
 5283:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5284:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5285:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5286:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5287:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5288:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5289:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5290:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5291:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5292:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5293:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5294:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5295:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5296:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5297:             );
 5298:             push(@{$brcrum},
 5299:                     {href => '/adm/createuser?action=selfenroll',
 5300:                      text => "Configure Self-enrollment",
 5301:                      help => 'Course_Self_Enrollment'});
 5302:             if (!exists($env{'form.state'})) {
 5303:                 $args = { bread_crumbs           => $brcrum,
 5304:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5305:                 $r->print(&header(undef,$args));
 5306:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5307:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5308:             } elsif ($env{'form.state'} eq 'done') {
 5309:                 push (@{$brcrum},
 5310:                           {href=>'/adm/createuser?action=selfenroll',
 5311:                            text=>"Result"});
 5312:                 $args = { bread_crumbs           => $brcrum,
 5313:                           bread_crumbs_component => 'Self-enrollment result'};
 5314:                 $r->print(&header(undef,$args));
 5315:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5316:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5317:             }
 5318:         } else {
 5319:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5320:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5321:         }
 5322:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5323:         if ($permission->{selfenrolladmin}) {
 5324:             push(@{$brcrum},
 5325:                      {href => '/adm/createuser?action=selfenrollqueue',
 5326:                       text => 'Enrollment requests',
 5327:                       help => 'Course_Approve_Selfenroll'});
 5328:             $bread_crumbs_component = 'Enrollment requests';
 5329:             if ($env{'form.state'} eq 'done') {
 5330:                 push(@{$brcrum},
 5331:                          {href => '/adm/createuser?action=selfenrollqueue',
 5332:                           text => 'Result',
 5333:                           help => 'Course_Approve_Selfenroll'});
 5334:                 $bread_crumbs_component = 'Enrollment result';
 5335:             }
 5336:             $args = { bread_crumbs           => $brcrum,
 5337:                       bread_crumbs_component => $bread_crumbs_component};
 5338:             $r->print(&header(undef,$args));
 5339:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5340:             if (!exists($env{'form.state'})) {
 5341:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5342:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5343:                                                                                 $cdom,$cnum));
 5344:             } elsif ($env{'form.state'} eq 'done') {
 5345:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5346:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5347:                               $cdom,$cnum,$coursedesc));
 5348:             }
 5349:         } else {
 5350:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5351:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5352:         }
 5353:     } elsif ($env{'form.action'} eq 'changelogs') {
 5354:         if ($permission->{cusr} || $permission->{view}) {
 5355:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5356:         } else {
 5357:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5358:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5359:         }
 5360:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5361:         if (($permission->{'owner'}) || ($permission->{'co-owner'})) {
 5362:             if ($env{'form.state'} eq 'process') {
 5363:                 if ($permission->{'owner'}) {
 5364:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5365:                 } else {
 5366:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5367:                 }
 5368:             } else {
 5369:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5370:             }
 5371:         } else {
 5372:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5373:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5374:         }
 5375:     } else {
 5376:         $bread_crumbs_component = 'User Management';
 5377:         $args = { bread_crumbs           => $brcrum,
 5378:                   bread_crumbs_component => $bread_crumbs_component};
 5379:         $r->print(&header(undef,$args));
 5380:         $r->print(&print_main_menu($permission,$context,$crstype));
 5381:     }
 5382:     $r->print(&Apache::loncommon::end_page());
 5383:     return OK;
 5384: }
 5385: 
 5386: sub header {
 5387:     my ($jscript,$args) = @_;
 5388:     my $start_page;
 5389:     if (ref($args) eq 'HASH') {
 5390:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5391:     } else {
 5392:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5393:     }
 5394:     return $start_page;
 5395: }
 5396: 
 5397: sub add_script {
 5398:     my ($js) = @_;
 5399:     return '<script type="text/javascript">'."\n"
 5400:           .'// <![CDATA['."\n"
 5401:           .$js."\n"
 5402:           .'// ]]>'."\n"
 5403:           .'</script>'."\n";
 5404: }
 5405: 
 5406: sub usernamerequest_javascript {
 5407:     my $js = <<ENDJS;
 5408: 
 5409: function openusernamereqdisplay(dom,uname,queue) {
 5410:     var url = '/adm/createuser?action=displayuserreq';
 5411:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5412:     var title = 'Account_Request_Browser';
 5413:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5414:     options += ',width=700,height=600';
 5415:     var stdeditbrowser = open(url,title,options,'1');
 5416:     stdeditbrowser.focus();
 5417:     return;
 5418: }
 5419:  
 5420: ENDJS
 5421: }
 5422: 
 5423: sub close_popup_form {
 5424:     my $close= &mt('Close Window');
 5425:     return << "END";
 5426: <p><form name="displayreq" action="" method="post">
 5427: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5428: </form></p>
 5429: END
 5430: }
 5431: 
 5432: sub verify_user_display {
 5433:     my ($context) = @_;
 5434:     my %lt = &Apache::lonlocal::texthash (
 5435:         course    => 'course(s): description, section(s), status',
 5436:         community => 'community(s): description, section(s), status',
 5437:         author    => 'author',
 5438:     );
 5439:     my $photos;
 5440:     if (($context eq 'course') && $env{'request.course.id'}) {
 5441:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5442:     }
 5443:     my $output = <<"END";
 5444: 
 5445: function hide_searching() {
 5446:     if (document.getElementById('searching')) {
 5447:         document.getElementById('searching').style.display = 'none';
 5448:     }
 5449:     return;
 5450: }
 5451: 
 5452: function display_update() {
 5453:     document.studentform.action.value = 'listusers';
 5454:     document.studentform.phase.value = 'display';
 5455:     document.studentform.submit();
 5456: }
 5457: 
 5458: function updateCols(caller) {
 5459:     var context = '$context';
 5460:     var photos = '$photos';
 5461:     if (caller == 'Status') {
 5462:         if ((context == 'domain') && 
 5463:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5464:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5465:             document.getElementById('showcolstatus').checked = false;
 5466:             document.getElementById('showcolstatus').disabled = 'disabled';
 5467:             document.getElementById('showcolstart').checked = false;
 5468:             document.getElementById('showcolend').checked = false;
 5469:         } else {
 5470:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5471:                 document.getElementById('showcolstatus').checked = true;
 5472:                 document.getElementById('showcolstatus').disabled = '';
 5473:                 document.getElementById('showcolstart').checked = true;
 5474:                 document.getElementById('showcolend').checked = true;
 5475:             } else {
 5476:                 document.getElementById('showcolstatus').checked = false;
 5477:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5478:                 document.getElementById('showcolstart').checked = false;
 5479:                 document.getElementById('showcolend').checked = false;
 5480:             }
 5481:         }
 5482:     }
 5483:     if (caller == 'output') {
 5484:         if (photos == 1) {
 5485:             if (document.getElementById('showcolphoto')) {
 5486:                 var photoitem = document.getElementById('showcolphoto');
 5487:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5488:                     photoitem.checked = true;
 5489:                     photoitem.disabled = '';
 5490:                 } else {
 5491:                     photoitem.checked = false;
 5492:                     photoitem.disabled = 'disabled';
 5493:                 }
 5494:             }
 5495:         }
 5496:     }
 5497:     if (caller == 'showrole') {
 5498:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5499:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5500:             document.getElementById('showcolrole').checked = true;
 5501:             document.getElementById('showcolrole').disabled = '';
 5502:         } else {
 5503:             document.getElementById('showcolrole').checked = false;
 5504:             document.getElementById('showcolrole').disabled = 'disabled';
 5505:         }
 5506:         if (context == 'domain') {
 5507:             var quotausageshow = 0;
 5508:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5509:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5510:                 document.getElementById('showcolstatus').checked = false;
 5511:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5512:                 document.getElementById('showcolstart').checked = false;
 5513:                 document.getElementById('showcolend').checked = false;
 5514:             } else {
 5515:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5516:                     document.getElementById('showcolstatus').checked = true;
 5517:                     document.getElementById('showcolstatus').disabled = '';
 5518:                     document.getElementById('showcolstart').checked = true;
 5519:                     document.getElementById('showcolend').checked = true;
 5520:                 }
 5521:             }
 5522:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5523:                 document.getElementById('showcolextent').disabled = 'disabled';
 5524:                 document.getElementById('showcolextent').checked = 'false';
 5525:                 document.getElementById('showextent').style.display='none';
 5526:                 document.getElementById('showcoltextextent').innerHTML = '';
 5527:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5528:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5529:                     if (document.getElementById('showcolauthorusage')) {
 5530:                         document.getElementById('showcolauthorusage').disabled = '';
 5531:                     }
 5532:                     if (document.getElementById('showcolauthorquota')) {
 5533:                         document.getElementById('showcolauthorquota').disabled = '';
 5534:                     }
 5535:                     quotausageshow = 1;
 5536:                 }
 5537:             } else {
 5538:                 document.getElementById('showextent').style.display='block';
 5539:                 document.getElementById('showextent').style.textAlign='left';
 5540:                 document.getElementById('showextent').style.textFace='normal';
 5541:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5542:                     document.getElementById('showcolextent').disabled = '';
 5543:                     document.getElementById('showcolextent').checked = 'true';
 5544:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5545:                 } else {
 5546:                     document.getElementById('showcolextent').disabled = '';
 5547:                     document.getElementById('showcolextent').checked = 'true';
 5548:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5549:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5550:                     } else {
 5551:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5552:                     }
 5553:                 }
 5554:             }
 5555:             if (quotausageshow == 0)  {
 5556:                 if (document.getElementById('showcolauthorusage')) {
 5557:                     document.getElementById('showcolauthorusage').checked = false;
 5558:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5559:                 }
 5560:                 if (document.getElementById('showcolauthorquota')) {
 5561:                     document.getElementById('showcolauthorquota').checked = false;
 5562:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5563:                 }
 5564:             }
 5565:         }
 5566:     }
 5567:     return;
 5568: }
 5569: 
 5570: END
 5571:     return $output;
 5572: 
 5573: }
 5574: 
 5575: ###############################################################
 5576: ###############################################################
 5577: #  Menu Phase One
 5578: sub print_main_menu {
 5579:     my ($permission,$context,$crstype) = @_;
 5580:     my $linkcontext = $context;
 5581:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5582:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5583:         $linkcontext = lc($crstype);
 5584:         $stuterm = 'Members';
 5585:     }
 5586:     my %links = (
 5587:                 domain => {
 5588:                             upload     => 'Upload a File of Users',
 5589:                             singleuser => 'Add/Modify a User',
 5590:                             listusers  => 'Manage Users',
 5591:                             },
 5592:                 author => {
 5593:                             upload     => 'Upload a File of Co-authors',
 5594:                             singleuser => 'Add/Modify a Co-author',
 5595:                             listusers  => 'Manage Co-authors',
 5596:                             },
 5597:                 course => {
 5598:                             upload     => 'Upload a File of Course Users',
 5599:                             singleuser => 'Add/Modify a Course User',
 5600:                             listusers  => 'List and Modify Multiple Course Users',
 5601:                             },
 5602:                 community => {
 5603:                             upload     => 'Upload a File of Community Users',
 5604:                             singleuser => 'Add/Modify a Community User',
 5605:                             listusers  => 'List and Modify Multiple Community Users',
 5606:                            },
 5607:                 );
 5608:      my %linktitles = (
 5609:                 domain => {
 5610:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5611:                             listusers  => 'Show and manage users in this domain.',
 5612:                             },
 5613:                 author => {
 5614:                             singleuser => 'Add a user with a co- or assistant author role.',
 5615:                             listusers  => 'Show and manage co- or assistant authors.',
 5616:                             },
 5617:                 course => {
 5618:                             singleuser => 'Add a user with a certain role to this course.',
 5619:                             listusers  => 'Show and manage users in this course.',
 5620:                             },
 5621:                 community => {
 5622:                             singleuser => 'Add a user with a certain role to this community.',
 5623:                             listusers  => 'Show and manage users in this community.',
 5624:                            },
 5625:                 );
 5626:   if ($linkcontext eq 'domain') {
 5627:       unless ($permission->{'cusr'}) {
 5628:           $links{'domain'}{'singleuser'} = 'View a User';
 5629:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5630:       }
 5631:   } elsif ($linkcontext eq 'course') {
 5632:       unless ($permission->{'cusr'}) {
 5633:           $links{'course'}{'singleuser'} = 'View a Course User';
 5634:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5635:           $links{'course'}{'listusers'} = 'List Course Users';
 5636:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5637:       }
 5638:   } elsif ($linkcontext eq 'community') {
 5639:       unless ($permission->{'cusr'}) {
 5640:           $links{'community'}{'singleuser'} = 'View a Community User';
 5641:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5642:           $links{'community'}{'listusers'} = 'List Community Users';
 5643:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5644:       }
 5645:   }
 5646:   my @menu = ( {categorytitle => 'Single Users', 
 5647:          items =>
 5648:          [
 5649:             {
 5650:              linktext => $links{$linkcontext}{'singleuser'},
 5651:              icon => 'edit-redo.png',
 5652:              #help => 'Course_Change_Privileges',
 5653:              url => '/adm/createuser?action=singleuser',
 5654:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5655:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5656:             },
 5657:          ]},
 5658: 
 5659:          {categorytitle => 'Multiple Users',
 5660:          items => 
 5661:          [
 5662:             {
 5663:              linktext => $links{$linkcontext}{'upload'},
 5664:              icon => 'uplusr.png',
 5665:              #help => 'Course_Create_Class_List',
 5666:              url => '/adm/createuser?action=upload',
 5667:              permission => $permission->{'cusr'},
 5668:              linktitle => 'Upload a CSV or a text file containing users.',
 5669:             },
 5670:             {
 5671:              linktext => $links{$linkcontext}{'listusers'},
 5672:              icon => 'mngcu.png',
 5673:              #help => 'Course_View_Class_List',
 5674:              url => '/adm/createuser?action=listusers',
 5675:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5676:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5677:             },
 5678: 
 5679:          ]},
 5680: 
 5681:          {categorytitle => 'Administration',
 5682:          items => [ ]},
 5683:        );
 5684: 
 5685:     if ($context eq 'domain'){
 5686:         push(@{  $menu[0]->{items} }, # Single Users
 5687:             {
 5688:              linktext => 'User Access Log',
 5689:              icon => 'document-properties.png',
 5690:              #help => 'Domain_User_Access_Logs',
 5691:              url => '/adm/createuser?action=accesslogs',
 5692:              permission => $permission->{'activity'},
 5693:              linktitle => 'View user access log.',
 5694:             }
 5695:         );
 5696:         
 5697:         push(@{ $menu[2]->{items} }, #Category: Administration
 5698:             {
 5699:              linktext => 'Custom Roles',
 5700:              icon => 'emblem-photos.png',
 5701:              #help => 'Course_Editing_Custom_Roles',
 5702:              url => '/adm/createuser?action=custom',
 5703:              permission => $permission->{'custom'},
 5704:              linktitle => 'Configure a custom role.',
 5705:             },
 5706:             {
 5707:              linktext => 'Authoring Space Requests',
 5708:              icon => 'selfenrl-queue.png',
 5709:              #help => 'Domain_Role_Approvals',
 5710:              url => '/adm/createuser?action=processauthorreq',
 5711:              permission => $permission->{'cusr'},
 5712:              linktitle => 'Approve or reject author role requests',
 5713:             },
 5714:             {
 5715:              linktext => 'LON-CAPA Account Requests',
 5716:              icon => 'list-add.png',
 5717:              #help => 'Domain_Username_Approvals',
 5718:              url => '/adm/createuser?action=processusernamereq',
 5719:              permission => $permission->{'cusr'},
 5720:              linktitle => 'Approve or reject LON-CAPA account requests',
 5721:             },
 5722:             {
 5723:              linktext => 'Change Log',
 5724:              icon => 'document-properties.png',
 5725:              #help => 'Course_User_Logs',
 5726:              url => '/adm/createuser?action=changelogs',
 5727:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5728:              linktitle => 'View change log.',
 5729:             },
 5730:         );
 5731:         
 5732:     }elsif ($context eq 'course'){
 5733:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5734: 
 5735:         my %linktext = (
 5736:                          'Course'    => {
 5737:                                           single => 'Add/Modify a Student', 
 5738:                                           drop   => 'Drop Students',
 5739:                                           groups => 'Course Groups',
 5740:                                         },
 5741:                          'Community' => {
 5742:                                           single => 'Add/Modify a Member', 
 5743:                                           drop   => 'Drop Members',
 5744:                                           groups => 'Community Groups',
 5745:                                         },
 5746:                        );
 5747:         $linktext{'Placement'} = $linktext{'Course'};
 5748: 
 5749:         my %linktitle = (
 5750:             'Course' => {
 5751:                   single => 'Add a user with the role of student to this course',
 5752:                   drop   => 'Remove a student from this course.',
 5753:                   groups => 'Manage course groups',
 5754:                         },
 5755:             'Community' => {
 5756:                   single => 'Add a user with the role of member to this community',
 5757:                   drop   => 'Remove a member from this community.',
 5758:                   groups => 'Manage community groups',
 5759:                            },
 5760:         );
 5761: 
 5762:         $linktitle{'Placement'} = $linktitle{'Course'};
 5763: 
 5764:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5765:             {   
 5766:              linktext => $linktext{$crstype}{'single'},
 5767:              #help => 'Course_Add_Student',
 5768:              icon => 'list-add.png',
 5769:              url => '/adm/createuser?action=singlestudent',
 5770:              permission => $permission->{'cusr'},
 5771:              linktitle => $linktitle{$crstype}{'single'},
 5772:             },
 5773:         );
 5774:         
 5775:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5776:             {
 5777:              linktext => $linktext{$crstype}{'drop'},
 5778:              icon => 'edit-undo.png',
 5779:              #help => 'Course_Drop_Student',
 5780:              url => '/adm/createuser?action=drop',
 5781:              permission => $permission->{'cusr'},
 5782:              linktitle => $linktitle{$crstype}{'drop'},
 5783:             },
 5784:         );
 5785:         push(@{ $menu[2]->{items} }, #Category: Administration
 5786:             {
 5787:              linktext => 'Helpdesk Access',
 5788:              icon => 'helpdesk-access.png',
 5789:              #help => 'Course_Helpdesk_Access',
 5790:              url => '/adm/createuser?action=helpdesk',
 5791:              permission => ($permission->{'owner'} || $permission->{'co-owner'}),
 5792:              linktitle => 'Helpdesk access options',
 5793:             },
 5794:             {
 5795:              linktext => 'Custom Roles',
 5796:              icon => 'emblem-photos.png',
 5797:              #help => 'Course_Editing_Custom_Roles',
 5798:              url => '/adm/createuser?action=custom',
 5799:              permission => $permission->{'custom'},
 5800:              linktitle => 'Configure a custom role.',
 5801:             },
 5802:             {
 5803:              linktext => $linktext{$crstype}{'groups'},
 5804:              icon => 'grps.png',
 5805:              #help => 'Course_Manage_Group',
 5806:              url => '/adm/coursegroups?refpage=cusr',
 5807:              permission => $permission->{'grp_manage'},
 5808:              linktitle => $linktitle{$crstype}{'groups'},
 5809:             },
 5810:             {
 5811:              linktext => 'Change Log',
 5812:              icon => 'document-properties.png',
 5813:              #help => 'Course_User_Logs',
 5814:              url => '/adm/createuser?action=changelogs',
 5815:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5816:              linktitle => 'View change log.',
 5817:             },
 5818:         );
 5819:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5820:             push(@{ $menu[2]->{items} },
 5821:                     {
 5822:                      linktext => 'Enrollment Requests',
 5823:                      icon => 'selfenrl-queue.png',
 5824:                      #help => 'Course_Approve_Selfenroll',
 5825:                      url => '/adm/createuser?action=selfenrollqueue',
 5826:                      permission => $permission->{'selfenrolladmin'},
 5827:                      linktitle =>'Approve or reject enrollment requests.',
 5828:                     },
 5829:             );
 5830:         }
 5831:         
 5832:         if (!exists($permission->{'cusr_section'})){
 5833:             if ($crstype ne 'Community') {
 5834:                 push(@{ $menu[2]->{items} },
 5835:                     {
 5836:                      linktext => 'Automated Enrollment',
 5837:                      icon => 'roles.png',
 5838:                      #help => 'Course_Automated_Enrollment',
 5839:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5840:                                          && (($permission->{'cusr'}) ||
 5841:                                              ($permission->{'view'}))),
 5842:                      url  => '/adm/populate',
 5843:                      linktitle => 'Automated enrollment manager.',
 5844:                     }
 5845:                 );
 5846:             }
 5847:             push(@{ $menu[2]->{items} }, 
 5848:                 {
 5849:                  linktext => 'User Self-Enrollment',
 5850:                  icon => 'self_enroll.png',
 5851:                  #help => 'Course_Self_Enrollment',
 5852:                  url => '/adm/createuser?action=selfenroll',
 5853:                  permission => $permission->{'selfenrolladmin'},
 5854:                  linktitle => 'Configure user self-enrollment.',
 5855:                 },
 5856:             );
 5857:         }
 5858:     } elsif ($context eq 'author') {
 5859:         push(@{ $menu[2]->{items} }, #Category: Administration
 5860:             {
 5861:              linktext => 'Change Log',
 5862:              icon => 'document-properties.png',
 5863:              #help => 'Course_User_Logs',
 5864:              url => '/adm/createuser?action=changelogs',
 5865:              permission => $permission->{'cusr'},
 5866:              linktitle => 'View change log.',
 5867:             },
 5868:         );
 5869:     }
 5870:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5871: #               { text => 'View Log-in History',
 5872: #                 help => 'Course_User_Logins',
 5873: #                 action => 'logins',
 5874: #                 permission => $permission->{'cusr'},
 5875: #               });
 5876: }
 5877: 
 5878: sub restore_prev_selections {
 5879:     my %saveable_parameters = ('srchby'   => 'scalar',
 5880: 			       'srchin'   => 'scalar',
 5881: 			       'srchtype' => 'scalar',
 5882: 			       );
 5883:     &Apache::loncommon::store_settings('user','user_picker',
 5884: 				       \%saveable_parameters);
 5885:     &Apache::loncommon::restore_settings('user','user_picker',
 5886: 					 \%saveable_parameters);
 5887: }
 5888: 
 5889: sub print_selfenroll_menu {
 5890:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5891:     my $crstype = &Apache::loncommon::course_type();
 5892:     my $formname = 'selfenroll';
 5893:     my $nolink = 1;
 5894:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5895:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5896:     my $setsec_js = 
 5897:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5898:     my %alerts = &Apache::lonlocal::texthash(
 5899:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5900:         butn => 'but no user types have been checked.',
 5901:         wilf => "Please uncheck 'activate' or check at least one type.",
 5902:     );
 5903:     my $disabled;
 5904:     if ($readonly) {
 5905:        $disabled = ' disabled="disabled"';
 5906:     }
 5907:     &js_escape(\%alerts);
 5908:     my $selfenroll_js = <<"ENDSCRIPT";
 5909: function update_types(caller,num) {
 5910:     var delidx = getIndexByName('selfenroll_delete');
 5911:     var actidx = getIndexByName('selfenroll_activate');
 5912:     if (caller == 'selfenroll_all') {
 5913:         var selall;
 5914:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5915:             if (document.$formname.selfenroll_all[i].checked) {
 5916:                 selall = document.$formname.selfenroll_all[i].value;
 5917:             }
 5918:         }
 5919:         if (selall == 1) {
 5920:             if (delidx != -1) {
 5921:                 if (document.$formname.selfenroll_delete.length) {
 5922:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5923:                         document.$formname.selfenroll_delete[j].checked = true;
 5924:                     }
 5925:                 } else {
 5926:                     document.$formname.elements[delidx].checked = true;
 5927:                 }
 5928:             }
 5929:             if (actidx != -1) {
 5930:                 if (document.$formname.selfenroll_activate.length) {
 5931:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5932:                         document.$formname.selfenroll_activate[j].checked = false;
 5933:                     }
 5934:                 } else {
 5935:                     document.$formname.elements[actidx].checked = false;
 5936:                 }
 5937:             }
 5938:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5939:         }
 5940:     }
 5941:     if (caller == 'selfenroll_activate') {
 5942:         if (document.$formname.selfenroll_activate.length) {
 5943:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5944:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5945:                     if (document.$formname.selfenroll_activate[j].checked) {
 5946:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5947:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5948:                                 document.$formname.selfenroll_all[i].checked = false;
 5949:                             }
 5950:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5951:                                 document.$formname.selfenroll_all[i].checked = true;
 5952:                             }
 5953:                         }
 5954:                     }
 5955:                 }
 5956:             }
 5957:         } else {
 5958:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5959:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5960:                     document.$formname.selfenroll_all[i].checked = false;
 5961:                 }
 5962:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5963:                     document.$formname.selfenroll_all[i].checked = true;
 5964:                 }
 5965:             }
 5966:         }
 5967:     }
 5968:     if (caller == 'selfenroll_delete') {
 5969:         if (document.$formname.selfenroll_delete.length) {
 5970:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5971:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5972:                     if (document.$formname.selfenroll_delete[j].checked) {
 5973:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5974:                         if (delindex != -1) { 
 5975:                             if (document.$formname.elements[delindex].length) {
 5976:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5977:                                     document.$formname.elements[delindex][k].checked = false;
 5978:                                 }
 5979:                             } else {
 5980:                                 document.$formname.elements[delindex].checked = false;
 5981:                             }
 5982:                         }
 5983:                     }
 5984:                 }
 5985:             }
 5986:         } else {
 5987:             if (document.$formname.selfenroll_delete.checked) {
 5988:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5989:                 if (delindex != -1) {
 5990:                     if (document.$formname.elements[delindex].length) {
 5991:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5992:                             document.$formname.elements[delindex][k].checked = false;
 5993:                         }
 5994:                     } else {
 5995:                         document.$formname.elements[delindex].checked = false;
 5996:                     }
 5997:                 }
 5998:             }
 5999:         }
 6000:     }
 6001:     return;
 6002: }
 6003: 
 6004: function validate_types(form) {
 6005:     var needaction = new Array();
 6006:     var countfail = 0;
 6007:     var actidx = getIndexByName('selfenroll_activate');
 6008:     if (actidx != -1) {
 6009:         if (document.$formname.selfenroll_activate.length) {
 6010:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 6011:                 var num = document.$formname.selfenroll_activate[j].value;
 6012:                 if (document.$formname.selfenroll_activate[j].checked) {
 6013:                     countfail = check_types(num,countfail,needaction)
 6014:                 }
 6015:             }
 6016:         } else {
 6017:             if (document.$formname.selfenroll_activate.checked) {
 6018:                 var num = document.$formname.selfenroll_activate.value;
 6019:                 countfail = check_types(num,countfail,needaction)
 6020:             }
 6021:         }
 6022:     }
 6023:     if (countfail > 0) {
 6024:         var msg = "$alerts{'acto'}\\n";
 6025:         var loopend = needaction.length -1;
 6026:         if (loopend > 0) {
 6027:             for (var m=0; m<loopend; m++) {
 6028:                 msg += needaction[m]+", ";
 6029:             }
 6030:         }
 6031:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 6032:         alert(msg);
 6033:         return; 
 6034:     }
 6035:     setSections(form);
 6036: }
 6037: 
 6038: function check_types(num,countfail,needaction) {
 6039:     var boxname = 'selfenroll_types_'+num;
 6040:     var typeidx = getIndexByName(boxname);
 6041:     var count = 0;
 6042:     if (typeidx != -1) {
 6043:         if (document.$formname.elements[boxname].length) {
 6044:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 6045:                 if (document.$formname.elements[boxname][k].checked) {
 6046:                     count ++;
 6047:                 }
 6048:             }
 6049:         } else {
 6050:             if (document.$formname.elements[typeidx].checked) {
 6051:                 count ++;
 6052:             }
 6053:         }
 6054:         if (count == 0) {
 6055:             var domidx = getIndexByName('selfenroll_dom_'+num);
 6056:             if (domidx != -1) {
 6057:                 var domname = document.$formname.elements[domidx].value;
 6058:                 needaction[countfail] = domname;
 6059:                 countfail ++;
 6060:             }
 6061:         }
 6062:     }
 6063:     return countfail;
 6064: }
 6065: 
 6066: function toggleNotify() {
 6067:     var selfenrollApproval = 0;
 6068:     if (document.$formname.selfenroll_approval.length) {
 6069:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 6070:             if (document.$formname.selfenroll_approval[i].checked) {
 6071:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 6072:                 break;        
 6073:             }
 6074:         }
 6075:     }
 6076:     if (document.getElementById('notified')) {
 6077:         if (selfenrollApproval == 0) {
 6078:             document.getElementById('notified').style.display='none';
 6079:         } else {
 6080:             document.getElementById('notified').style.display='block';
 6081:         }
 6082:     }
 6083:     return;
 6084: }
 6085: 
 6086: function getIndexByName(item) {
 6087:     for (var i=0;i<document.$formname.elements.length;i++) {
 6088:         if (document.$formname.elements[i].name == item) {
 6089:             return i;
 6090:         }
 6091:     }
 6092:     return -1;
 6093: }
 6094: ENDSCRIPT
 6095: 
 6096:     my $output = '<script type="text/javascript">'."\n".
 6097:                  '// <![CDATA['."\n".
 6098:                  $setsec_js."\n".$selfenroll_js."\n".
 6099:                  '// ]]>'."\n".
 6100:                  '</script>'."\n".
 6101:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 6102:  
 6103:     my $visactions = &cat_visibility();
 6104:     my ($cathash,%cattype);
 6105:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 6106:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 6107:         $cathash = $domconfig{'coursecategories'}{'cats'};
 6108:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 6109:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 6110:         if ($cattype{'auth'} eq '') {
 6111:             $cattype{'auth'} = 'std';
 6112:         }
 6113:         if ($cattype{'unauth'} eq '') {
 6114:             $cattype{'unauth'} = 'std';
 6115:         }
 6116:     } else {
 6117:         $cathash = {};
 6118:         $cattype{'auth'} = 'std';
 6119:         $cattype{'unauth'} = 'std';
 6120:     }
 6121:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 6122:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6123:                   '<br />'.
 6124:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6125:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 6126:                   '</ul>');
 6127:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 6128:         if ($currsettings->{'uniquecode'}) {
 6129:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 6130:         } else {
 6131:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6132:                   '<br />'.
 6133:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6134:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 6135:                   '</ul><br />');
 6136:         }
 6137:     } else {
 6138:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 6139:         if (ref($visactions) eq 'HASH') {
 6140:             if ($visible) {
 6141:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 6142:            } else {
 6143:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 6144:                           .$visactions->{'yous'}.
 6145:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 6146:                 if (ref($vismsgs) eq 'ARRAY') {
 6147:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 6148:                     foreach my $item (@{$vismsgs}) {
 6149:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 6150:                     }
 6151:                     $output .= '</ul>';
 6152:                 }
 6153:                 $output .= '</p>';
 6154:             }
 6155:         }
 6156:     }
 6157:     my $actionhref = '/adm/createuser';
 6158:     if ($context eq 'domain') {
 6159:         $actionhref = '/adm/modifycourse';
 6160:     }
 6161: 
 6162:     my %noedit;
 6163:     unless ($context eq 'domain') {
 6164:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 6165:     }
 6166:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 6167:                &Apache::lonhtmlcommon::start_pick_box();
 6168:     if (ref($row) eq 'ARRAY') {
 6169:         foreach my $item (@{$row}) {
 6170:             my $title = $item; 
 6171:             if (ref($lt) eq 'HASH') {
 6172:                 $title = $lt->{$item};
 6173:             }
 6174:             $output .= &Apache::lonhtmlcommon::row_title($title);
 6175:             if ($item eq 'types') {
 6176:                 my $curr_types;
 6177:                 if (ref($currsettings) eq 'HASH') {
 6178:                     $curr_types = $currsettings->{'selfenroll_types'};
 6179:                 }
 6180:                 if ($noedit{$item}) {
 6181:                     if ($curr_types eq '*') {
 6182:                         $output .= &mt('Any user in any domain');   
 6183:                     } else {
 6184:                         my @entries = split(/;/,$curr_types);
 6185:                         if (@entries > 0) {
 6186:                             $output .= '<ul>'; 
 6187:                             foreach my $entry (@entries) {
 6188:                                 my ($currdom,$typestr) = split(/:/,$entry);
 6189:                                 next if ($typestr eq '');
 6190:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 6191:                                 my @currinsttypes = split(',',$typestr);
 6192:                                 my ($othertitle,$usertypes,$types) = 
 6193:                                     &Apache::loncommon::sorted_inst_types($currdom);
 6194:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6195:                                     $usertypes->{'any'} = &mt('any user'); 
 6196:                                     if (keys(%{$usertypes}) > 0) {
 6197:                                         $usertypes->{'other'} = &mt('other users');
 6198:                                     }
 6199:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 6200:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 6201:                                  }
 6202:                             }
 6203:                             $output .= '</ul>';
 6204:                         } else {
 6205:                             $output .= &mt('None');
 6206:                         }
 6207:                     }
 6208:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6209:                     next;
 6210:                 }
 6211:                 my $showdomdesc = 1;
 6212:                 my $includeempty = 1;
 6213:                 my $num = 0;
 6214:                 $output .= &Apache::loncommon::start_data_table().
 6215:                            &Apache::loncommon::start_data_table_row()
 6216:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6217:                            .&mt('Any user in any domain:')
 6218:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6219:                 if ($curr_types eq '*') {
 6220:                     $output .= ' checked="checked" '; 
 6221:                 }
 6222:                 $output .= 'onchange="javascript:update_types('.
 6223:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6224:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6225:                 if ($curr_types ne '*') {
 6226:                     $output .= ' checked="checked" ';
 6227:                 }
 6228:                 $output .= ' onchange="javascript:update_types('.
 6229:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6230:                            &Apache::loncommon::end_data_table_row().
 6231:                            &Apache::loncommon::end_data_table().
 6232:                            &mt('Or').'<br />'.
 6233:                            &Apache::loncommon::start_data_table();
 6234:                 my %currdoms;
 6235:                 if ($curr_types eq '') {
 6236:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6237:                 } elsif ($curr_types ne '*') {
 6238:                     my @entries = split(/;/,$curr_types);
 6239:                     if (@entries > 0) {
 6240:                         foreach my $entry (@entries) {
 6241:                             my ($currdom,$typestr) = split(/:/,$entry);
 6242:                             $currdoms{$currdom} = 1;
 6243:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6244:                             my @currinsttypes = split(',',$typestr);
 6245:                             $output .= &Apache::loncommon::start_data_table_row()
 6246:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6247:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6248:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6249:                                        .'" value="'.$currdom.'" /></span><br />'
 6250:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6251:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6252:                                        .&mt('Delete').'</label></span></td>';
 6253:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6254:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6255:                                        .&Apache::loncommon::end_data_table_row();
 6256:                             $num ++;
 6257:                         }
 6258:                     }
 6259:                 }
 6260:                 my $add_domtitle = &mt('Users in additional domain:');
 6261:                 if ($curr_types eq '*') { 
 6262:                     $add_domtitle = &mt('Users in specific domain:');
 6263:                 } elsif ($curr_types eq '') {
 6264:                     $add_domtitle = &mt('Users in other domain:');
 6265:                 }
 6266:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 6267:                 $output .= &Apache::loncommon::start_data_table_row()
 6268:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6269:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6270:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 6271:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6272:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6273:                            .&Apache::loncommon::end_data_table();
 6274:             } elsif ($item eq 'registered') {
 6275:                 my ($regon,$regoff);
 6276:                 my $registered;
 6277:                 if (ref($currsettings) eq 'HASH') {
 6278:                     $registered = $currsettings->{'selfenroll_registered'};
 6279:                 }
 6280:                 if ($noedit{$item}) {
 6281:                     if ($registered) {
 6282:                         $output .= &mt('Must be registered in course');
 6283:                     } else {
 6284:                         $output .= &mt('No requirement');
 6285:                     }
 6286:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6287:                     next;
 6288:                 }
 6289:                 if ($registered) {
 6290:                     $regon = ' checked="checked" ';
 6291:                     $regoff = '';
 6292:                 } else {
 6293:                     $regon = '';
 6294:                     $regoff = ' checked="checked" ';
 6295:                 }
 6296:                 $output .= '<label>'.
 6297:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6298:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6299:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6300:                            &mt('No').'</label>';
 6301:             } elsif ($item eq 'enroll_dates') {
 6302:                 my ($starttime,$endtime);
 6303:                 if (ref($currsettings) eq 'HASH') {
 6304:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6305:                     $endtime = $currsettings->{'selfenroll_end_date'};
 6306:                     if ($starttime eq '') {
 6307:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6308:                     }
 6309:                     if ($endtime eq '') {
 6310:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6311:                     }
 6312:                 }
 6313:                 if ($noedit{$item}) {
 6314:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6315:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6316:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6317:                     next;
 6318:                 }
 6319:                 my $startform =
 6320:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6321:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6322:                 my $endform =
 6323:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6324:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6325:                 $output .= &selfenroll_date_forms($startform,$endform);
 6326:             } elsif ($item eq 'access_dates') {
 6327:                 my ($starttime,$endtime);
 6328:                 if (ref($currsettings) eq 'HASH') {
 6329:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6330:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6331:                     if ($starttime eq '') {
 6332:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6333:                     }
 6334:                     if ($endtime eq '') {
 6335:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6336:                     }
 6337:                 }
 6338:                 if ($noedit{$item}) {
 6339:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6340:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6341:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6342:                     next;
 6343:                 }
 6344:                 my $startform =
 6345:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6346:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6347:                 my $endform =
 6348:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6349:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6350:                 $output .= &selfenroll_date_forms($startform,$endform);
 6351:             } elsif ($item eq 'section') {
 6352:                 my $currsec;
 6353:                 if (ref($currsettings) eq 'HASH') {
 6354:                     $currsec = $currsettings->{'selfenroll_section'};
 6355:                 }
 6356:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6357:                 my $newsecval;
 6358:                 if ($currsec ne 'none' && $currsec ne '') {
 6359:                     if (!defined($sections_count{$currsec})) {
 6360:                         $newsecval = $currsec;
 6361:                     }
 6362:                 }
 6363:                 if ($noedit{$item}) {
 6364:                     if ($currsec ne '') {
 6365:                         $output .= $currsec;
 6366:                     } else {
 6367:                         $output .= &mt('No specific section');
 6368:                     }
 6369:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6370:                     next;
 6371:                 }
 6372:                 my $sections_select = 
 6373:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6374:                 $output .= '<table class="LC_createuser">'."\n".
 6375:                            '<tr class="LC_section_row">'."\n".
 6376:                            '<td align="center">'.&mt('Existing sections')."\n".
 6377:                            '<br />'.$sections_select.'</td><td align="center">'.
 6378:                            &mt('New section').'<br />'."\n".
 6379:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6380:                            '<input type="hidden" name="sections" value="" />'."\n".
 6381:                            '</td></tr></table>'."\n";
 6382:             } elsif ($item eq 'approval') {
 6383:                 my ($currnotified,$currapproval,%appchecked);
 6384:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6385:                 if (ref($currsettings) eq 'HASH') {
 6386:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6387:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6388:                 }
 6389:                 if ($currapproval !~ /^[012]$/) {
 6390:                     $currapproval = 0;
 6391:                 }
 6392:                 if ($noedit{$item}) {
 6393:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6394:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6395:                     next;
 6396:                 }
 6397:                 $appchecked{$currapproval} = ' checked="checked"';
 6398:                 for my $i (0..2) {
 6399:                     $output .= '<label>'.
 6400:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6401:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6402:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6403:                 }
 6404:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6405:                 my (@ccs,%notified);
 6406:                 my $ccrole = 'cc';
 6407:                 if ($crstype eq 'Community') {
 6408:                     $ccrole = 'co';
 6409:                 }
 6410:                 if ($advhash{$ccrole}) {
 6411:                     @ccs = split(/,/,$advhash{$ccrole});
 6412:                 }
 6413:                 if ($currnotified) {
 6414:                     foreach my $current (split(/,/,$currnotified)) {
 6415:                         $notified{$current} = 1;
 6416:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6417:                             push(@ccs,$current);
 6418:                         }
 6419:                     }
 6420:                 }
 6421:                 if (@ccs) {
 6422:                     my $style;
 6423:                     unless ($currapproval) {
 6424:                         $style = ' style="display: none;"'; 
 6425:                     }
 6426:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6427:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6428:                                &Apache::loncommon::start_data_table().
 6429:                                &Apache::loncommon::start_data_table_row();
 6430:                     my $count = 0;
 6431:                     my $numcols = 4;
 6432:                     foreach my $cc (sort(@ccs)) {
 6433:                         my $notifyon;
 6434:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6435:                         if ($notified{$cc}) {
 6436:                             $notifyon = ' checked="checked" ';
 6437:                         }
 6438:                         if ($count && !$count%$numcols) {
 6439:                             $output .= &Apache::loncommon::end_data_table_row().
 6440:                                        &Apache::loncommon::start_data_table_row()
 6441:                         }
 6442:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6443:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6444:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6445:                                    '</label></span></td>';
 6446:                         $count ++;
 6447:                     }
 6448:                     my $rem = $count%$numcols;
 6449:                     if ($rem) {
 6450:                         my $emptycols = $numcols - $rem;
 6451:                         for (my $i=0; $i<$emptycols; $i++) { 
 6452:                             $output .= '<td>&nbsp;</td>';
 6453:                         }
 6454:                     }
 6455:                     $output .= &Apache::loncommon::end_data_table_row().
 6456:                                &Apache::loncommon::end_data_table().
 6457:                                '</div>';
 6458:                 }
 6459:             } elsif ($item eq 'limit') {
 6460:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6461:                 if (ref($currsettings) eq 'HASH') {
 6462:                     $currlim = $currsettings->{'selfenroll_limit'};
 6463:                     $currcap = $currsettings->{'selfenroll_cap'};
 6464:                 }
 6465:                 if ($noedit{$item}) {
 6466:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6467:                         if ($currlim eq 'allstudents') {
 6468:                             $output .= &mt('Limit by total students');
 6469:                         } elsif ($currlim eq 'selfenrolled') {
 6470:                             $output .= &mt('Limit by total self-enrolled students');
 6471:                         }
 6472:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6473:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6474:                     } else {
 6475:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6476:                     }
 6477:                     next;
 6478:                 }
 6479:                 if ($currlim eq 'allstudents') {
 6480:                     $crslimit = ' checked="checked" ';
 6481:                     $selflimit = ' ';
 6482:                     $nolimit = ' ';
 6483:                 } elsif ($currlim eq 'selfenrolled') {
 6484:                     $crslimit = ' ';
 6485:                     $selflimit = ' checked="checked" ';
 6486:                     $nolimit = ' '; 
 6487:                 } else {
 6488:                     $crslimit = ' ';
 6489:                     $selflimit = ' ';
 6490:                     $nolimit = ' checked="checked" ';
 6491:                 }
 6492:                 $output .= '<table><tr><td><label>'.
 6493:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6494:                            &mt('No limit').'</label></td><td><label>'.
 6495:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6496:                            &mt('Limit by total students').'</label></td><td><label>'.
 6497:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6498:                            &mt('Limit by total self-enrolled students').
 6499:                            '</td></tr><tr>'.
 6500:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6501:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6502:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6503:             }
 6504:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6505:         }
 6506:     }
 6507:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6508:     unless ($readonly) {
 6509:         $output .= '<input type="button" name="selfenrollconf" value="'
 6510:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6511:     }
 6512:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6513:               .'<input type="hidden" name="state" value="done" />'."\n"
 6514:               .$additional.'</form>';
 6515:     $r->print($output);
 6516:     return;
 6517: }
 6518: 
 6519: sub get_noedit_fields {
 6520:     my ($cdom,$cnum,$crstype,$row) = @_;
 6521:     my %noedit;
 6522:     if (ref($row) eq 'ARRAY') {
 6523:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6524:                                                            'internal.selfenrollmgrdc',
 6525:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6526:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6527:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6528:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6529:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6530:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6531:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6532: 
 6533:         foreach my $item (@{$row}) {
 6534:             next if ($specific_managebycc{$item});
 6535:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6536:                 $noedit{$item} = 1;
 6537:             }
 6538:         }
 6539:     }
 6540:     return %noedit;
 6541: } 
 6542: 
 6543: sub visible_in_stdcat {
 6544:     my ($cdom,$cnum,$domconf) = @_;
 6545:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6546:     unless (ref($domconf) eq 'HASH') {
 6547:         return ($visible,$cansetvis,\@vismsgs);
 6548:     }
 6549:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6550:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6551:             $settable{'togglecats'} = 1;
 6552:         }
 6553:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6554:             $settable{'categorize'} = 1;
 6555:         }
 6556:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6557:     }
 6558:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6559:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6560:     } elsif ($settable{'togglecats'}) {
 6561:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6562:     } elsif ($settable{'categorize'}) {
 6563:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6564:     } else {
 6565:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6566:     }
 6567:      
 6568:     my %currsettings =
 6569:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6570:                              $cdom,$cnum);
 6571:     $visible = 0;
 6572:     if ($currsettings{'internal.coursecode'} ne '') {
 6573:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6574:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6575:             if (ref($cathash) eq 'HASH') {
 6576:                 if ($cathash->{'instcode::0'} eq '') {
 6577:                     push(@vismsgs,'dc_addinst'); 
 6578:                 } else {
 6579:                     $visible = 1;
 6580:                 }
 6581:             } else {
 6582:                 $visible = 1;
 6583:             }
 6584:         } else {
 6585:             $visible = 1;
 6586:         }
 6587:     } else {
 6588:         if (ref($cathash) eq 'HASH') {
 6589:             if ($cathash->{'instcode::0'} ne '') {
 6590:                 push(@vismsgs,'dc_instcode');
 6591:             }
 6592:         } else {
 6593:             push(@vismsgs,'dc_instcode');
 6594:         }
 6595:     }
 6596:     if ($currsettings{'categories'} ne '') {
 6597:         my $cathash;
 6598:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6599:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6600:             if (ref($cathash) eq 'HASH') {
 6601:                 if (keys(%{$cathash}) == 0) {
 6602:                     push(@vismsgs,'dc_catalog');
 6603:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6604:                     push(@vismsgs,'dc_categories');
 6605:                 } else {
 6606:                     my @currcategories = split('&',$currsettings{'categories'});
 6607:                     my $matched = 0;
 6608:                     foreach my $cat (@currcategories) {
 6609:                         if ($cathash->{$cat} ne '') {
 6610:                             $visible = 1;
 6611:                             $matched = 1;
 6612:                             last;
 6613:                         }
 6614:                     }
 6615:                     if (!$matched) {
 6616:                         if ($settable{'categorize'}) { 
 6617:                             push(@vismsgs,'chgcat');
 6618:                         } else {
 6619:                             push(@vismsgs,'dc_chgcat');
 6620:                         }
 6621:                     }
 6622:                 }
 6623:             }
 6624:         }
 6625:     } else {
 6626:         if (ref($cathash) eq 'HASH') {
 6627:             if ((keys(%{$cathash}) > 1) || 
 6628:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6629:                 if ($settable{'categorize'}) {
 6630:                     push(@vismsgs,'addcat');
 6631:                 } else {
 6632:                     push(@vismsgs,'dc_addcat');
 6633:                 }
 6634:             }
 6635:         }
 6636:     }
 6637:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6638:         $visible = 0;
 6639:         if ($settable{'togglecats'}) {
 6640:             unshift(@vismsgs,'unhide');
 6641:         } else {
 6642:             unshift(@vismsgs,'dc_unhide')
 6643:         }
 6644:     }
 6645:     return ($visible,$cansetvis,\@vismsgs);
 6646: }
 6647: 
 6648: sub cat_visibility {
 6649:     my %visactions = &Apache::lonlocal::texthash(
 6650:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6651:                    gen => 'Courses can be both self-cataloging, based on an institutional code (e.g., fs08phy231), or can be assigned categories from a hierarchy defined for the domain.',
 6652:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6653:                    none => 'Display of a course catalog is disabled for this domain.',
 6654:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6655:                    coca => 'Courses can be absent from the Catalog, because they do not have an institutional code, have no assigned category, or have been specifically excluded.',
 6656:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6657:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6658:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6659:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6660:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6661:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6662:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6663:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6664:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6665:                    dc_chgcat => 'Ask a domain coordinator to change the category assigned to the course, as the one currently assigned is no longer used in the domain',
 6666:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6667:     );
 6668:     $visactions{'unhide'} = &mt('Use [_1]Categorize course[_2] to change the "Exclude from course catalog" setting.','<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6669:     $visactions{'chgcat'} = &mt('Use [_1]Categorize course[_2] to change the category assigned to the course, as the one currently assigned is no longer used in the domain.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6670:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6671:     return \%visactions;
 6672: }
 6673: 
 6674: sub new_selfenroll_dom_row {
 6675:     my ($newdom,$num) = @_;
 6676:     my $domdesc = &Apache::lonnet::domain($newdom);
 6677:     my $output;
 6678:     if ($domdesc ne '') {
 6679:         $output .= &Apache::loncommon::start_data_table_row()
 6680:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6681:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6682:                    .'" value="'.$newdom.'" /></span><br />'
 6683:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6684:                    .'name="selfenroll_activate" value="'.$num.'" '
 6685:                    .'onchange="javascript:update_types('
 6686:                    ."'selfenroll_activate','$num'".');" />'
 6687:                    .&mt('Activate').'</label></span></td>';
 6688:         my @currinsttypes;
 6689:         $output .= '<td>'.&mt('User types:').'<br />'
 6690:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6691:                    .&Apache::loncommon::end_data_table_row();
 6692:     }
 6693:     return $output;
 6694: }
 6695: 
 6696: sub selfenroll_inst_types {
 6697:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6698:     my $output;
 6699:     my $numinrow = 4;
 6700:     my $count = 0;
 6701:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6702:     my $othervalue = 'any';
 6703:     my $disabled;
 6704:     if ($readonly) {
 6705:         $disabled = ' disabled="disabled"';
 6706:     }
 6707:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6708:         if (keys(%{$usertypes}) > 0) {
 6709:             $othervalue = 'other';
 6710:         }
 6711:         $output .= '<table><tr>';
 6712:         foreach my $type (@{$types}) {
 6713:             if (($count > 0) && ($count%$numinrow == 0)) {
 6714:                 $output .= '</tr><tr>';
 6715:             }
 6716:             if (defined($usertypes->{$type})) {
 6717:                 my $esc_type = &escape($type);
 6718:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6719:                            $esc_type.'" ';
 6720:                 if (ref($currinsttypes) eq 'ARRAY') {
 6721:                     if (@{$currinsttypes} > 0) {
 6722:                         if (grep(/^any$/,@{$currinsttypes})) {
 6723:                             $output .= 'checked="checked"';
 6724:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6725:                             $output .= 'checked="checked"';
 6726:                         }
 6727:                     } else {
 6728:                         $output .= 'checked="checked"';
 6729:                     }
 6730:                 }
 6731:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6732:             }
 6733:             $count ++;
 6734:         }
 6735:         if (($count > 0) && ($count%$numinrow == 0)) {
 6736:             $output .= '</tr><tr>';
 6737:         }
 6738:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6739:         if (ref($currinsttypes) eq 'ARRAY') {
 6740:             if (@{$currinsttypes} > 0) {
 6741:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6742:                     $output .= ' checked="checked"';
 6743:                 } elsif ($othervalue eq 'other') {
 6744:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6745:                         $output .= ' checked="checked"';
 6746:                     }
 6747:                 }
 6748:             } else {
 6749:                 $output .= ' checked="checked"';
 6750:             }
 6751:         } else {
 6752:             $output .= ' checked="checked"';
 6753:         }
 6754:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6755:     }
 6756:     return $output;
 6757: }
 6758: 
 6759: sub selfenroll_date_forms {
 6760:     my ($startform,$endform) = @_;
 6761:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6762:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6763:                                                     'LC_oddrow_value')."\n".
 6764:                   $startform."\n".
 6765:                   &Apache::lonhtmlcommon::row_closure(1).
 6766:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6767:                                                    'LC_oddrow_value')."\n".
 6768:                   $endform."\n".
 6769:                   &Apache::lonhtmlcommon::row_closure(1).
 6770:                   &Apache::lonhtmlcommon::end_pick_box();
 6771:     return $output;
 6772: }
 6773: 
 6774: sub print_userchangelogs_display {
 6775:     my ($r,$context,$permission,$brcrum) = @_;
 6776:     my $formname = 'rolelog';
 6777:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6778:     if ($context eq 'domain') {
 6779:         $domain = $env{'request.role.domain'};
 6780:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6781:     } else {
 6782:         if ($context eq 'course') { 
 6783:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6784:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6785:             $crstype = &Apache::loncommon::course_type();
 6786:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6787:             my %saveable_parameters = ('show' => 'scalar',);
 6788:             &Apache::loncommon::store_course_settings('roles_log',
 6789:                                                       \%saveable_parameters);
 6790:             &Apache::loncommon::restore_course_settings('roles_log',
 6791:                                                         \%saveable_parameters);
 6792:         } elsif ($context eq 'author') {
 6793:             $domain = $env{'user.domain'}; 
 6794:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6795:                 $username = $env{'user.name'};
 6796:             } else {
 6797:                 undef($domain);
 6798:             }
 6799:         }
 6800:         if ($domain ne '' && $username ne '') { 
 6801:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6802:         }
 6803:     }
 6804:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6805: 
 6806:     my $helpitem;
 6807:     if ($context eq 'course') {
 6808:         $helpitem = 'Course_User_Logs';
 6809:     } elsif ($context eq 'domain') {
 6810:         $helpitem = 'Domain_Role_Logs';
 6811:     } elsif ($context eq 'author') {
 6812:         $helpitem = 'Author_User_Logs';
 6813:     }
 6814:     push (@{$brcrum},
 6815:              {href => '/adm/createuser?action=changelogs',
 6816:               text => 'User Management Logs',
 6817:               help => $helpitem});
 6818:     my $bread_crumbs_component = 'User Changes';
 6819:     my $args = { bread_crumbs           => $brcrum,
 6820:                  bread_crumbs_component => $bread_crumbs_component};
 6821: 
 6822:     # Create navigation javascript
 6823:     my $jsnav = &userlogdisplay_js($formname);
 6824: 
 6825:     my $jscript = (<<ENDSCRIPT);
 6826: <script type="text/javascript">
 6827: // <![CDATA[
 6828: $jsnav
 6829: // ]]>
 6830: </script>
 6831: ENDSCRIPT
 6832: 
 6833:     # print page header
 6834:     $r->print(&header($jscript,$args));
 6835: 
 6836:     # set defaults
 6837:     my $now = time();
 6838:     my $defstart = $now - (7*24*3600); #7 days ago 
 6839:     my %defaults = (
 6840:                      page               => '1',
 6841:                      show               => '10',
 6842:                      role               => 'any',
 6843:                      chgcontext         => 'any',
 6844:                      rolelog_start_date => $defstart,
 6845:                      rolelog_end_date   => $now,
 6846:                    );
 6847:     my $more_records = 0;
 6848: 
 6849:     # set current
 6850:     my %curr;
 6851:     foreach my $item ('show','page','role','chgcontext') {
 6852:         $curr{$item} = $env{'form.'.$item};
 6853:     }
 6854:     my ($startdate,$enddate) = 
 6855:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6856:     $curr{'rolelog_start_date'} = $startdate;
 6857:     $curr{'rolelog_end_date'} = $enddate;
 6858:     foreach my $key (keys(%defaults)) {
 6859:         if ($curr{$key} eq '') {
 6860:             $curr{$key} = $defaults{$key};
 6861:         }
 6862:     }
 6863:     my (%whodunit,%changed,$version);
 6864:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6865:     my ($minshown,$maxshown);
 6866:     $minshown = 1;
 6867:     my $count = 0;
 6868:     if ($curr{'show'} =~ /\D/) {
 6869:         $curr{'page'} = 1;
 6870:     } else {
 6871:         $maxshown = $curr{'page'} * $curr{'show'};
 6872:         if ($curr{'page'} > 1) {
 6873:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6874:         }
 6875:     }
 6876: 
 6877:     # Form Header
 6878:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6879:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6880:                                    $version,$crstype));
 6881: 
 6882:     my $showntableheader = 0;
 6883: 
 6884:     # Table Header
 6885:     my $tableheader = 
 6886:         &Apache::loncommon::start_data_table_header_row()
 6887:        .'<th>&nbsp;</th>'
 6888:        .'<th>'.&mt('When').'</th>'
 6889:        .'<th>'.&mt('Who made the change').'</th>'
 6890:        .'<th>'.&mt('Changed User').'</th>'
 6891:        .'<th>'.&mt('Role').'</th>';
 6892: 
 6893:     if ($context eq 'course') {
 6894:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6895:     }
 6896:     $tableheader .=
 6897:         '<th>'.&mt('Context').'</th>'
 6898:        .'<th>'.&mt('Start').'</th>'
 6899:        .'<th>'.&mt('End').'</th>'
 6900:        .&Apache::loncommon::end_data_table_header_row();
 6901: 
 6902:     # Display user change log data
 6903:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6904:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6905:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6906:         if ($curr{'show'} !~ /\D/) {
 6907:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6908:                 $more_records = 1;
 6909:                 last;
 6910:             }
 6911:         }
 6912:         if ($curr{'role'} ne 'any') {
 6913:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6914:         }
 6915:         if ($curr{'chgcontext'} ne 'any') {
 6916:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6917:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6918:             } else {
 6919:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6920:             }
 6921:         }
 6922:         if (($context eq 'course') && ($viewablesec ne '')) {
 6923:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6924:         }
 6925:         $count ++;
 6926:         next if ($count < $minshown);
 6927:         unless ($showntableheader) {
 6928:             $r->print(&Apache::loncommon::start_data_table()
 6929:                      .$tableheader);
 6930:             $r->rflush();
 6931:             $showntableheader = 1;
 6932:         }
 6933:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6934:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6935:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6936:         }
 6937:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6938:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6939:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6940:         }
 6941:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6942:         if ($sec eq '') {
 6943:             $sec = &mt('None');
 6944:         }
 6945:         my ($rolestart,$roleend);
 6946:         if ($roleslog{$id}{'delflag'}) {
 6947:             $rolestart = &mt('deleted');
 6948:             $roleend = &mt('deleted');
 6949:         } else {
 6950:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6951:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6952:             if ($rolestart eq '' || $rolestart == 0) {
 6953:                 $rolestart = &mt('No start date'); 
 6954:             } else {
 6955:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6956:             }
 6957:             if ($roleend eq '' || $roleend == 0) { 
 6958:                 $roleend = &mt('No end date');
 6959:             } else {
 6960:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6961:             }
 6962:         }
 6963:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6964:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6965:             $chgcontext = 'selfenroll';
 6966:         }
 6967:         my %lt = &rolechg_contexts($context,$crstype);
 6968:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6969:             $chgcontext = $lt{$chgcontext};
 6970:         }
 6971:         $r->print(
 6972:             &Apache::loncommon::start_data_table_row()
 6973:            .'<td>'.$count.'</td>'
 6974:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6975:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6976:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6977:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6978:         if ($context eq 'course') { 
 6979:             $r->print('<td>'.$sec.'</td>');
 6980:         }
 6981:         $r->print(
 6982:             '<td>'.$chgcontext.'</td>'
 6983:            .'<td>'.$rolestart.'</td>'
 6984:            .'<td>'.$roleend.'</td>'
 6985:            .&Apache::loncommon::end_data_table_row()."\n");
 6986:     }
 6987: 
 6988:     if ($showntableheader) { # Table footer, if content displayed above
 6989:         $r->print(&Apache::loncommon::end_data_table().
 6990:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6991:     } else { # No content displayed above
 6992:         $r->print('<p class="LC_info">'
 6993:                  .&mt('There are no records to display.')
 6994:                  .'</p>'
 6995:         );
 6996:     }
 6997: 
 6998:     # Form Footer
 6999:     $r->print( 
 7000:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7001:        .'<input type="hidden" name="action" value="changelogs" />'
 7002:        .'</form>');
 7003:     return;
 7004: }
 7005: 
 7006: sub print_useraccesslogs_display {
 7007:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 7008:     my $formname = 'accesslog';
 7009:     my $form = 'document.accesslog';
 7010: 
 7011: # set breadcrumbs
 7012:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 7013:     my $prevphasestr;
 7014:     if ($env{'form.popup'}) {
 7015:         $brcrum = [];
 7016:     } else {
 7017:         push (@{$brcrum},
 7018:             {href => "javascript:backPage($form)",
 7019:              text => $breadcrumb_text{'search'}});
 7020:         my @prevphases;
 7021:         if ($env{'form.prevphases'}) {
 7022:             @prevphases = split(/,/,$env{'form.prevphases'});
 7023:             $prevphasestr = $env{'form.prevphases'};
 7024:         }
 7025:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 7026:             push(@{$brcrum},
 7027:                   {href => "javascript:backPage($form,'get_user_info','select')",
 7028:                    text => $breadcrumb_text{'userpicked'}});
 7029:             if ($env{'form.phase'} eq 'userpicked') {
 7030:                 $prevphasestr = 'userpicked';
 7031:             }
 7032:         }
 7033:     }
 7034:     push(@{$brcrum},
 7035:              {href => '/adm/createuser?action=accesslogs',
 7036:               text => 'User access logs',
 7037:               help => 'Domain_User_Access_Logs'});
 7038:     my $bread_crumbs_component = 'User Access Logs';
 7039:     my $args = { bread_crumbs           => $brcrum,
 7040:                  bread_crumbs_component => 'User Management'};
 7041:     if ($env{'form.popup'}) {
 7042:         $args->{'no_nav_bar'} = 1;
 7043:         $args->{'bread_crumbs_nomenu'} = 1;
 7044:     }
 7045: 
 7046: # set javascript
 7047:     my ($jsback,$elements) = &crumb_utilities();
 7048:     my $jsnav = &userlogdisplay_js($formname);
 7049: 
 7050:     my $jscript = (<<ENDSCRIPT);
 7051: <script type="text/javascript">
 7052: // <![CDATA[
 7053: 
 7054: $jsback
 7055: $jsnav
 7056: 
 7057: // ]]>
 7058: </script>
 7059: 
 7060: ENDSCRIPT
 7061: 
 7062: # print page header
 7063:     $r->print(&header($jscript,$args));
 7064: 
 7065: # early out unless log data can be displayed.
 7066:     unless ($permission->{'activity'}) {
 7067:         $r->print('<p class="LC_warning">'
 7068:                  .&mt('You do not have rights to display user access logs.')
 7069:                  .'</p>');
 7070:         if ($env{'form.popup'}) {
 7071:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7072:         } else {
 7073:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7074:         }
 7075:         return;
 7076:     }
 7077: 
 7078:     unless ($udom eq $env{'request.role.domain'}) {
 7079:         $r->print('<p class="LC_warning">'
 7080:                  .&mt("User's domain must match role's domain")
 7081:                  .'</p>'
 7082:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7083:         return;
 7084:     }
 7085: 
 7086:     if (($uname eq '') || ($udom eq '')) {
 7087:         $r->print('<p class="LC_warning">'
 7088:                  .&mt('Invalid username or domain')
 7089:                  .'</p>'
 7090:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7091:         return;
 7092:     }
 7093: 
 7094:     if (&Apache::lonnet::privileged($uname,$udom,
 7095:                                     [$env{'request.role.domain'}],['dc','su'])) {
 7096:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 7097:                                             [$env{'request.role.domain'}],['dc','su'])) {
 7098:             $r->print('<p class="LC_warning">'
 7099:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 7100:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 7101:                                                          $uname,$udom))
 7102:                  .'</p>');
 7103:             if ($env{'form.popup'}) {
 7104:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7105:             } else {
 7106:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7107:             }
 7108:             return;
 7109:         }
 7110:     }
 7111: 
 7112: # set defaults
 7113:     my $now = time();
 7114:     my $defstart = $now - (7*24*3600);
 7115:     my %defaults = (
 7116:                      page                 => '1',
 7117:                      show                 => '10',
 7118:                      activity             => 'any',
 7119:                      accesslog_start_date => $defstart,
 7120:                      accesslog_end_date   => $now,
 7121:                    );
 7122:     my $more_records = 0;
 7123: 
 7124: # set current
 7125:     my %curr;
 7126:     foreach my $item ('show','page','activity') {
 7127:         $curr{$item} = $env{'form.'.$item};
 7128:     }
 7129:     my ($startdate,$enddate) =
 7130:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 7131:     $curr{'accesslog_start_date'} = $startdate;
 7132:     $curr{'accesslog_end_date'} = $enddate;
 7133:     foreach my $key (keys(%defaults)) {
 7134:         if ($curr{$key} eq '') {
 7135:             $curr{$key} = $defaults{$key};
 7136:         }
 7137:     }
 7138:     my ($minshown,$maxshown);
 7139:     $minshown = 1;
 7140:     my $count = 0;
 7141:     if ($curr{'show'} =~ /\D/) {
 7142:         $curr{'page'} = 1;
 7143:     } else {
 7144:         $maxshown = $curr{'page'} * $curr{'show'};
 7145:         if ($curr{'page'} > 1) {
 7146:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 7147:         }
 7148:     }
 7149: 
 7150: # form header
 7151:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 7152:               &activity_display_filter($formname,\%curr));
 7153: 
 7154:     my $showntableheader = 0;
 7155:     my ($nav_script,$nav_links);
 7156: 
 7157: # table header
 7158:     my $heading = '<h3>'.
 7159:         &mt('User access logs for: [_1]',
 7160:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 7161:     my $tableheader = $heading
 7162:        .&Apache::loncommon::start_data_table_header_row()
 7163:        .'<th>&nbsp;</th>'
 7164:        .'<th>'.&mt('When').'</th>'
 7165:        .'<th>'.&mt('HostID').'</th>'
 7166:        .'<th>'.&mt('Event').'</th>'
 7167:        .'<th>'.&mt('Other data').'</th>'
 7168:        .&Apache::loncommon::end_data_table_header_row();
 7169: 
 7170:     my %filters=(
 7171:         start  => $curr{'accesslog_start_date'},
 7172:         end    => $curr{'accesslog_end_date'},
 7173:         action => $curr{'activity'},
 7174:     );
 7175: 
 7176:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 7177:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7178:         my (%courses,%missing);
 7179:         my @results = split(/\&/,$reply);
 7180:         foreach my $item (reverse(@results)) {
 7181:             my ($timestamp,$host,$event) = split(/:/,$item);
 7182:             next unless ($event =~ /^(Log|Role)/);
 7183:             if ($curr{'show'} !~ /\D/) {
 7184:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 7185:                     $more_records = 1;
 7186:                     last;
 7187:                 }
 7188:             }
 7189:             $count ++;
 7190:             next if ($count < $minshown);
 7191:             unless ($showntableheader) {
 7192:                 $r->print($nav_script
 7193:                          .&Apache::loncommon::start_data_table()
 7194:                          .$tableheader);
 7195:                 $r->rflush();
 7196:                 $showntableheader = 1;
 7197:             }
 7198:             my ($shown,$extra);
 7199:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 7200:             if ($event eq 'Role') {
 7201:                 my ($rolecode,$extent) = split(/\./,$data,2);
 7202:                 next if ($extent eq '');
 7203:                 my ($crstype,$desc,$info);
 7204:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 7205:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 7206:                     my $cid = $cdom.'_'.$cnum;
 7207:                     if (exists($courses{$cid})) {
 7208:                         $crstype = $courses{$cid}{'type'};
 7209:                         $desc = $courses{$cid}{'description'};
 7210:                     } elsif ($missing{$cid}) {
 7211:                         $crstype = 'Course';
 7212:                         $desc = 'Course/Community';
 7213:                     } else {
 7214:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7215:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 7216:                             $courses{$cid} = $crsinfo{$cid};
 7217:                             $crstype = $crsinfo{$cid}{'type'};
 7218:                             $desc = $crsinfo{$cid}{'description'};
 7219:                         } else {
 7220:                             $missing{$cid} = 1;
 7221:                         }
 7222:                     }
 7223:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 7224:                     if ($sec ne '') {
 7225:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 7226:                     }
 7227:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 7228:                     my ($dom,$name) = ($1,$2);
 7229:                     if ($rolecode eq 'au') {
 7230:                         $extra = '';
 7231:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 7232:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 7233:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 7234:                         $extra = &mt('Domain: [_1]',$dom);
 7235:                     }
 7236:                 }
 7237:                 my $rolename;
 7238:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 7239:                     my $role = $3;
 7240:                     my $owner = "($2:$1)";
 7241:                     if ($2 eq $1.'-domainconfig') {
 7242:                         $owner = '(ad hoc)';
 7243:                     }
 7244:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7245:                 } else {
 7246:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7247:                 }
 7248:                 $shown = &mt('Role selection: [_1]',$rolename);
 7249:             } else {
 7250:                 $shown = &mt($event);
 7251:                 if ($data =~ /^webdav/) {
 7252:                     my ($path,$clientip) = split(/\s+/,$data,2);
 7253:                     $path =~ s/^webdav//;
 7254:                     if ($clientip ne '') {
 7255:                         $extra = &mt('Client IP address: [_1]',$clientip);
 7256:                     }
 7257:                     if ($path ne '') {
 7258:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 7259:                     }
 7260:                 } elsif ($data ne '') {
 7261:                     $extra = &mt('Client IP address: [_1]',$data);
 7262:                 }
 7263:             }
 7264:             $r->print(
 7265:             &Apache::loncommon::start_data_table_row()
 7266:            .'<td>'.$count.'</td>'
 7267:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7268:            .'<td>'.$host.'</td>'
 7269:            .'<td>'.$shown.'</td>'
 7270:            .'<td>'.$extra.'</td>'
 7271:            .&Apache::loncommon::end_data_table_row()."\n");
 7272:         }
 7273:     }
 7274: 
 7275:     if ($showntableheader) { # Table footer, if content displayed above
 7276:         $r->print(&Apache::loncommon::end_data_table().
 7277:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7278:     } else { # No content displayed above
 7279:         $r->print($heading.'<p class="LC_info">'
 7280:                  .&mt('There are no records to display.')
 7281:                  .'</p>');
 7282:     }
 7283: 
 7284:     if ($env{'form.popup'} == 1) {
 7285:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 7286:     }
 7287: 
 7288:     # Form Footer
 7289:     $r->print(
 7290:         '<input type="hidden" name="currstate" value="" />'
 7291:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7292:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7293:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7294:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7295:        .'<input type="hidden" name="phase" value="activity" />'
 7296:        .'<input type="hidden" name="action" value="accesslogs" />'
 7297:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7298:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7299:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7300:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7301:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7302:        .'</form>');
 7303:     return;
 7304: }
 7305: 
 7306: sub earlyout_accesslog_form {
 7307:     my ($formname,$prevphasestr,$udom) = @_;
 7308:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7309:    return <<"END";
 7310: <form action="/adm/createuser" method="post" name="$formname">
 7311: <input type="hidden" name="currstate" value="" />
 7312: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7313: <input type="hidden" name="phase" value="activity" />
 7314: <input type="hidden" name="action" value="accesslogs" />
 7315: <input type="hidden" name="srchdomain" value="$udom" />
 7316: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7317: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7318: <input type="hidden" name="srchterm" value="$srchterm" />
 7319: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7320: </form>
 7321: END
 7322: }
 7323: 
 7324: sub activity_display_filter {
 7325:     my ($formname,$curr) = @_;
 7326:     my $nolink = 1;
 7327:     my $output = '<table><tr><td valign="top">'.
 7328:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7329:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7330:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7331:                  '</td><td>&nbsp;&nbsp;</td>';
 7332:     my $startform =
 7333:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7334:                                             $curr->{'accesslog_start_date'},undef,
 7335:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7336:     my $endform =
 7337:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7338:                                             $curr->{'accesslog_end_date'},undef,
 7339:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7340:     my %lt = &Apache::lonlocal::texthash (
 7341:                                           activity => 'Activity',
 7342:                                           Role     => 'Role selection',
 7343:                                           log      => 'Log-in or Logout',
 7344:     );
 7345:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7346:                '<table><tr><td>'.&mt('After:').
 7347:                '</td><td>'.$startform.'</td></tr>'.
 7348:                '<tr><td>'.&mt('Before:').'</td>'.
 7349:                '<td>'.$endform.'</td></tr></table>'.
 7350:                '</td>'.
 7351:                '<td>&nbsp;&nbsp;</td>'.
 7352:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7353:                '<select name="activity"><option value="any"';
 7354:     if ($curr->{'activity'} eq 'any') {
 7355:         $output .= ' selected="selected"';
 7356:     }
 7357:     $output .= '>'.&mt('Any').'</option>'."\n";
 7358:     foreach my $activity ('Role','log') {
 7359:         my $selstr = '';
 7360:         if ($activity eq $curr->{'activity'}) {
 7361:             $selstr = ' selected="selected"';
 7362:         }
 7363:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7364:     }
 7365:     $output .= '</select></td>'.
 7366:                '</tr></table>';
 7367:     # Update Display button
 7368:     $output .= '<p>'
 7369:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7370:               .'</p><hr />';
 7371:     return $output;
 7372: }
 7373: 
 7374: sub userlogdisplay_js {
 7375:     my ($formname) = @_;
 7376:     return <<"ENDSCRIPT";
 7377: 
 7378: function chgPage(caller) {
 7379:     if (caller == 'previous') {
 7380:         document.$formname.page.value --;
 7381:     }
 7382:     if (caller == 'next') {
 7383:         document.$formname.page.value ++;
 7384:     }
 7385:     document.$formname.submit();
 7386:     return;
 7387: }
 7388: ENDSCRIPT
 7389: }
 7390: 
 7391: sub userlogdisplay_navlinks {
 7392:     my ($curr,$more_records) = @_;
 7393:     return unless(ref($curr) eq 'HASH');
 7394:     # Navigation Buttons
 7395:     my $nav_links = '<p>';
 7396:     if (($curr->{'page'} > 1) || ($more_records)) {
 7397:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7398:             $nav_links .= '<input type="button"'
 7399:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7400:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7401:                          .'" /> ';
 7402:         }
 7403:         if ($more_records) {
 7404:             $nav_links .= '<input type="button"'
 7405:                          .' onclick="javascript:chgPage('."'next'".');"'
 7406:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7407:                          .'" />';
 7408:         }
 7409:     }
 7410:     $nav_links .= '</p>';
 7411:     return $nav_links;
 7412: }
 7413: 
 7414: sub role_display_filter {
 7415:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7416:     my $lctype;
 7417:     if ($context eq 'course') {
 7418:         $lctype = lc($crstype);
 7419:     }
 7420:     my $nolink = 1;
 7421:     my $output = '<table><tr><td valign="top">'.
 7422:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7423:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7424:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7425:                  '</td><td>&nbsp;&nbsp;</td>';
 7426:     my $startform =
 7427:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7428:                                             $curr->{'rolelog_start_date'},undef,
 7429:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7430:     my $endform =
 7431:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7432:                                             $curr->{'rolelog_end_date'},undef,
 7433:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7434:     my %lt = &rolechg_contexts($context,$crstype);
 7435:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7436:                '<table><tr><td>'.&mt('After:').
 7437:                '</td><td>'.$startform.'</td></tr>'.
 7438:                '<tr><td>'.&mt('Before:').'</td>'.
 7439:                '<td>'.$endform.'</td></tr></table>'.
 7440:                '</td>'.
 7441:                '<td>&nbsp;&nbsp;</td>'.
 7442:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7443:                '<select name="role"><option value="any"';
 7444:     if ($curr->{'role'} eq 'any') {
 7445:         $output .= ' selected="selected"';
 7446:     }
 7447:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7448:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7449:     foreach my $role (@roles) {
 7450:         my $plrole;
 7451:         if ($role eq 'cr') {
 7452:             $plrole = &mt('Custom Role');
 7453:         } else {
 7454:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7455:         }
 7456:         my $selstr = '';
 7457:         if ($role eq $curr->{'role'}) {
 7458:             $selstr = ' selected="selected"';
 7459:         }
 7460:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7461:     }
 7462:     $output .= '</select></td>'.
 7463:                '<td>&nbsp;&nbsp;</td>'.
 7464:                '<td valign="top"><b>'.
 7465:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7466:     my @posscontexts;
 7467:     if ($context eq 'course') {
 7468:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses','chgtype');
 7469:     } elsif ($context eq 'domain') {
 7470:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7471:     } else {
 7472:         @posscontexts = ('any','author','domain');
 7473:     }
 7474:     foreach my $chgtype (@posscontexts) {
 7475:         my $selstr = '';
 7476:         if ($curr->{'chgcontext'} eq $chgtype) {
 7477:             $selstr = ' selected="selected"';
 7478:         }
 7479:         if ($context eq 'course') {
 7480:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7481:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7482:             }
 7483:         }
 7484:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7485:     }
 7486:     $output .= '</select></td>'
 7487:               .'</tr></table>';
 7488: 
 7489:     # Update Display button
 7490:     $output .= '<p>'
 7491:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7492:               .'</p>';
 7493: 
 7494:     # Server version info
 7495:     my $needsrev = '2.11.0';
 7496:     if ($context eq 'course') {
 7497:         $needsrev = '2.7.0';
 7498:     }
 7499:     
 7500:     $output .= '<p class="LC_info">'
 7501:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7502:                   ,$needsrev);
 7503:     if ($version) {
 7504:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7505:     }
 7506:     $output .= '</p><hr />';
 7507:     return $output;
 7508: }
 7509: 
 7510: sub rolechg_contexts {
 7511:     my ($context,$crstype) = @_;
 7512:     my %lt;
 7513:     if ($context eq 'course') {
 7514:         %lt = &Apache::lonlocal::texthash (
 7515:                                              any          => 'Any',
 7516:                                              automated    => 'Automated Enrollment',
 7517:                                              chgtype      => 'Enrollment Type/Lock Change',
 7518:                                              updatenow    => 'Roster Update',
 7519:                                              createcourse => 'Course Creation',
 7520:                                              course       => 'User Management in course',
 7521:                                              domain       => 'User Management in domain',
 7522:                                              selfenroll   => 'Self-enrolled',
 7523:                                              requestcourses => 'Course Request',
 7524:                                          );
 7525:         if ($crstype eq 'Community') {
 7526:             $lt{'createcourse'} = &mt('Community Creation');
 7527:             $lt{'course'} = &mt('User Management in community');
 7528:             $lt{'requestcourses'} = &mt('Community Request');
 7529:         }
 7530:     } elsif ($context eq 'domain') {
 7531:         %lt = &Apache::lonlocal::texthash (
 7532:                                              any           => 'Any',
 7533:                                              domain        => 'User Management in domain',
 7534:                                              requestauthor => 'Authoring Request',
 7535:                                              server        => 'Command line script (DC role)',
 7536:                                              domconfig     => 'Self-enrolled',
 7537:                                          );
 7538:     } else {
 7539:         %lt = &Apache::lonlocal::texthash (
 7540:                                              any    => 'Any',
 7541:                                              domain => 'User Management in domain',
 7542:                                              author => 'User Management by author',
 7543:                                          );
 7544:     } 
 7545:     return %lt;
 7546: }
 7547: 
 7548: sub print_helpdeskaccess_display {
 7549:     my ($r,$permission,$brcrum) = @_;
 7550:     my $formname = 'helpdeskaccess';
 7551:     my $helpitem = 'Course_Helpdesk_Access';
 7552:     push (@{$brcrum},
 7553:              {href => '/adm/createuser?action=helpdesk',
 7554:               text => 'Helpdesk Access',
 7555:               help => $helpitem});
 7556:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7557:     my $args = { bread_crumbs           => $brcrum,
 7558:                  bread_crumbs_component => $bread_crumbs_component};
 7559: 
 7560:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7561:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7562:     my $confname = $cdom.'-domainconfig';
 7563:     my $crstype = &Apache::loncommon::course_type();
 7564: 
 7565:     my @accesstypes = ('all','dh','da','none');
 7566:     my ($numstatustypes,@jsarray);
 7567:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7568:     if (ref($types) eq 'ARRAY') {
 7569:         if (@{$types} > 0) {
 7570:             $numstatustypes = scalar(@{$types});
 7571:             push(@accesstypes,'status');
 7572:             @jsarray = ('bystatus');
 7573:         }
 7574:     }
 7575:     my %customroles = &get_domain_customroles($cdom,$confname);
 7576:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7577:     if (keys(%domhelpdesk)) {
 7578:        push(@accesstypes,('inc','exc'));
 7579:        push(@jsarray,('notinc','notexc'));
 7580:     }
 7581:     push(@jsarray,'privs');
 7582:     my $hiddenstr = join("','",@jsarray);
 7583:     my $rolestr = join("','",sort(keys(%customroles)));
 7584: 
 7585:     my $jscript;
 7586:     my (%settings,%overridden);
 7587:     if (keys(%customroles)) {
 7588:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7589:                                 $types,\%customroles,\%settings,\%overridden);
 7590:         my %jsfull=();
 7591:         my %jslevels= (
 7592:                      course => {},
 7593:                      domain => {},
 7594:                      system => {},
 7595:                     );
 7596:         my %jslevelscurrent=(
 7597:                            course => {},
 7598:                            domain => {},
 7599:                            system => {},
 7600:                           );
 7601:         my (%privs,%jsprivs);
 7602:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7603:         foreach my $priv (keys(%jsfull)) {
 7604:             if ($jslevels{'course'}{$priv}) {
 7605:                 $jsprivs{$priv} = 1;
 7606:             }
 7607:         }
 7608:         my (%elements,%stored);
 7609:         foreach my $role (keys(%customroles)) {
 7610:             $elements{$role.'_access'} = 'radio';
 7611:             $elements{$role.'_incrs'} = 'radio';
 7612:             if ($numstatustypes) {
 7613:                 $elements{$role.'_status'} = 'checkbox';
 7614:             }
 7615:             if (keys(%domhelpdesk) > 0) {
 7616:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7617:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7618:             }
 7619:             $elements{$role.'_override'} = 'checkbox';
 7620:             if (ref($settings{$role}) eq 'HASH') {
 7621:                 if ($settings{$role}{'access'} ne '') {
 7622:                     my $curraccess = $settings{$role}{'access'};
 7623:                     $stored{$role.'_access'} = $curraccess;
 7624:                     $stored{$role.'_incrs'} = 1;
 7625:                     if ($curraccess eq 'status') {
 7626:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7627:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7628:                         }
 7629:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7630:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7631:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7632:                         }
 7633:                     }
 7634:                 } else {
 7635:                     $stored{$role.'_incrs'} = 0;
 7636:                 }
 7637:                 $stored{$role.'_override'} = [];
 7638:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7639:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7640:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7641:                             push(@{$stored{$role.'_override'}},$priv);
 7642:                         }
 7643:                     }
 7644:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7645:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7646:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7647:                                 push(@{$stored{$role.'_override'}},$priv);
 7648:                             }
 7649:                         }
 7650:                     }
 7651:                 }
 7652:             } else {
 7653:                 $stored{$role.'_incrs'} = 0;
 7654:             }
 7655:         }
 7656:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7657:     }
 7658: 
 7659:     my $js = <<"ENDJS";
 7660: <script type="text/javascript">
 7661: // <![CDATA[
 7662: $jscript;
 7663: 
 7664: function switchRoleTab(caller,role) {
 7665:     if (document.getElementById(role+'_maindiv')) {
 7666:         if (caller.id != 'LC_current_minitab') {
 7667:             if (document.getElementById('LC_current_minitab')) {
 7668:                 document.getElementById('LC_current_minitab').id=null;
 7669:             }
 7670:             var roledivs = Array('$rolestr');
 7671:             if (roledivs.length > 0) {
 7672:                 for (var i=0; i<roledivs.length; i++) {
 7673:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7674:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7675:                     }
 7676:                 }
 7677:             }
 7678:             caller.id = 'LC_current_minitab';
 7679:             document.getElementById(role+'_maindiv').style.display='block';
 7680:         }
 7681:     }
 7682:     return false;
 7683: }
 7684: 
 7685: function helpdeskAccess(role) {
 7686:     var curraccess = null;
 7687:     if (document.$formname.elements[role+'_access'].length) {
 7688:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7689:             if (document.$formname.elements[role+'_access'][i].checked) {
 7690:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7691:             }
 7692:         }
 7693:     }
 7694:     var shown = Array();
 7695:     var hidden = Array();
 7696:     if (curraccess == 'none') {
 7697:         hidden = Array ('$hiddenstr');
 7698:     } else {
 7699:         if (curraccess == 'status') {
 7700:             shown = Array ('bystatus','privs');
 7701:             hidden = Array ('notinc','notexc');
 7702:         } else {
 7703:             if (curraccess == 'exc') {
 7704:                 shown = Array ('notexc','privs');
 7705:                 hidden = Array ('notinc','bystatus');
 7706:             }
 7707:             if (curraccess == 'inc') {
 7708:                 shown = Array ('notinc','privs');
 7709:                 hidden = Array ('notexc','bystatus');
 7710:             }
 7711:             if (curraccess == 'all') {
 7712:                 shown = Array ('privs');
 7713:                 hidden = Array ('notinc','notexc','bystatus');
 7714:             }
 7715:         }
 7716:     }
 7717:     if (hidden.length > 0) {
 7718:         for (var i=0; i<hidden.length; i++) {
 7719:             if (document.getElementById(role+'_'+hidden[i])) {
 7720:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 7721:             }
 7722:         }
 7723:     }
 7724:     if (shown.length > 0) {
 7725:         for (var i=0; i<shown.length; i++) {
 7726:             if (document.getElementById(role+'_'+shown[i])) {
 7727:                 if (shown[i] == 'privs') {
 7728:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7729:                 } else {
 7730:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7731:                 }
 7732:             }
 7733:         }
 7734:     }
 7735:     return;
 7736: }
 7737: 
 7738: function toggleAccess(role) {
 7739:     if ((document.getElementById(role+'_setincrs')) &&
 7740:         (document.getElementById(role+'_setindom'))) {
 7741:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7742:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7743:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7744:                     document.getElementById(role+'_setindom').style.display = 'none';
 7745:                     document.getElementById(role+'_setincrs').style.display = 'block';
 7746:                 } else {
 7747:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7748:                     document.getElementById(role+'_setindom').style.display = 'block';
 7749:                 }
 7750:                 break;
 7751:             }
 7752:         }
 7753:     }
 7754:     return;
 7755: }
 7756: 
 7757: // ]]>
 7758: </script>
 7759: ENDJS
 7760: 
 7761:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7762: 
 7763:     # print page header
 7764:     $r->print(&header($js,$args));
 7765:     # print form header
 7766:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7767: 
 7768:     if (keys(%customroles)) {
 7769:         my %lt = &Apache::lonlocal::texthash(
 7770:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7771:                     'rou'    => 'Role usage',
 7772:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7773:                     'udd'    => 'Use domain default',
 7774:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 7775:                     'dh'     => 'All with domain helpdesk role',
 7776:                     'da'     => 'All with domain helpdesk assistant role',
 7777:                     'none'   => 'None',
 7778:                     'status' => 'Determined based on institutional status',
 7779:                     'inc'    => 'Include all, but exclude specific personnel',
 7780:                     'exc'    => 'Exclude all, but include specific personnel',
 7781:                     'hel'    => 'Helpdesk',
 7782:                     'rpr'    => 'Role privileges',
 7783:                  );
 7784:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7785:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7786:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7787:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7788:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7789:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7790:             }
 7791:         }
 7792:         my $count = 0;
 7793:         foreach my $role (sort(keys(%customroles))) {
 7794:             my ($order,$desc,$access_in_dom);
 7795:             if (ref($domcurrent{$role}) eq 'HASH') {
 7796:                 $order = $domcurrent{$role}{'order'};
 7797:                 $desc = $domcurrent{$role}{'desc'};
 7798:                 $access_in_dom = $domcurrent{$role}{'access'};
 7799:             }
 7800:             if ($order eq '') {
 7801:                 $order = $count;
 7802:             }
 7803:             $ordered{$order} = $role;
 7804:             if ($desc ne '') {
 7805:                 $description{$role} = $desc;
 7806:             } else {
 7807:                 $description{$role}= $role;
 7808:             }
 7809:             $count++;
 7810:         }
 7811:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7812:         my @roles_by_num = ();
 7813:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7814:             push(@roles_by_num,$ordered{$item});
 7815:         }
 7816:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7817:         if ($permission->{'owner'}) {
 7818:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7819:             $r->print('<input type="hidden" name="state" value="process" />'.
 7820:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7821:         } else {
 7822:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7823:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7824:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7825:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7826:             }
 7827:             $disabled = ' disabled="disabled"';
 7828:         }
 7829:         $r->print('</p>');
 7830: 
 7831:         $r->print('<div id="LC_minitab_header"><ul>');
 7832:         my $count = 0;
 7833:         my %visibility;
 7834:         foreach my $role (@roles_by_num) {
 7835:             my $id;
 7836:             if ($count == 0) {
 7837:                 $id=' id="LC_current_minitab"';
 7838:                 $visibility{$role} = ' style="display:block"';
 7839:             } else {
 7840:                 $visibility{$role} = ' style="display:none"';
 7841:             }
 7842:             $count ++;
 7843:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7844:         }
 7845:         $r->print('</ul></div>');
 7846: 
 7847:         foreach my $role (@roles_by_num) {
 7848:             my %usecheck = (
 7849:                              all => ' checked="checked"',
 7850:                            );
 7851:             my %displaydiv = (
 7852:                                 status => 'none',
 7853:                                 inc    => 'none',
 7854:                                 exc    => 'none',
 7855:                                 priv   => 'block',
 7856:                              );
 7857:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7858:             if (ref($settings{$role}) eq 'HASH') {
 7859:                 if ($settings{$role}{'access'} ne '') {
 7860:                     $indomvis = ' style="display:none"';
 7861:                     $incrsvis = ' style="display:block"';
 7862:                     $incrscheck = ' checked="checked"';
 7863:                     if ($settings{$role}{'access'} ne 'all') {
 7864:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7865:                         delete($usecheck{'all'});
 7866:                         if ($settings{$role}{'access'} eq 'status') {
 7867:                             my $access = 'status';
 7868:                             $displaydiv{$access} = 'inline';
 7869:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7870:                                 $selected{$access} = $settings{$role}{$access};
 7871:                             }
 7872:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7873:                             my $access = $1;
 7874:                             $displaydiv{$access} = 'inline';
 7875:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7876:                                 $selected{$access} = $settings{$role}{$access};
 7877:                             }
 7878:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7879:                             $displaydiv{'priv'} = 'none';
 7880:                         }
 7881:                     }
 7882:                 } else {
 7883:                     $indomcheck = ' checked="checked"';
 7884:                     $indomvis = ' style="display:block"';
 7885:                     $incrsvis = ' style="display:none"';
 7886:                 }
 7887:             } else {
 7888:                 $indomcheck = ' checked="checked"';
 7889:                 $indomvis = ' style="display:block"';
 7890:                 $incrsvis = ' style="display:none"';
 7891:             }
 7892:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7893:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7894:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7895:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7896:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7897:                       '<span>'.('&nbsp;'x2).
 7898:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7899:                       $lt{'udd'}.'</label><span></p>'.
 7900:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7901:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7902:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7903:             foreach my $access (@accesstypes) {
 7904:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7905:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7906:                 if ($access eq 'status') {
 7907:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7908:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7909:                                                                         $othertitle,$usertypes,$types,$disabled).
 7910:                               '</div>');
 7911:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7912:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7913:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7914:                                                                  \%domhelpdesk,$disabled).
 7915:                               '</div>');
 7916:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7917:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7918:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7919:                                                                  \%domhelpdesk,$disabled).
 7920:                               '</div>');
 7921:                 }
 7922:                 $r->print('</p>');
 7923:             }
 7924:             $r->print('</div></fieldset>');
 7925:             my %full=();
 7926:             my %levels= (
 7927:                          course => {},
 7928:                          domain => {},
 7929:                          system => {},
 7930:                         );
 7931:             my %levelscurrent=(
 7932:                                course => {},
 7933:                                domain => {},
 7934:                                system => {},
 7935:                               );
 7936:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7937:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7938:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7939:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7940:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7941:         }
 7942:         if ($permission->{'owner'}) {
 7943:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7944:         }
 7945:     } else {
 7946:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7947:     }
 7948:     # Form Footer
 7949:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7950:              .'</form>');
 7951:     return;
 7952: }
 7953: 
 7954: sub domain_adhoc_access {
 7955:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7956:     my %domusage;
 7957:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7958:     foreach my $role (keys(%{$roles})) {
 7959:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7960:             my $access = $domcurrent->{$role}{'access'};
 7961:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7962:                 $access = 'all';
 7963:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 7964:                                                                                           &Apache::lonnet::plaintext('da'));
 7965:             } elsif ($access eq 'status') {
 7966:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7967:                     my @shown;
 7968:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7969:                         unless ($type eq 'default') {
 7970:                             if ($usertypes->{$type}) {
 7971:                                 push(@shown,$usertypes->{$type});
 7972:                             }
 7973:                         }
 7974:                     }
 7975:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7976:                         push(@shown,$othertitle);
 7977:                     }
 7978:                     if (@shown) {
 7979:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7980:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 7981:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 7982:                     } else {
 7983:                         $domusage{$role} = &mt('No one in the domain');
 7984:                     }
 7985:                 }
 7986:             } elsif ($access eq 'inc') {
 7987:                 my @dominc = ();
 7988:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7989:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7990:                         my ($uname,$udom) = split(/:/,$user);
 7991:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7992:                     }
 7993:                     my $showninc = join(', ',@dominc);
 7994:                     if ($showninc ne '') {
 7995:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 7996:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 7997:                     } else {
 7998:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7999:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 8000:                     }
 8001:                 }
 8002:             } elsif ($access eq 'exc') {
 8003:                 my @domexc = ();
 8004:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 8005:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 8006:                         my ($uname,$udom) = split(/:/,$user);
 8007:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 8008:                     }
 8009:                 }
 8010:                 my $shownexc = join(', ',@domexc);
 8011:                 if ($shownexc ne '') {
 8012:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 8013:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 8014:                 } else {
 8015:                     $domusage{$role} = &mt('No one in the domain');
 8016:                 }
 8017:             } elsif ($access eq 'none') {
 8018:                 $domusage{$role} = &mt('No one in the domain');
 8019:             } elsif ($access eq 'dh') {
 8020:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 8021:             } elsif ($access eq 'da') {
 8022:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 8023:             } elsif ($access eq 'all') {
 8024:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 8025:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 8026:             }
 8027:         } else {
 8028:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 8029:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 8030:         }
 8031:     }
 8032:     return %domusage;
 8033: }
 8034: 
 8035: sub get_domain_customroles {
 8036:     my ($cdom,$confname) = @_;
 8037:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 8038:     my %customroles;
 8039:     foreach my $key (keys(%existing)) {
 8040:         if ($key=~/^rolesdef\_(\w+)$/) {
 8041:             my $rolename = $1;
 8042:             my %privs;
 8043:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 8044:             $customroles{$rolename} = \%privs;
 8045:         }
 8046:     }
 8047:     return %customroles;
 8048: }
 8049: 
 8050: sub role_priv_table {
 8051:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 8052:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 8053:                    (ref($levelscurrent) eq 'HASH'));
 8054:     my %lt=&Apache::lonlocal::texthash (
 8055:                     'crl'  => 'Course Level Privilege',
 8056:                     'def'  => 'Domain Defaults',
 8057:                     'ove'  => 'Override in Course',
 8058:                     'ine'  => 'In effect',
 8059:                     'dis'  => 'Disabled',
 8060:                     'ena'  => 'Enabled',
 8061:                    );
 8062:     if ($crstype eq 'Community') {
 8063:         $lt{'ove'} = 'Override in Community',
 8064:     }
 8065:     my @status = ('Disabled','Enabled');
 8066:     my (%on,%off);
 8067:     if (ref($overridden) eq 'HASH') {
 8068:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 8069:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 8070:         }
 8071:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 8072:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 8073:         }
 8074:     }
 8075:     my $output=&Apache::loncommon::start_data_table().
 8076:                &Apache::loncommon::start_data_table_header_row().
 8077:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 8078:                '</th><th>'.$lt{'ine'}.'</th>'.
 8079:                &Apache::loncommon::end_data_table_header_row();
 8080:     foreach my $priv (sort(keys(%{$full}))) {
 8081:         next unless ($levels->{'course'}{$priv});
 8082:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 8083:         my ($default,$ineffect);
 8084:         if ($levelscurrent->{'course'}{$priv}) {
 8085:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8086:             $ineffect = $default;
 8087:         }
 8088:         my ($customstatus,$checked);
 8089:         $output .= &Apache::loncommon::start_data_table_row().
 8090:                    '<td>'.$privtext.'</td>'.
 8091:                    '<td>'.$default.'</td><td>';
 8092:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 8093:             if ($permission->{'owner'}) {
 8094:                 $checked = ' checked="checked"';
 8095:             }
 8096:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 8097:             $ineffect = $customstatus;
 8098:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 8099:             if ($permission->{'owner'}) {
 8100:                 $checked = ' checked="checked"';
 8101:             }
 8102:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8103:             $ineffect = $customstatus;
 8104:         }
 8105:         if ($permission->{'owner'}) {
 8106:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 8107:         } else {
 8108:             $output .= $customstatus;
 8109:         }
 8110:         $output .= '</td><td>'.$ineffect.'</td>'.
 8111:                    &Apache::loncommon::end_data_table_row();
 8112:     }
 8113:     $output .= &Apache::loncommon::end_data_table();
 8114:     return $output;
 8115: }
 8116: 
 8117: sub get_adhocrole_settings {
 8118:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 8119:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 8120:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 8121:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 8122:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 8123:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 8124:             $settings->{$role}{'access'} = $curraccess;
 8125:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 8126:                 my @status = split(/,/,$rest);
 8127:                 my @currstatus;
 8128:                 foreach my $type (@status) {
 8129:                     if ($type eq 'default') {
 8130:                         push(@currstatus,$type);
 8131:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8132:                         push(@currstatus,$type);
 8133:                     }
 8134:                 }
 8135:                 if (@currstatus) {
 8136:                     $settings->{$role}{$curraccess} = \@currstatus;
 8137:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8138:                     my @personnel = split(/,/,$rest);
 8139:                     $settings->{$role}{$curraccess} = \@personnel;
 8140:                 }
 8141:             }
 8142:         }
 8143:     }
 8144:     foreach my $role (keys(%{$customroles})) {
 8145:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 8146:             my %currentprivs;
 8147:             if (ref($customroles->{$role}) eq 'HASH') {
 8148:                 if (exists($customroles->{$role}{'course'})) {
 8149:                     my %full=();
 8150:                     my %levels= (
 8151:                                   course => {},
 8152:                                   domain => {},
 8153:                                   system => {},
 8154:                                 );
 8155:                     my %levelscurrent=(
 8156:                                         course => {},
 8157:                                         domain => {},
 8158:                                         system => {},
 8159:                                       );
 8160:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 8161:                     %currentprivs = %{$levelscurrent{'course'}};
 8162:                 }
 8163:             }
 8164:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 8165:                 next if ($item eq '');
 8166:                 my ($rule,$rest) = split(/=/,$item);
 8167:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 8168:                 foreach my $priv (split(/:/,$rest)) {
 8169:                     if ($priv ne '') {
 8170:                         if ($rule eq 'off') {
 8171:                             push(@{$overridden->{$role}{'off'}},$priv);
 8172:                             if ($currentprivs{$priv}) {
 8173:                                 push(@{$settings->{$role}{'off'}},$priv);
 8174:                             }
 8175:                         } else {
 8176:                             push(@{$overridden->{$role}{'on'}},$priv);
 8177:                             unless ($currentprivs{$priv}) {
 8178:                                 push(@{$settings->{$role}{'on'}},$priv);
 8179:                             }
 8180:                         }
 8181:                     }
 8182:                 }
 8183:             }
 8184:         }
 8185:     }
 8186:     return;
 8187: }
 8188: 
 8189: sub update_helpdeskaccess {
 8190:     my ($r,$permission,$brcrum) = @_;
 8191:     my $helpitem = 'Course_Helpdesk_Access';
 8192:     push (@{$brcrum},
 8193:              {href => '/adm/createuser?action=helpdesk',
 8194:               text => 'Helpdesk Access',
 8195:               help => $helpitem},
 8196:              {href => '/adm/createuser?action=helpdesk',
 8197:               text => 'Result',
 8198:               help => $helpitem}
 8199:          );
 8200:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8201:     my $args = { bread_crumbs           => $brcrum,
 8202:                  bread_crumbs_component => $bread_crumbs_component};
 8203: 
 8204:     # print page header
 8205:     $r->print(&header('',$args));
 8206:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 8207:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 8208:         return;
 8209:     }
 8210:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 8211:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8212:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8213:     my $confname = $cdom.'-domainconfig';
 8214:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8215:     my $crstype = &Apache::loncommon::course_type();
 8216:     my %customroles = &get_domain_customroles($cdom,$confname);
 8217:     my (%settings,%overridden);
 8218:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8219:                             $types,\%customroles,\%settings,\%overridden);
 8220:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8221:     my (%changed,%storehash,@todelete);
 8222: 
 8223:     if (keys(%customroles)) {
 8224:         my (%newsettings,@incrs);
 8225:         foreach my $role (keys(%customroles)) {
 8226:             $newsettings{$role} = {
 8227:                                     access => '',
 8228:                                     status => '',
 8229:                                     exc    => '',
 8230:                                     inc    => '',
 8231:                                     on     => '',
 8232:                                     off    => '',
 8233:                                   };
 8234:             my %current;
 8235:             if (ref($settings{$role}) eq 'HASH') {
 8236:                 %current = %{$settings{$role}};
 8237:             }
 8238:             if (ref($overridden{$role}) eq 'HASH') {
 8239:                 $current{'overridden'} = $overridden{$role};
 8240:             }
 8241:             if ($env{'form.'.$role.'_incrs'}) {
 8242:                 my $access = $env{'form.'.$role.'_access'};
 8243:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 8244:                     push(@incrs,$role);
 8245:                     unless ($current{'access'} eq $access) {
 8246:                         $changed{$role}{'access'} = 1;
 8247:                         $storehash{'internal.adhoc.'.$role} = $access;
 8248:                     }
 8249:                     if ($access eq 'status') {
 8250:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 8251:                         my @stored;
 8252:                         my @shownstatus;
 8253:                         if (ref($types) eq 'ARRAY') {
 8254:                             foreach my $type (sort(@statuses)) {
 8255:                                 if ($type eq 'default') {
 8256:                                     push(@stored,$type);
 8257:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8258:                                     push(@stored,$type);
 8259:                                     push(@shownstatus,$usertypes->{$type});
 8260:                                 }
 8261:                             }
 8262:                             if (grep(/^default$/,@statuses)) {
 8263:                                 push(@shownstatus,$othertitle);
 8264:                             }
 8265:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8266:                         }
 8267:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 8268:                         if (ref($current{'status'}) eq 'ARRAY') {
 8269:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 8270:                             if (@diffs) {
 8271:                                 $changed{$role}{'status'} = 1;
 8272:                             }
 8273:                         } elsif (@stored) {
 8274:                             $changed{$role}{'status'} = 1;
 8275:                         }
 8276:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 8277:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 8278:                         my @newspecstaff;
 8279:                         my @stored;
 8280:                         my @currstaff;
 8281:                         foreach my $person (sort(@personnel)) {
 8282:                             if ($domhelpdesk{$person}) {
 8283:                                 push(@stored,$person);
 8284:                             }
 8285:                         }
 8286:                         if (ref($current{$access}) eq 'ARRAY') {
 8287:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 8288:                             if (@diffs) {
 8289:                                 $changed{$role}{$access} = 1;
 8290:                             }
 8291:                         } elsif (@stored) {
 8292:                             $changed{$role}{$access} = 1;
 8293:                         }
 8294:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8295:                         foreach my $person (@stored) {
 8296:                             my ($uname,$udom) = split(/:/,$person);
 8297:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 8298:                         }
 8299:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 8300:                     }
 8301:                     $newsettings{$role}{'access'} = $access;
 8302:                 }
 8303:             } else {
 8304:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 8305:                     $changed{$role}{'access'} = 1;
 8306:                     $newsettings{$role} = {};
 8307:                     push(@todelete,'internal.adhoc.'.$role);
 8308:                 }
 8309:             }
 8310:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 8311:                 if (ref($current{'overridden'}) eq 'HASH') {
 8312:                     push(@todelete,'internal.adhocpriv.'.$role);
 8313:                 }
 8314:             } else {
 8315:                 my %full=();
 8316:                 my %levels= (
 8317:                              course => {},
 8318:                              domain => {},
 8319:                              system => {},
 8320:                             );
 8321:                 my %levelscurrent=(
 8322:                                    course => {},
 8323:                                    domain => {},
 8324:                                    system => {},
 8325:                                   );
 8326:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 8327:                 my (@updatedon,@updatedoff,@override);
 8328:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 8329:                 if (@override) {
 8330:                     foreach my $priv (sort(keys(%full))) {
 8331:                         next unless ($levels{'course'}{$priv});
 8332:                         if (grep(/^\Q$priv\E$/,@override)) {
 8333:                             if ($levelscurrent{'course'}{$priv}) {
 8334:                                 push(@updatedoff,$priv);
 8335:                             } else {
 8336:                                 push(@updatedon,$priv);
 8337:                             }
 8338:                         }
 8339:                     }
 8340:                 }
 8341:                 if (@updatedon) {
 8342:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 8343:                 }
 8344:                 if (@updatedoff) {
 8345:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 8346:                 }
 8347:                 if (ref($current{'overridden'}) eq 'HASH') {
 8348:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 8349:                         if (@updatedon) {
 8350:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 8351:                             if (@diffs) {
 8352:                                 $changed{$role}{'on'} = 1;
 8353:                             }
 8354:                         } else {
 8355:                             $changed{$role}{'on'} = 1;
 8356:                         }
 8357:                     } elsif (@updatedon) {
 8358:                         $changed{$role}{'on'} = 1;
 8359:                     }
 8360:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 8361:                         if (@updatedoff) {
 8362:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 8363:                             if (@diffs) {
 8364:                                 $changed{$role}{'off'} = 1;
 8365:                             }
 8366:                         } else {
 8367:                             $changed{$role}{'off'} = 1;
 8368:                         }
 8369:                     } elsif (@updatedoff) {
 8370:                         $changed{$role}{'off'} = 1;
 8371:                     }
 8372:                 } else {
 8373:                     if (@updatedon) {
 8374:                         $changed{$role}{'on'} = 1;
 8375:                     }
 8376:                     if (@updatedoff) {
 8377:                         $changed{$role}{'off'} = 1;
 8378:                     }
 8379:                 }
 8380:                 if (ref($changed{$role}) eq 'HASH') {
 8381:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8382:                         my $newpriv;
 8383:                         if (@updatedon) {
 8384:                             $newpriv = 'on='.join(':',@updatedon);
 8385:                         }
 8386:                         if (@updatedoff) {
 8387:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8388:                         }
 8389:                         if ($newpriv eq '') {
 8390:                             push(@todelete,'internal.adhocpriv.'.$role);
 8391:                         } else {
 8392:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8393:                         }
 8394:                     }
 8395:                 }
 8396:             }
 8397:         }
 8398:         if (@incrs) {
 8399:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8400:         } elsif (@todelete) {
 8401:             push(@todelete,'internal.adhocaccess');
 8402:         }
 8403:         if (keys(%changed)) {
 8404:             my ($putres,$delres);
 8405:             if (keys(%storehash)) {
 8406:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8407:                 my %newenvhash;
 8408:                 foreach my $key (keys(%storehash)) {
 8409:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8410:                 }
 8411:                 &Apache::lonnet::appenv(\%newenvhash);
 8412:             }
 8413:             if (@todelete) {
 8414:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8415:                 foreach my $key (@todelete) {
 8416:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8417:                 }
 8418:             }
 8419:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8420:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8421:                 my (%domcurrent,%ordered,%description,%domusage);
 8422:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8423:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8424:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8425:                     }
 8426:                 }
 8427:                 my $count = 0;
 8428:                 foreach my $role (sort(keys(%customroles))) {
 8429:                     my ($order,$desc);
 8430:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8431:                         $order = $domcurrent{$role}{'order'};
 8432:                         $desc = $domcurrent{$role}{'desc'};
 8433:                     }
 8434:                     if ($order eq '') {
 8435:                         $order = $count;
 8436:                     }
 8437:                     $ordered{$order} = $role;
 8438:                     if ($desc ne '') {
 8439:                         $description{$role} = $desc;
 8440:                     } else {
 8441:                         $description{$role}= $role;
 8442:                     }
 8443:                     $count++;
 8444:                 }
 8445:                 my @roles_by_num = ();
 8446:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8447:                     push(@roles_by_num,$ordered{$item});
 8448:                 }
 8449:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8450:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8451:                 $r->print('<ul>');
 8452:                 foreach my $role (@roles_by_num) {
 8453:                     next unless (ref($changed{$role}) eq 'HASH');
 8454:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8455:                               '<ul>');
 8456:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8457:                         $r->print('<li>');
 8458:                         if ($env{'form.'.$role.'_incrs'}) {
 8459:                             if ($newsettings{$role}{'access'} eq 'all') {
 8460:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8461:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 8462:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8463:                                               &Apache::lonnet::plaintext('dh')));
 8464:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 8465:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8466:                                               &Apache::lonnet::plaintext('da')));
 8467:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8468:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8469:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8470:                                 if ($newsettings{$role}{'status'}) {
 8471:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8472:                                     if (split(/,/,$rest) > 1) {
 8473:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8474:                                                       $newsettings{$role}{'status'}));
 8475:                                     } else {
 8476:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8477:                                                       $newsettings{$role}{'status'}));
 8478:                                     }
 8479:                                 } else {
 8480:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8481:                                 }
 8482:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8483:                                 if ($newsettings{$role}{'exc'}) {
 8484:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8485:                                 } else {
 8486:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8487:                                 }
 8488:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8489:                                 if ($newsettings{$role}{'inc'}) {
 8490:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8491:                                 } else {
 8492:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8493:                                 }
 8494:                             }
 8495:                         } else {
 8496:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8497:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8498:                         }
 8499:                         $r->print('</li>');
 8500:                     }
 8501:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8502:                         if ($changed{$role}{'off'}) {
 8503:                             if ($newsettings{$role}{'off'}) {
 8504:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8505:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8506:                             } else {
 8507:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8508:                             }
 8509:                         }
 8510:                         if ($changed{$role}{'on'}) {
 8511:                             if ($newsettings{$role}{'on'}) {
 8512:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8513:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8514:                             } else {
 8515:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8516:                             }
 8517:                         }
 8518:                     }
 8519:                     $r->print('</ul></li>');
 8520:                 }
 8521:                 $r->print('</ul>');
 8522:             }
 8523:         } else {
 8524:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8525:         }
 8526:     }
 8527:     return;
 8528: }
 8529: 
 8530: #-------------------------------------------------- functions for &phase_two
 8531: sub user_search_result {
 8532:     my ($context,$srch) = @_;
 8533:     my %allhomes;
 8534:     my %inst_matches;
 8535:     my %srch_results;
 8536:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8537:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8538:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8539:         $response = &mt('Invalid search.');
 8540:     }
 8541:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8542:         $response = &mt('Invalid search.');
 8543:     }
 8544:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8545:         $response = &mt('Invalid search.');
 8546:     }
 8547:     if ($srch->{'srchterm'} eq '') {
 8548:         $response = &mt('You must enter a search term.');
 8549:     }
 8550:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8551:         $response = &mt('Your search term must contain more than just spaces.');
 8552:     }
 8553:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8554:         if (($srch->{'srchdomain'} eq '') || 
 8555: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8556:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8557:         }
 8558:     }
 8559:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8560:         ($srch->{'srchin'} eq 'alc')) {
 8561:         if ($srch->{'srchby'} eq 'uname') {
 8562:             my $unamecheck = $srch->{'srchterm'};
 8563:             if ($srch->{'srchtype'} eq 'contains') {
 8564:                 if ($unamecheck !~ /^\w/) {
 8565:                     $unamecheck = 'a'.$unamecheck; 
 8566:                 }
 8567:             }
 8568:             if ($unamecheck !~ /^$match_username$/) {
 8569:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8570:             }
 8571:         }
 8572:     }
 8573:     if ($response ne '') {
 8574:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8575:     }
 8576:     if ($srch->{'srchin'} eq 'instd') {
 8577:         my $instd_chk = &instdirectorysrch_check($srch);
 8578:         if ($instd_chk ne 'ok') {
 8579:             my $domd_chk = &domdirectorysrch_check($srch);
 8580:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8581:             if ($domd_chk eq 'ok') {
 8582:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 8583:             }
 8584:             $response .= '<br />';
 8585:         }
 8586:     } else {
 8587:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8588:             my $domd_chk = &domdirectorysrch_check($srch);
 8589:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 8590:                 my $instd_chk = &instdirectorysrch_check($srch);
 8591:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8592:                 if ($instd_chk eq 'ok') {
 8593:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 8594:                 }
 8595:                 $response .= '<br />';
 8596:             }
 8597:         }
 8598:     }
 8599:     if ($response ne '') {
 8600:         return ($currstate,$response);
 8601:     }
 8602:     if ($srch->{'srchby'} eq 'uname') {
 8603:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8604:             if ($env{'form.forcenew'}) {
 8605:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8606:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8607:                     if ($uhome eq 'no_host') {
 8608:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8609:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8610:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8611:                     } else {
 8612:                         $currstate = 'modify';
 8613:                     }
 8614:                 } else {
 8615:                     $currstate = 'modify';
 8616:                 }
 8617:             } else {
 8618:                 if ($srch->{'srchin'} eq 'dom') {
 8619:                     if ($srch->{'srchtype'} eq 'exact') {
 8620:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8621:                         if ($uhome eq 'no_host') {
 8622:                             ($currstate,$response,$forcenewuser) =
 8623:                                 &build_search_response($context,$srch,%srch_results);
 8624:                         } else {
 8625:                             $currstate = 'modify';
 8626:                             if ($env{'form.action'} eq 'accesslogs') {
 8627:                                 $currstate = 'activity';
 8628:                             }
 8629:                             my $uname = $srch->{'srchterm'};
 8630:                             my $udom = $srch->{'srchdomain'};
 8631:                             $srch_results{$uname.':'.$udom} =
 8632:                                 { &Apache::lonnet::get('environment',
 8633:                                                        ['firstname',
 8634:                                                         'lastname',
 8635:                                                         'permanentemail'],
 8636:                                                          $udom,$uname)
 8637:                                 };
 8638:                         }
 8639:                     } else {
 8640:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8641:                         ($currstate,$response,$forcenewuser) =
 8642:                             &build_search_response($context,$srch,%srch_results);
 8643:                     }
 8644:                 } else {
 8645:                     my $courseusers = &get_courseusers();
 8646:                     if ($srch->{'srchtype'} eq 'exact') {
 8647:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8648:                             $currstate = 'modify';
 8649:                         } else {
 8650:                             ($currstate,$response,$forcenewuser) =
 8651:                                 &build_search_response($context,$srch,%srch_results);
 8652:                         }
 8653:                     } else {
 8654:                         foreach my $user (keys(%$courseusers)) {
 8655:                             my ($cuname,$cudomain) = split(/:/,$user);
 8656:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8657:                                 my $matched = 0;
 8658:                                 if ($srch->{'srchtype'} eq 'begins') {
 8659:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8660:                                         $matched = 1;
 8661:                                     }
 8662:                                 } else {
 8663:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8664:                                         $matched = 1;
 8665:                                     }
 8666:                                 }
 8667:                                 if ($matched) {
 8668:                                     $srch_results{$user} = 
 8669: 					{&Apache::lonnet::get('environment',
 8670: 							     ['firstname',
 8671: 							      'lastname',
 8672: 							      'permanentemail'],
 8673: 							      $cudomain,$cuname)};
 8674:                                 }
 8675:                             }
 8676:                         }
 8677:                         ($currstate,$response,$forcenewuser) =
 8678:                             &build_search_response($context,$srch,%srch_results);
 8679:                     }
 8680:                 }
 8681:             }
 8682:         } elsif ($srch->{'srchin'} eq 'alc') {
 8683:             $currstate = 'query';
 8684:         } elsif ($srch->{'srchin'} eq 'instd') {
 8685:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8686:             if ($dirsrchres eq 'ok') {
 8687:                 ($currstate,$response,$forcenewuser) = 
 8688:                     &build_search_response($context,$srch,%srch_results);
 8689:             } else {
 8690:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8691:                 $response = '<span class="LC_warning">'.
 8692:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8693:                     '</span><br />'.
 8694:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8695:                     '<br />'; 
 8696:             }
 8697:         }
 8698:     } else {
 8699:         if ($srch->{'srchin'} eq 'dom') {
 8700:             %srch_results = &Apache::lonnet::usersearch($srch);
 8701:             ($currstate,$response,$forcenewuser) = 
 8702:                 &build_search_response($context,$srch,%srch_results); 
 8703:         } elsif ($srch->{'srchin'} eq 'crs') {
 8704:             my $courseusers = &get_courseusers(); 
 8705:             foreach my $user (keys(%$courseusers)) {
 8706:                 my ($uname,$udom) = split(/:/,$user);
 8707:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8708:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8709:                 if ($srch->{'srchby'} eq 'lastname') {
 8710:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8711:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8712:                         (($srch->{'srchtype'} eq 'begins') &&
 8713:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8714:                         (($srch->{'srchtype'} eq 'contains') &&
 8715:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8716:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8717:                                             lastname => $names{'lastname'},
 8718:                                             permanentemail => $emails{'permanentemail'},
 8719:                                            };
 8720:                     }
 8721:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8722:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8723:                     $srchlast =~ s/\s+$//;
 8724:                     $srchfirst =~ s/^\s+//;
 8725:                     if ($srch->{'srchtype'} eq 'exact') {
 8726:                         if (($names{'lastname'} eq $srchlast) &&
 8727:                             ($names{'firstname'} eq $srchfirst)) {
 8728:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8729:                                                 lastname => $names{'lastname'},
 8730:                                                 permanentemail => $emails{'permanentemail'},
 8731: 
 8732:                                            };
 8733:                         }
 8734:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8735:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8736:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8737:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8738:                                                 lastname => $names{'lastname'},
 8739:                                                 permanentemail => $emails{'permanentemail'},
 8740:                                                };
 8741:                         }
 8742:                     } else {
 8743:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 8744:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 8745:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8746:                                                 lastname => $names{'lastname'},
 8747:                                                 permanentemail => $emails{'permanentemail'},
 8748:                                                };
 8749:                         }
 8750:                     }
 8751:                 }
 8752:             }
 8753:             ($currstate,$response,$forcenewuser) = 
 8754:                 &build_search_response($context,$srch,%srch_results); 
 8755:         } elsif ($srch->{'srchin'} eq 'alc') {
 8756:             $currstate = 'query';
 8757:         } elsif ($srch->{'srchin'} eq 'instd') {
 8758:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8759:             if ($dirsrchres eq 'ok') {
 8760:                 ($currstate,$response,$forcenewuser) = 
 8761:                     &build_search_response($context,$srch,%srch_results);
 8762:             } else {
 8763:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8764:                 $response = '<span class="LC_warning">'.
 8765:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8766:                     '</span><br />'.
 8767:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8768:                     '<br />';
 8769:             }
 8770:         }
 8771:     }
 8772:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8773: }
 8774: 
 8775: sub domdirectorysrch_check {
 8776:     my ($srch) = @_;
 8777:     my $response;
 8778:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8779:                                              ['directorysrch'],$srch->{'srchdomain'});
 8780:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8781:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8782:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8783:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8784:         }
 8785:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8786:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8787:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8788:             }
 8789:         }
 8790:     }
 8791:     return 'ok';
 8792: }
 8793: 
 8794: sub instdirectorysrch_check {
 8795:     my ($srch) = @_;
 8796:     my $can_search = 0;
 8797:     my $response;
 8798:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8799:                                              ['directorysrch'],$srch->{'srchdomain'});
 8800:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8801:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8802:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8803:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8804:         }
 8805:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8806:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8807:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8808:             }
 8809:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8810:             if (!@usertypes) {
 8811:                 push(@usertypes,'default');
 8812:             }
 8813:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8814:                 foreach my $type (@usertypes) {
 8815:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8816:                         $can_search = 1;
 8817:                         last;
 8818:                     }
 8819:                 }
 8820:             }
 8821:             if (!$can_search) {
 8822:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8823:                 my @longtypes; 
 8824:                 foreach my $item (@usertypes) {
 8825:                     if (defined($insttypes->{$item})) { 
 8826:                         push (@longtypes,$insttypes->{$item});
 8827:                     } elsif ($item eq 'default') {
 8828:                         push (@longtypes,&mt('other')); 
 8829:                     }
 8830:                 }
 8831:                 my $insttype_str = join(', ',@longtypes); 
 8832:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8833:             }
 8834:         } else {
 8835:             $can_search = 1;
 8836:         }
 8837:     } else {
 8838:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8839:     }
 8840:     my %longtext = &Apache::lonlocal::texthash (
 8841:                        uname     => 'username',
 8842:                        lastfirst => 'last name, first name',
 8843:                        lastname  => 'last name',
 8844:                        contains  => 'contains',
 8845:                        exact     => 'as exact match to',
 8846:                        begins    => 'begins with',
 8847:                    );
 8848:     if ($can_search) {
 8849:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8850:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8851:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8852:             }
 8853:         } else {
 8854:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8855:         }
 8856:     }
 8857:     if ($can_search) {
 8858:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8859:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8860:                 return 'ok';
 8861:             } else {
 8862:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8863:             }
 8864:         } else {
 8865:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8866:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8867:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 8868:                 return 'ok';
 8869:             } else {
 8870:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8871:             }
 8872:         }
 8873:     }
 8874: }
 8875: 
 8876: sub get_courseusers {
 8877:     my %advhash;
 8878:     my $classlist = &Apache::loncoursedata::get_classlist();
 8879:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8880:     foreach my $role (sort(keys(%coursepersonnel))) {
 8881:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8882: 	    if (!exists($classlist->{$user})) {
 8883: 		$classlist->{$user} = [];
 8884: 	    }
 8885:         }
 8886:     }
 8887:     return $classlist;
 8888: }
 8889: 
 8890: sub build_search_response {
 8891:     my ($context,$srch,%srch_results) = @_;
 8892:     my ($currstate,$response,$forcenewuser);
 8893:     my %names = (
 8894:           'uname'     => 'username',
 8895:           'lastname'  => 'last name',
 8896:           'lastfirst' => 'last name, first name',
 8897:           'crs'       => 'this course',
 8898:           'dom'       => 'LON-CAPA domain',
 8899:           'instd'     => 'the institutional directory for domain',
 8900:     );
 8901: 
 8902:     my %single = (
 8903:                    begins   => 'A match',
 8904:                    contains => 'A match',
 8905:                    exact    => 'An exact match',
 8906:                  );
 8907:     my %nomatch = (
 8908:                    begins   => 'No match',
 8909:                    contains => 'No match',
 8910:                    exact    => 'No exact match',
 8911:                   );
 8912:     if (keys(%srch_results) > 1) {
 8913:         $currstate = 'select';
 8914:     } else {
 8915:         if (keys(%srch_results) == 1) {
 8916:             if ($env{'form.action'} eq 'accesslogs') {
 8917:                 $currstate = 'activity';
 8918:             } else {
 8919:                 $currstate = 'modify';
 8920:             }
 8921:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8922:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8923:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8924:             }
 8925:         } else { # Search has nothing found. Prepare message to user.
 8926:             $response = '<span class="LC_warning">';
 8927:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8928:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8929:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8930:                                  &display_domain_info($srch->{'srchdomain'}));
 8931:             } else {
 8932:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8933:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8934:             }
 8935:             $response .= '</span>';
 8936: 
 8937:             if ($srch->{'srchin'} ne 'alc') {
 8938:                 $forcenewuser = 1;
 8939:                 my $cansrchinst = 0; 
 8940:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
 8941:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8942:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8943:                         if ($domconfig{'directorysrch'}{'available'}) {
 8944:                             $cansrchinst = 1;
 8945:                         } 
 8946:                     }
 8947:                 }
 8948:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8949:                      ($srch->{'srchby'} eq 'lastname')) &&
 8950:                     ($srch->{'srchin'} eq 'dom')) {
 8951:                     if ($cansrchinst) {
 8952:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8953:                     }
 8954:                 }
 8955:                 if ($srch->{'srchin'} eq 'crs') {
 8956:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8957:                 }
 8958:             }
 8959:             my $createdom = $env{'request.role.domain'};
 8960:             if ($context eq 'requestcrs') {
 8961:                 if ($env{'form.coursedom'} ne '') {
 8962:                     $createdom = $env{'form.coursedom'};
 8963:                 }
 8964:             }
 8965:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8966:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8967:                 my $cancreate =
 8968:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8969:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8970:                 if ($cancreate) {
 8971:                     my $showdom = &display_domain_info($createdom); 
 8972:                     $response .= '<br /><br />'
 8973:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8974:                                 .'<br />';
 8975:                     if ($context eq 'requestcrs') {
 8976:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8977:                     } else {
 8978:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8979:                     }
 8980:                     $response .='<ul><li>'
 8981:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8982:                                 .'</li><li>'
 8983:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8984:                                 .'</li><li>'
 8985:                                 .&mt('Provide the proposed username')
 8986:                                 .'</li><li>'
 8987:                                 .&mt("Click 'Search'")
 8988:                                 .'</li></ul><br />';
 8989:                 } else {
 8990:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8991:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8992:                         $response .= '<br /><br />';
 8993:                         if ($context eq 'requestcrs') {
 8994:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8995:                         } else {
 8996:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 8997:                         }
 8998:                         $response .= '<br />'
 8999:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 9000:                                         ,' <a'.$helplink.'>'
 9001:                                         ,'</a>')
 9002:                                      .'<br />';
 9003:                     }
 9004:                 }
 9005:             }
 9006:         }
 9007:     }
 9008:     return ($currstate,$response,$forcenewuser);
 9009: }
 9010: 
 9011: sub display_domain_info {
 9012:     my ($dom) = @_;
 9013:     my $output = $dom;
 9014:     if ($dom ne '') { 
 9015:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 9016:         if ($domdesc ne '') {
 9017:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 9018:         }
 9019:     }
 9020:     return $output;
 9021: }
 9022: 
 9023: sub crumb_utilities {
 9024:     my %elements = (
 9025:        crtuser => {
 9026:            srchterm => 'text',
 9027:            srchin => 'selectbox',
 9028:            srchby => 'selectbox',
 9029:            srchtype => 'selectbox',
 9030:            srchdomain => 'selectbox',
 9031:        },
 9032:        crtusername => {
 9033:            srchterm => 'text',
 9034:            srchdomain => 'selectbox',
 9035:        },
 9036:        docustom => {
 9037:            rolename => 'selectbox',
 9038:            newrolename => 'textbox',
 9039:        },
 9040:        studentform => {
 9041:            srchterm => 'text',
 9042:            srchin => 'selectbox',
 9043:            srchby => 'selectbox',
 9044:            srchtype => 'selectbox',
 9045:            srchdomain => 'selectbox',
 9046:        },
 9047:     );
 9048: 
 9049:     my $jsback .= qq|
 9050: function backPage(formname,prevphase,prevstate) {
 9051:     if (typeof prevphase == 'undefined') {
 9052:         formname.phase.value = '';
 9053:     }
 9054:     else {  
 9055:         formname.phase.value = prevphase;
 9056:     }
 9057:     if (typeof prevstate == 'undefined') {
 9058:         formname.currstate.value = '';
 9059:     }
 9060:     else {
 9061:         formname.currstate.value = prevstate;
 9062:     }
 9063:     formname.submit();
 9064: }
 9065: |;
 9066:     return ($jsback,\%elements);
 9067: }
 9068: 
 9069: sub course_level_table {
 9070:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 9071:     return unless (ref($inccourses) eq 'HASH');
 9072:     my $table = '';
 9073: # Custom Roles?
 9074: 
 9075:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9076:     my %lt=&Apache::lonlocal::texthash(
 9077:             'exs'  => "Existing sections",
 9078:             'new'  => "Define new section",
 9079:             'ssd'  => "Set Start Date",
 9080:             'sed'  => "Set End Date",
 9081:             'crl'  => "Course Level",
 9082:             'act'  => "Activate",
 9083:             'rol'  => "Role",
 9084:             'ext'  => "Extent",
 9085:             'grs'  => "Section",
 9086:             'crd'  => "Credits",
 9087:             'sta'  => "Start",
 9088:             'end'  => "End"
 9089:     );
 9090: 
 9091:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 9092: 	my $thiscourse=$protectedcourse;
 9093: 	$thiscourse=~s:_:/:g;
 9094: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 9095:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 9096: 	my $area=$coursedata{'description'};
 9097:         my $crstype=$coursedata{'type'};
 9098: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 9099: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 9100:         my %sections_count;
 9101:         if (defined($env{'request.course.id'})) {
 9102:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 9103:                 %sections_count = 
 9104: 		    &Apache::loncommon::get_sections($domain,$cnum);
 9105:             }
 9106:         }
 9107:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 9108: 	foreach my $role (@roles) {
 9109:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 9110: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 9111:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 9112:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9113:                                             $plrole,\%sections_count,\%lt,
 9114:                                             $showcredits,$defaultcredits,$crstype);
 9115:             } elsif ($env{'request.course.sec'} ne '') {
 9116:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 9117:                                              $env{'request.course.sec'})) {
 9118:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9119:                                                 $plrole,\%sections_count,\%lt,
 9120:                                                 $showcredits,$defaultcredits,$crstype);
 9121:                 }
 9122:             }
 9123:         }
 9124:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 9125:             foreach my $cust (sort(keys(%customroles))) {
 9126:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 9127:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 9128:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9129:                                             $cust,\%sections_count,\%lt,
 9130:                                             $showcredits,$defaultcredits,$crstype);
 9131:             }
 9132: 	}
 9133:     }
 9134:     return '' if ($table eq ''); # return nothing if there is nothing 
 9135:                                  # in the table
 9136:     my $result;
 9137:     if (!$env{'request.course.id'}) {
 9138:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 9139:     }
 9140:     $result .= 
 9141: &Apache::loncommon::start_data_table().
 9142: &Apache::loncommon::start_data_table_header_row().
 9143: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9144: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 9145:     if ($showcredits) {
 9146:         $result .= $lt{'crd'}.'</th>';
 9147:     }
 9148:     $result .=
 9149: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 9150: '<th>'.$lt{'end'}.'</th>'.
 9151: &Apache::loncommon::end_data_table_header_row().
 9152: $table.
 9153: &Apache::loncommon::end_data_table();
 9154:     return $result;
 9155: }
 9156: 
 9157: sub course_level_row {
 9158:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 9159:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 9160:     my $creditem;
 9161:     my $row = &Apache::loncommon::start_data_table_row().
 9162:               ' <td><input type="checkbox" name="act_'.
 9163:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 9164:               ' <td>'.$plrole.'</td>'."\n".
 9165:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 9166:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 9167:         $row .= 
 9168:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 9169:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 9170:     } else {
 9171:         $row .= '<td>&nbsp;</td>';
 9172:     }
 9173:     if (($role eq 'cc') || ($role eq 'co')) {
 9174:         $row .= '<td>&nbsp;</td>';
 9175:     } elsif ($env{'request.course.sec'} ne '') {
 9176:         $row .= ' <td><input type="hidden" value="'.
 9177:                 $env{'request.course.sec'}.'" '.
 9178:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 9179:                 $env{'request.course.sec'}.'</td>';
 9180:     } else {
 9181:         if (ref($sections_count) eq 'HASH') {
 9182:             my $currsec = 
 9183:                 &Apache::lonuserutils::course_sections($sections_count,
 9184:                                                        $protectedcourse.'_'.$role);
 9185:             $row .= '<td><table class="LC_createuser">'."\n".
 9186:                     '<tr class="LC_section_row">'."\n".
 9187:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 9188:                        $currsec.'</td>'."\n".
 9189:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 9190:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 9191:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 9192:                      '" value="" />'.
 9193:                      '<input type="hidden" '.
 9194:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 9195:                      '</tr></table></td>'."\n";
 9196:         } else {
 9197:             $row .= '<td><input type="text" size="10" '.
 9198:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 9199:         }
 9200:     }
 9201:     $row .= <<ENDTIMEENTRY;
 9202: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 9203: <a href=
 9204: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 9205: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 9206: <a href=
 9207: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 9208: ENDTIMEENTRY
 9209:     $row .= &Apache::loncommon::end_data_table_row();
 9210:     return $row;
 9211: }
 9212: 
 9213: sub course_level_dc {
 9214:     my ($dcdom,$showcredits) = @_;
 9215:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9216:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 9217:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 9218:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 9219:                       '<input type="hidden" name="dccourse" value="" />';
 9220:     my $courseform=&Apache::loncommon::selectcourse_link
 9221:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 9222:     my $credit_elem;
 9223:     if ($showcredits) {
 9224:         $credit_elem = 'credits';
 9225:     }
 9226:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 9227:     my %lt=&Apache::lonlocal::texthash(
 9228:                     'rol'  => "Role",
 9229:                     'grs'  => "Section",
 9230:                     'exs'  => "Existing sections",
 9231:                     'new'  => "Define new section", 
 9232:                     'sta'  => "Start",
 9233:                     'end'  => "End",
 9234:                     'ssd'  => "Set Start Date",
 9235:                     'sed'  => "Set End Date",
 9236:                     'scc'  => "Course/Community",
 9237:                     'crd'  => "Credits",
 9238:                   );
 9239:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 9240:                  &Apache::loncommon::start_data_table().
 9241:                  &Apache::loncommon::start_data_table_header_row().
 9242:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9243:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 9244:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 9245:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 9246:                  &Apache::loncommon::end_data_table_header_row();
 9247:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 9248:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 9249:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 9250:                      '<td valign="top"><br /><select name="role">'."\n";
 9251:     foreach my $role (@roles) {
 9252:         my $plrole=&Apache::lonnet::plaintext($role);
 9253:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 9254:     }
 9255:     if ( keys(%customroles) > 0) {
 9256:         foreach my $cust (sort(keys(%customroles))) {
 9257:             my $custrole='cr_cr_'.$env{'user.domain'}.
 9258:                     '_'.$env{'user.name'}.'_'.$cust;
 9259:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 9260:         }
 9261:     }
 9262:     $otheritems .= '</select></td><td>'.
 9263:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 9264:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 9265:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 9266:                      '<td>&nbsp;&nbsp;</td>'.
 9267:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 9268:                      '<input type="text" name="newsec" value="" />'.
 9269:                      '<input type="hidden" name="section" value="" />'.
 9270:                      '<input type="hidden" name="groups" value="" />'.
 9271:                      '<input type="hidden" name="crstype" value="" /></td>'.
 9272:                      '</tr></table></td>'."\n";
 9273:     if ($showcredits) {
 9274:         $otheritems .= '<td><br />'."\n".
 9275:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 9276:     }
 9277:     $otheritems .= <<ENDTIMEENTRY;
 9278: <td><br /><input type="hidden" name="start" value='' />
 9279: <a href=
 9280: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 9281: <td><br /><input type="hidden" name="end" value='' />
 9282: <a href=
 9283: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 9284: ENDTIMEENTRY
 9285:     $otheritems .= &Apache::loncommon::end_data_table_row().
 9286:                    &Apache::loncommon::end_data_table()."\n";
 9287:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 9288: }
 9289: 
 9290: sub update_selfenroll_config {
 9291:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 9292:     return unless (ref($currsettings) eq 'HASH');
 9293:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 9294:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9295:     my (%changes,%warning);
 9296:     my $curr_types;
 9297:     my %noedit;
 9298:     unless ($context eq 'domain') {
 9299:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 9300:     }
 9301:     if (ref($row) eq 'ARRAY') {
 9302:         foreach my $item (@{$row}) {
 9303:             next if ($noedit{$item});
 9304:             if ($item eq 'enroll_dates') {
 9305:                 my (%currenrolldate,%newenrolldate);
 9306:                 foreach my $type ('start','end') {
 9307:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 9308:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 9309:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 9310:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 9311:                     }
 9312:                 }
 9313:             } elsif ($item eq 'access_dates') {
 9314:                 my (%currdate,%newdate);
 9315:                 foreach my $type ('start','end') {
 9316:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 9317:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 9318:                     if ($newdate{$type} ne $currdate{$type}) {
 9319:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 9320:                     }
 9321:                 }
 9322:             } elsif ($item eq 'types') {
 9323:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 9324:                 if ($env{'form.selfenroll_all'}) {
 9325:                     if ($curr_types ne '*') {
 9326:                         $changes{'internal.selfenroll_types'} = '*';
 9327:                     } else {
 9328:                         next;
 9329:                     }
 9330:                 } else {
 9331:                     my %currdoms;
 9332:                     my @entries = split(/;/,$curr_types);
 9333:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 9334:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 9335:                     my $newnum = 0;
 9336:                     my @latesttypes;
 9337:                     foreach my $num (@activations) {
 9338:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 9339:                         if (@types > 0) {
 9340:                             @types = sort(@types);
 9341:                             my $typestr = join(',',@types);
 9342:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 9343:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9344:                             $currdoms{$typedom} = 1;
 9345:                             $newnum ++;
 9346:                         }
 9347:                     }
 9348:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 9349:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 9350:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 9351:                             if (@types > 0) {
 9352:                                 @types = sort(@types);
 9353:                                 my $typestr = join(',',@types);
 9354:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 9355:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 9356:                                 $currdoms{$typedom} = 1;
 9357:                                 $newnum ++;
 9358:                             }
 9359:                         }
 9360:                     }
 9361:                     if ($env{'form.selfenroll_newdom'} ne '') {
 9362:                         my $typedom = $env{'form.selfenroll_newdom'};
 9363:                         if ((!defined($currdoms{$typedom})) && 
 9364:                             (&Apache::lonnet::domain($typedom) ne '')) {
 9365:                             my $typestr;
 9366:                             my ($othertitle,$usertypes,$types) = 
 9367:                                 &Apache::loncommon::sorted_inst_types($typedom);
 9368:                             my $othervalue = 'any';
 9369:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 9370:                                 if (@{$types} > 0) {
 9371:                                     my @esc_types = map { &escape($_); } @{$types};
 9372:                                     $othervalue = 'other';
 9373:                                     $typestr = join(',',(@esc_types,$othervalue));
 9374:                                 }
 9375:                                 $typestr = $othervalue;
 9376:                             } else {
 9377:                                 $typestr = $othervalue;
 9378:                             } 
 9379:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9380:                             $newnum ++ ;
 9381:                         }
 9382:                     }
 9383:                     my $selfenroll_types = join(';',@latesttypes);
 9384:                     if ($selfenroll_types ne $curr_types) {
 9385:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9386:                     }
 9387:                 }
 9388:             } elsif ($item eq 'limit') {
 9389:                 my $newlimit = $env{'form.selfenroll_limit'};
 9390:                 my $newcap = $env{'form.selfenroll_cap'};
 9391:                 $newcap =~s/\s+//g;
 9392:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9393:                 $currlimit = 'none' if ($currlimit eq '');
 9394:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9395:                 if ($newlimit ne $currlimit) {
 9396:                     if ($newlimit ne 'none') {
 9397:                         if ($newcap =~ /^\d+$/) {
 9398:                             if ($newcap ne $currcap) {
 9399:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9400:                             }
 9401:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9402:                         } else {
 9403:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9404:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9405:                         }
 9406:                     } elsif ($currcap ne '') {
 9407:                         $changes{'internal.selfenroll_cap'} = '';
 9408:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9409:                     }
 9410:                 } elsif ($currlimit ne 'none') {
 9411:                     if ($newcap =~ /^\d+$/) {
 9412:                         if ($newcap ne $currcap) {
 9413:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9414:                         }
 9415:                     } else {
 9416:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9417:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9418:                     }
 9419:                 }
 9420:             } elsif ($item eq 'approval') {
 9421:                 my (@currnotified,@newnotified);
 9422:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9423:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9424:                 if ($currnotifylist ne '') {
 9425:                     @currnotified = split(/,/,$currnotifylist);
 9426:                     @currnotified = sort(@currnotified);
 9427:                 }
 9428:                 my $newapproval = $env{'form.selfenroll_approval'};
 9429:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9430:                 @newnotified = sort(@newnotified);
 9431:                 if ($newapproval ne $currapproval) {
 9432:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9433:                     if (!$newapproval) {
 9434:                         if ($currnotifylist ne '') {
 9435:                             $changes{'internal.selfenroll_notifylist'} = '';
 9436:                         }
 9437:                     } else {
 9438:                         my @differences =  
 9439:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9440:                         if (@differences > 0) {
 9441:                             if (@newnotified > 0) {
 9442:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9443:                             } else {
 9444:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9445:                             }
 9446:                         }
 9447:                     }
 9448:                 } else {
 9449:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9450:                     if (@differences > 0) {
 9451:                         if (@newnotified > 0) {
 9452:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9453:                         } else {
 9454:                             $changes{'internal.selfenroll_notifylist'} = '';
 9455:                         }
 9456:                     }
 9457:                 }
 9458:             } else {
 9459:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9460:                 my $newval = $env{'form.selfenroll_'.$item};
 9461:                 if ($item eq 'section') {
 9462:                     $newval = $env{'form.sections'};
 9463:                     if (defined($curr_groups{$newval})) {
 9464:                         $newval = $curr_val;
 9465:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9466:                                           &mt('Group names and section names must be distinct');
 9467:                     } elsif ($newval eq 'all') {
 9468:                         $newval = $curr_val;
 9469:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9470:                     }
 9471:                     if ($newval eq '') {
 9472:                         $newval = 'none';
 9473:                     }
 9474:                 }
 9475:                 if ($newval ne $curr_val) {
 9476:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9477:                 }
 9478:             }
 9479:         }
 9480:         if (keys(%warning) > 0) {
 9481:             foreach my $item (@{$row}) {
 9482:                 if (exists($warning{$item})) {
 9483:                     $r->print($warning{$item}.'<br />');
 9484:                 }
 9485:             } 
 9486:         }
 9487:         if (keys(%changes) > 0) {
 9488:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9489:             if ($putresult eq 'ok') {
 9490:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9491:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9492:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9493:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9494:                                                                 $cnum,undef,undef,'Course');
 9495:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9496:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9497:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9498:                             if (exists($changes{'internal.'.$item})) {
 9499:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9500:                             }
 9501:                         }
 9502:                         my $crsputresult =
 9503:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9504:                                                          $chome,'notime');
 9505:                     }
 9506:                 }
 9507:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9508:                 foreach my $item (@{$row}) {
 9509:                     my $title = $item;
 9510:                     if (ref($lt) eq 'HASH') {
 9511:                         $title = $lt->{$item};
 9512:                     }
 9513:                     if ($item eq 'enroll_dates') {
 9514:                         foreach my $type ('start','end') {
 9515:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9516:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9517:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9518:                                           $title,$type,$newdate).'</li>');
 9519:                             }
 9520:                         }
 9521:                     } elsif ($item eq 'access_dates') {
 9522:                         foreach my $type ('start','end') {
 9523:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9524:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9525:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9526:                                           $title,$type,$newdate).'</li>');
 9527:                             }
 9528:                         }
 9529:                     } elsif ($item eq 'limit') {
 9530:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9531:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9532:                             my ($newval,$newcap);
 9533:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9534:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9535:                             } else {
 9536:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9537:                             }
 9538:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9539:                                 $newval = &mt('No limit');
 9540:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9541:                                      'allstudents') {
 9542:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9543:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9544:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9545:                             } else {
 9546:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9547:                                 if ($currlimit eq 'allstudents') {
 9548:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9549:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9550:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9551:                                 }
 9552:                             }
 9553:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9554:                         }
 9555:                     } elsif ($item eq 'approval') {
 9556:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9557:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9558:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9559:                             my ($newval,$newnotify);
 9560:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9561:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9562:                             } else {   
 9563:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9564:                             }
 9565:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9566:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9567:                                     $changes{'internal.selfenroll_approval'} = '0';
 9568:                                 }
 9569:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9570:                             } else {
 9571:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9572:                                 if ($currapproval !~ /^[012]$/) {
 9573:                                     $currapproval = 0;
 9574:                                 }
 9575:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9576:                             }
 9577:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9578:                             if ($newnotify) {
 9579:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9580:                             } else {
 9581:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9582:                             }
 9583:                             $r->print('</li>'."\n");
 9584:                         }
 9585:                     } else {
 9586:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9587:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9588:                             if ($item eq 'types') {
 9589:                                 if ($newval eq '') {
 9590:                                     $newval = &mt('None');
 9591:                                 } elsif ($newval eq '*') {
 9592:                                     $newval = &mt('Any user in any domain');
 9593:                                 }
 9594:                             } elsif ($item eq 'registered') {
 9595:                                 if ($newval eq '1') {
 9596:                                     $newval = &mt('Yes');
 9597:                                 } elsif ($newval eq '0') {
 9598:                                     $newval = &mt('No');
 9599:                                 }
 9600:                             }
 9601:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9602:                         }
 9603:                     }
 9604:                 }
 9605:                 $r->print('</ul>');
 9606:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9607:                     my %newenvhash;
 9608:                     foreach my $key (keys(%changes)) {
 9609:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9610:                     }
 9611:                     &Apache::lonnet::appenv(\%newenvhash);
 9612:                 }
 9613:             } else {
 9614:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9615:                           &mt('The error was: [_1].',$putresult));
 9616:             }
 9617:         } else {
 9618:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9619:         }
 9620:     } else {
 9621:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9622:     }
 9623:     my $visactions = &cat_visibility();
 9624:     my ($cathash,%cattype);
 9625:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9626:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9627:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9628:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9629:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9630:     } else {
 9631:         $cathash = {};
 9632:         $cattype{'auth'} = 'std';
 9633:         $cattype{'unauth'} = 'std';
 9634:     }
 9635:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9636:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9637:                   '<br />'.
 9638:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9639:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9640:                   '</ul>');
 9641:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9642:         if ($currsettings->{'uniquecode'}) {
 9643:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9644:         } else {
 9645:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9646:                   '<br />'.
 9647:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9648:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9649:                   '</ul><br />');
 9650:         }
 9651:     } else {
 9652:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9653:         if (ref($visactions) eq 'HASH') {
 9654:             if (!$visible) {
 9655:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9656:                           '<br />');
 9657:                 if (ref($vismsgs) eq 'ARRAY') {
 9658:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9659:                     foreach my $item (@{$vismsgs}) {
 9660:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9661:                     }
 9662:                     $r->print('</ul>');
 9663:                 }
 9664:                 $r->print($cansetvis);
 9665:             }
 9666:         }
 9667:     } 
 9668:     return;
 9669: }
 9670: 
 9671: #---------------------------------------------- end functions for &phase_two
 9672: 
 9673: #--------------------------------- functions for &phase_two and &phase_three
 9674: 
 9675: #--------------------------end of functions for &phase_two and &phase_three
 9676: 
 9677: 1;
 9678: __END__
 9679: 
 9680: 

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