File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.455: download - view: text, annotated - select for diffs
Sat Sep 25 20:35:26 2021 UTC (2 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Captcha on public-facing web forms.
  - textbox user entry for original Captcha on same line as instructions.
  - validation for reCaptcha 2 moved to immediately above form submission
    button, as there re-validation is required after 2 minutes.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.455 2021/09/25 20:35:26 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: 
   75: my $loginscript; # piece of javascript used in two separate instances
   76: my $authformnop;
   77: my $authformkrb;
   78: my $authformint;
   79: my $authformfsys;
   80: my $authformloc;
   81: my $authformlti;
   82: 
   83: sub initialize_authen_forms {
   84:     my ($dom,$formname,$curr_authtype,$mode) = @_;
   85:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
   86:     my %param = ( formname => $formname,
   87:                   kerb_def_dom => $krbdefdom,
   88:                   kerb_def_auth => $krbdef,
   89:                   domain => $dom,
   90:                 );
   91:     my %abv_auth = &auth_abbrev();
   92:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix|lti):(.*)$/) {
   93:         my $long_auth = $1;
   94:         my $curr_autharg = $2;
   95:         my %abv_auth = &auth_abbrev();
   96:         $param{'curr_authtype'} = $abv_auth{$long_auth};
   97:         if ($long_auth =~ /^krb(4|5)$/) {
   98:             $param{'curr_kerb_ver'} = $1;
   99:             $param{'curr_autharg'} = $curr_autharg;
  100:         }
  101:         if ($mode eq 'modifyuser') {
  102:             $param{'mode'} = $mode;
  103:         }
  104:     }
  105:     $loginscript  = &Apache::loncommon::authform_header(%param);
  106:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
  107:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
  108:     $authformint  = &Apache::loncommon::authform_internal(%param);
  109:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
  110:     $authformloc  = &Apache::loncommon::authform_local(%param);
  111:     $authformlti  = &Apache::loncommon::authform_lti(%param);
  112: }
  113: 
  114: sub auth_abbrev {
  115:     my %abv_auth = (
  116:                      krb5      => 'krb',
  117:                      krb4      => 'krb',
  118:                      internal  => 'int',
  119:                      localauth => 'loc',
  120:                      unix      => 'fsys',
  121:                      lti       => 'lti',
  122:                    );
  123:     return %abv_auth;
  124: }
  125: 
  126: # ====================================================
  127: 
  128: sub user_quotas {
  129:     my ($ccuname,$ccdomain) = @_;
  130:     my %lt = &Apache::lonlocal::texthash(
  131:                    'usrt'      => "User Tools",
  132:                    'cust'      => "Custom quota",
  133:                    'chqu'      => "Change quota",
  134:     );
  135:    
  136:     my $quota_javascript = <<"END_SCRIPT";
  137: <script type="text/javascript">
  138: // <![CDATA[
  139: function quota_changes(caller,context) {
  140:     var customoff = document.getElementById('custom_'+context+'quota_off');
  141:     var customon = document.getElementById('custom_'+context+'quota_on');
  142:     var number = document.getElementById(context+'quota');
  143:     if (caller == "custom") {
  144:         if (customoff) {
  145:             if (customoff.checked) {
  146:                 number.value = "";
  147:             }
  148:         }
  149:     }
  150:     if (caller == "quota") {
  151:         if (customon) {
  152:             customon.checked = true;
  153:         }
  154:     }
  155:     return;
  156: }
  157: // ]]>
  158: </script>
  159: END_SCRIPT
  160:     my $longinsttype;
  161:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
  162:     my $output = $quota_javascript."\n".
  163:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
  164:                  &Apache::loncommon::start_data_table();
  165: 
  166:     if ((&Apache::lonnet::allowed('mut',$ccdomain)) ||
  167:         (&Apache::lonnet::allowed('udp',$ccdomain))) {
  168:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
  169:     }
  170: 
  171:     my %titles = &Apache::lonlocal::texthash (
  172:                     portfolio => "Disk space allocated to user's portfolio files",
  173:                     author    => "Disk space allocated to user's Authoring Space (if role assigned)",
  174:                  );
  175:     foreach my $name ('portfolio','author') {
  176:         my ($currquota,$quotatype,$inststatus,$defquota) =
  177:             &Apache::loncommon::get_user_quota($ccuname,$ccdomain,$name);
  178:         if ($longinsttype eq '') { 
  179:             if ($inststatus ne '') {
  180:                 if ($usertypes->{$inststatus} ne '') {
  181:                     $longinsttype = $usertypes->{$inststatus};
  182:                 }
  183:             }
  184:         }
  185:         my ($showquota,$custom_on,$custom_off,$defaultinfo);
  186:         $custom_on = ' ';
  187:         $custom_off = ' checked="checked" ';
  188:         if ($quotatype eq 'custom') {
  189:             $custom_on = $custom_off;
  190:             $custom_off = ' ';
  191:             $showquota = $currquota;
  192:             if ($longinsttype eq '') {
  193:                 $defaultinfo = &mt('For this user, the default quota would be [_1]'
  194:                               .' MB.',$defquota);
  195:             } else {
  196:                 $defaultinfo = &mt("For this user, the default quota would be [_1]".
  197:                                    " MB, as determined by the user's institutional".
  198:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  199:             }
  200:         } else {
  201:             if ($longinsttype eq '') {
  202:                 $defaultinfo = &mt('For this user, the default quota is [_1]'
  203:                               .' MB.',$defquota);
  204:             } else {
  205:                 $defaultinfo = &mt("For this user, the default quota of [_1]".
  206:                                    " MB, is determined by the user's institutional".
  207:                                    " affiliation ([_2]).",$defquota,$longinsttype);
  208:             }
  209:         }
  210: 
  211:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
  212:             $output .= '<tr class="LC_info_row">'."\n".
  213:                        '    <td>'.$titles{$name}.'</td>'."\n".
  214:                        '  </tr>'."\n".
  215:                        &Apache::loncommon::start_data_table_row()."\n".
  216:                        '  <td><span class="LC_nobreak">'.
  217:                        &mt('Current quota: [_1] MB',$currquota).'</span>&nbsp;&nbsp;'.
  218:                        $defaultinfo.'</td>'."\n".
  219:                        &Apache::loncommon::end_data_table_row()."\n".
  220:                        &Apache::loncommon::start_data_table_row()."\n".
  221:                        '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
  222:                        ': <label>'.
  223:                        '<input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_off" '.
  224:                        'value="0" '.$custom_off.' onchange="javascript:quota_changes('."'custom','$name'".');"'.
  225:                        ' /><span class="LC_nobreak">'.
  226:                        &mt('Default ([_1] MB)',$defquota).'</span></label>&nbsp;'.
  227:                        '&nbsp;<label><input type="radio" name="custom_'.$name.'quota" id="custom_'.$name.'quota_on" '.
  228:                        'value="1" '.$custom_on.'  onchange="javascript:quota_changes('."'custom','$name'".');"'.
  229:                        ' />'.$lt{'cust'}.':</label>&nbsp;'.
  230:                        '<input type="text" name="'.$name.'quota" id="'.$name.'quota" size ="5" '.
  231:                        'value="'.$showquota.'" onfocus="javascript:quota_changes('."'quota','$name'".');"'.
  232:                        ' />&nbsp;'.&mt('MB').'</span></td>'."\n".
  233:                        &Apache::loncommon::end_data_table_row()."\n";
  234:         }
  235:     }
  236:     $output .= &Apache::loncommon::end_data_table();
  237:     return $output;
  238: }
  239: 
  240: sub build_tools_display {
  241:     my ($ccuname,$ccdomain,$context) = @_;
  242:     my (@usertools,%userenv,$output,@options,%validations,%reqtitles,%reqdisplay,
  243:         $colspan,$isadv,%domconfig);
  244:     my %lt = &Apache::lonlocal::texthash (
  245:                    'blog'       => "Personal User Blog",
  246:                    'aboutme'    => "Personal Information Page",
  247:                    'webdav'     => "WebDAV access to Authoring Spaces (if SSL and author/co-author)",
  248:                    'portfolio'  => "Personal User Portfolio",
  249:                    'avai'       => "Available",
  250:                    'cusa'       => "availability",
  251:                    'chse'       => "Change setting",
  252:                    'usde'       => "Use default",
  253:                    'uscu'       => "Use custom",
  254:                    'official'   => 'Can request creation of official courses',
  255:                    'unofficial' => 'Can request creation of unofficial courses',
  256:                    'community'  => 'Can request creation of communities',
  257:                    'textbook'   => 'Can request creation of textbook courses',
  258:                    'placement'  => 'Can request creation of placement tests',
  259:                    'lti'        => 'Can request creation of LTI courses',
  260:                    'requestauthor'  => 'Can request author space',
  261:     );
  262:     if ($context eq 'requestcourses') {
  263:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  264:                       'requestcourses.official','requestcourses.unofficial',
  265:                       'requestcourses.community','requestcourses.textbook',
  266:                       'requestcourses.placement','requestcourses.lti');
  267:         @usertools = ('official','unofficial','community','textbook','placement','lti');
  268:         @options =('norequest','approval','autolimit','validate');
  269:         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
  270:         %reqtitles = &courserequest_titles();
  271:         %reqdisplay = &courserequest_display();
  272:         $colspan = ' colspan="2"';
  273:         %domconfig =
  274:             &Apache::lonnet::get_dom('configuration',['requestcourses'],$ccdomain);
  275:         $isadv = &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
  276:     } elsif ($context eq 'requestauthor') {
  277:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  278:                                                     'requestauthor');
  279:         @usertools = ('requestauthor');
  280:         @options =('norequest','approval','automatic');
  281:         %reqtitles = &requestauthor_titles();
  282:         %reqdisplay = &requestauthor_display();
  283:         $colspan = ' colspan="2"';
  284:         %domconfig =
  285:             &Apache::lonnet::get_dom('configuration',['requestauthor'],$ccdomain);
  286:     } else {
  287:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  288:                           'tools.aboutme','tools.portfolio','tools.blog',
  289:                           'tools.webdav');
  290:         @usertools = ('aboutme','blog','webdav','portfolio');
  291:     }
  292:     foreach my $item (@usertools) {
  293:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off,
  294:             $currdisp,$custdisp,$custradio);
  295:         $cust_off = 'checked="checked" ';
  296:         $tool_on = 'checked="checked" ';
  297:         $curr_access =  
  298:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
  299:                                               $context);
  300:         if ($context eq 'requestauthor') {
  301:             if ($userenv{$context} ne '') {
  302:                 $cust_on = ' checked="checked" ';
  303:                 $cust_off = '';
  304:             }  
  305:         } elsif ($userenv{$context.'.'.$item} ne '') {
  306:             $cust_on = ' checked="checked" ';
  307:             $cust_off = '';
  308:         }
  309:         if ($context eq 'requestcourses') {
  310:             if ($userenv{$context.'.'.$item} eq '') {
  311:                 $custom_access = &mt('Currently from default setting.');
  312:             } else {
  313:                 $custom_access = &mt('Currently from custom setting.');
  314:             }
  315:         } elsif ($context eq 'requestauthor') {
  316:             if ($userenv{$context} eq '') {
  317:                 $custom_access = &mt('Currently from default setting.');
  318:             } else {
  319:                 $custom_access = &mt('Currently from custom setting.');
  320:             }
  321:         } else {
  322:             if ($userenv{$context.'.'.$item} eq '') {
  323:                 $custom_access =
  324:                     &mt('Availability determined currently from default setting.');
  325:                 if (!$curr_access) {
  326:                     $tool_off = 'checked="checked" ';
  327:                     $tool_on = '';
  328:                 }
  329:             } else {
  330:                 $custom_access =
  331:                     &mt('Availability determined currently from custom setting.');
  332:                 if ($userenv{$context.'.'.$item} == 0) {
  333:                     $tool_off = 'checked="checked" ';
  334:                     $tool_on = '';
  335:                 }
  336:             }
  337:         }
  338:         $output .= '  <tr class="LC_info_row">'."\n".
  339:                    '   <td'.$colspan.'>'.$lt{$item}.'</td>'."\n".
  340:                    '  </tr>'."\n".
  341:                    &Apache::loncommon::start_data_table_row()."\n";
  342:   
  343:         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
  344:             my ($curroption,$currlimit);
  345:             my $envkey = $context.'.'.$item;
  346:             if ($context eq 'requestauthor') {
  347:                 $envkey = $context;
  348:             }
  349:             if ($userenv{$envkey} ne '') {
  350:                 $curroption = $userenv{$envkey};
  351:             } else {
  352:                 my (@inststatuses);
  353:                 if ($context eq 'requestcourses') {
  354:                     $curroption =
  355:                         &Apache::loncoursequeueadmin::get_processtype('course',$ccuname,$ccdomain,
  356:                                                                       $isadv,$ccdomain,$item,
  357:                                                                       \@inststatuses,\%domconfig);
  358:                 } else {
  359:                      $curroption = 
  360:                          &Apache::loncoursequeueadmin::get_processtype('requestauthor',$ccuname,$ccdomain,
  361:                                                                        $isadv,$ccdomain,undef,
  362:                                                                        \@inststatuses,\%domconfig);
  363:                 }
  364:             }
  365:             if (!$curroption) {
  366:                 $curroption = 'norequest';
  367:             }
  368:             if ($curroption =~ /^autolimit=(\d*)$/) {
  369:                 $currlimit = $1;
  370:                 if ($currlimit eq '') {
  371:                     $currdisp = &mt('Yes, automatic creation');
  372:                 } else {
  373:                     $currdisp = &mt('Yes, up to [quant,_1,request]/user',$currlimit);
  374:                 }
  375:             } else {
  376:                 $currdisp = $reqdisplay{$curroption};
  377:             }
  378:             $custdisp = '<table>';
  379:             foreach my $option (@options) {
  380:                 my $val = $option;
  381:                 if ($option eq 'norequest') {
  382:                     $val = 0;
  383:                 }
  384:                 if ($option eq 'validate') {
  385:                     my $canvalidate = 0;
  386:                     if (ref($validations{$item}) eq 'HASH') {
  387:                         if ($validations{$item}{'_custom_'}) {
  388:                             $canvalidate = 1;
  389:                         }
  390:                     }
  391:                     next if (!$canvalidate);
  392:                 }
  393:                 my $checked = '';
  394:                 if ($option eq $curroption) {
  395:                     $checked = ' checked="checked"';
  396:                 } elsif ($option eq 'autolimit') {
  397:                     if ($curroption =~ /^autolimit/) {
  398:                         $checked = ' checked="checked"';
  399:                     }
  400:                 }
  401:                 my $name = 'crsreq_'.$item;
  402:                 if ($context eq 'requestauthor') {
  403:                     $name = $item;
  404:                 }
  405:                 $custdisp .= '<tr><td><span class="LC_nobreak"><label>'.
  406:                              '<input type="radio" name="'.$name.'" '.
  407:                              'value="'.$val.'"'.$checked.' />'.
  408:                              $reqtitles{$option}.'</label>&nbsp;';
  409:                 if ($option eq 'autolimit') {
  410:                     $custdisp .= '<input type="text" name="'.$name.
  411:                                  '_limit" size="1" '.
  412:                                  'value="'.$currlimit.'" /></span><br />'.
  413:                                  $reqtitles{'unlimited'};
  414:                 } else {
  415:                     $custdisp .= '</span>';
  416:                 }
  417:                 $custdisp .= '</td></tr>';
  418:             }
  419:             $custdisp .= '</table>';
  420:             $custradio = '</span></td><td>'.&mt('Custom setting').'<br />'.$custdisp;
  421:         } else {
  422:             $currdisp = ($curr_access?&mt('Yes'):&mt('No'));
  423:             my $name = $context.'_'.$item;
  424:             if ($context eq 'requestauthor') {
  425:                 $name = $context;
  426:             }
  427:             $custdisp = '<span class="LC_nobreak"><label>'.
  428:                         '<input type="radio" name="'.$name.'"'.
  429:                         ' value="1" '.$tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
  430:                         '<input type="radio" name="'.$name.'" value="0" '.
  431:                         $tool_off.'/>'.&mt('Off').'</label></span>';
  432:             $custradio = ('&nbsp;'x2).'--'.$lt{'cusa'}.':&nbsp;'.$custdisp.
  433:                           '</span>';
  434:         }
  435:         $output .= '  <td'.$colspan.'>'.$custom_access.('&nbsp;'x4).
  436:                    $lt{'avai'}.': '.$currdisp.'</td>'."\n".
  437:                    &Apache::loncommon::end_data_table_row()."\n";
  438:         unless (&Apache::lonnet::allowed('udp',$ccdomain)) {
  439:             $output .=
  440:                    &Apache::loncommon::start_data_table_row()."\n".
  441:                    '  <td style="vertical-align:top;"><span class="LC_nobreak">'.
  442:                    $lt{'chse'}.': <label>'.
  443:                    '<input type="radio" name="custom'.$item.'" value="0" '.
  444:                    $cust_off.'/>'.$lt{'usde'}.'</label>'.('&nbsp;' x3).
  445:                    '<label><input type="radio" name="custom'.$item.'" value="1" '.
  446:                    $cust_on.'/>'.$lt{'uscu'}.'</label>'.$custradio.'</td>'.
  447:                    &Apache::loncommon::end_data_table_row()."\n";
  448:         }
  449:     }
  450:     return $output;
  451: }
  452: 
  453: sub coursereq_externaluser {
  454:     my ($ccuname,$ccdomain,$cdom) = @_;
  455:     my (@usertools,@options,%validations,%userenv,$output);
  456:     my %lt = &Apache::lonlocal::texthash (
  457:                    'official'   => 'Can request creation of official courses',
  458:                    'unofficial' => 'Can request creation of unofficial courses',
  459:                    'community'  => 'Can request creation of communities',
  460:                    'textbook'   => 'Can request creation of textbook courses',
  461:                    'placement'  => 'Can request creation of placement tests',
  462:     );
  463: 
  464:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
  465:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
  466:                       'reqcrsotherdom.community','reqcrsotherdom.textbook',
  467:                       'reqcrsotherdom.placement');
  468:     @usertools = ('official','unofficial','community','textbook','placement');
  469:     @options = ('approval','validate','autolimit');
  470:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
  471:     my $optregex = join('|',@options);
  472:     my %reqtitles = &courserequest_titles();
  473:     foreach my $item (@usertools) {
  474:         my ($curroption,$currlimit,$tooloff);
  475:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
  476:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
  477:             foreach my $req (@curr) {
  478:                 if ($req =~ /^\Q$cdom\E\:($optregex)=?(\d*)$/) {
  479:                     $curroption = $1;
  480:                     $currlimit = $2;
  481:                     last;
  482:                 }
  483:             }
  484:             if (!$curroption) {
  485:                 $curroption = 'norequest';
  486:                 $tooloff = ' checked="checked"';
  487:             }
  488:         } else {
  489:             $curroption = 'norequest';
  490:             $tooloff = ' checked="checked"';
  491:         }
  492:         $output.= &Apache::loncommon::start_data_table_row()."\n".
  493:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': </span></td><td>'.
  494:                   '<table><tr><td valign="top">'."\n".
  495:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
  496:                   '" value=""'.$tooloff.' />'.$reqtitles{'norequest'}.
  497:                   '</label></td>';
  498:         foreach my $option (@options) {
  499:             if ($option eq 'validate') {
  500:                 my $canvalidate = 0;
  501:                 if (ref($validations{$item}) eq 'HASH') {
  502:                     if ($validations{$item}{'_external_'}) {
  503:                         $canvalidate = 1;
  504:                     }
  505:                 }
  506:                 next if (!$canvalidate);
  507:             }
  508:             my $checked = '';
  509:             if ($option eq $curroption) {
  510:                 $checked = ' checked="checked"';
  511:             }
  512:             $output .= '<td valign="top"><span class="LC_nobreak"><label>'.
  513:                        '<input type="radio" name="reqcrsotherdom_'.$item.
  514:                        '" value="'.$option.'"'.$checked.' />'.
  515:                        $reqtitles{$option}.'</label>';
  516:             if ($option eq 'autolimit') {
  517:                 $output .= '&nbsp;<input type="text" name="reqcrsotherdom_'.
  518:                            $item.'_limit" size="1" '.
  519:                            'value="'.$currlimit.'" /></span>'.
  520:                            '<br />'.$reqtitles{'unlimited'};
  521:             } else {
  522:                 $output .= '</span>';
  523:             }
  524:             $output .= '</td>';
  525:         }
  526:         $output .= '</td></tr></table></td>'."\n".
  527:                    &Apache::loncommon::end_data_table_row()."\n";
  528:     }
  529:     return $output;
  530: }
  531: 
  532: sub domainrole_req {
  533:     my ($ccuname,$ccdomain) = @_;
  534:     return '<br /><h3>'.
  535:            &mt('User Can Request Assignment of Domain Roles?').
  536:            '</h3>'."\n".
  537:            &Apache::loncommon::start_data_table().
  538:            &build_tools_display($ccuname,$ccdomain,
  539:                                 'requestauthor').
  540:            &Apache::loncommon::end_data_table();
  541: }
  542: 
  543: sub courserequest_titles {
  544:     my %titles = &Apache::lonlocal::texthash (
  545:                                    official   => 'Official',
  546:                                    unofficial => 'Unofficial',
  547:                                    community  => 'Communities',
  548:                                    textbook   => 'Textbook',
  549:                                    placement  => 'Placement Tests',
  550:                                    lti        => 'LTI Provider',
  551:                                    norequest  => 'Not allowed',
  552:                                    approval   => 'Approval by Dom. Coord.',
  553:                                    validate   => 'With validation',
  554:                                    autolimit  => 'Numerical limit',
  555:                                    unlimited  => '(blank for unlimited)',
  556:                  );
  557:     return %titles;
  558: }
  559: 
  560: sub courserequest_display {
  561:     my %titles = &Apache::lonlocal::texthash (
  562:                                    approval   => 'Yes, need approval',
  563:                                    validate   => 'Yes, with validation',
  564:                                    norequest  => 'No',
  565:    );
  566:    return %titles;
  567: }
  568: 
  569: sub requestauthor_titles {
  570:     my %titles = &Apache::lonlocal::texthash (
  571:                                    norequest  => 'Not allowed',
  572:                                    approval   => 'Approval by Dom. Coord.',
  573:                                    automatic  => 'Automatic approval',
  574:                  );
  575:     return %titles;
  576: 
  577: }
  578: 
  579: sub requestauthor_display {
  580:     my %titles = &Apache::lonlocal::texthash (
  581:                                    approval   => 'Yes, need approval',
  582:                                    automatic  => 'Yes, automatic approval',
  583:                                    norequest  => 'No',
  584:    );
  585:    return %titles;
  586: }
  587: 
  588: sub requestchange_display {
  589:     my %titles = &Apache::lonlocal::texthash (
  590:                                    approval   => "availability set to 'on' (approval required)", 
  591:                                    automatic  => "availability set to 'on' (automatic approval)",
  592:                                    norequest  => "availability set to 'off'",
  593:    );
  594:    return %titles;
  595: }
  596: 
  597: sub curr_requestauthor {
  598:     my ($uname,$udom,$isadv,$inststatuses,$domconfig) = @_;
  599:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
  600:     if ($uname eq '' || $udom eq '') {
  601:         $uname = $env{'user.name'};
  602:         $udom = $env{'user.domain'};
  603:         $isadv = $env{'user.adv'};
  604:     }
  605:     my (%userenv,%settings,$val);
  606:     my @options = ('automatic','approval');
  607:     %userenv =
  608:         &Apache::lonnet::userenvironment($udom,$uname,'requestauthor','inststatus');
  609:     if ($userenv{'requestauthor'}) {
  610:         $val = $userenv{'requestauthor'};
  611:         @{$inststatuses} = ('_custom_');
  612:     } else {
  613:         my %alltasks;
  614:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') {
  615:             %settings = %{$domconfig->{'requestauthor'}};
  616:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
  617:                 $val = $settings{'_LC_adv'};
  618:                 @{$inststatuses} = ('_LC_adv_');
  619:             } else {
  620:                 if ($userenv{'inststatus'} ne '') {
  621:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
  622:                 } else {
  623:                     @{$inststatuses} = ('default');
  624:                 }
  625:                 foreach my $status (@{$inststatuses}) {
  626:                     if (exists($settings{$status})) {
  627:                         my $value = $settings{$status};
  628:                         next unless ($value);
  629:                         unless (exists($alltasks{$value})) {
  630:                             if (ref($alltasks{$value}) eq 'ARRAY') {
  631:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
  632:                                     push(@{$alltasks{$value}},$status);
  633:                                 }
  634:                             } else {
  635:                                 @{$alltasks{$value}} = ($status);
  636:                             }
  637:                         }
  638:                     }
  639:                 }
  640:                 foreach my $option (@options) {
  641:                     if ($alltasks{$option}) {
  642:                         $val = $option;
  643:                         last;
  644:                     }
  645:                 }
  646:             }
  647:         }
  648:     }
  649:     return $val;
  650: }
  651: 
  652: # =================================================================== Phase one
  653: 
  654: sub print_username_entry_form {
  655:     my ($r,$context,$response,$srch,$forcenewuser,$crstype,$brcrum,
  656:         $permission) = @_;
  657:     my $defdom=$env{'request.role.domain'};
  658:     my $formtoset = 'crtuser';
  659:     if (exists($env{'form.startrolename'})) {
  660:         $formtoset = 'docustom';
  661:         $env{'form.rolename'} = $env{'form.startrolename'};
  662:     } elsif ($env{'form.origform'} eq 'crtusername') {
  663:         $formtoset =  $env{'form.origform'};
  664:     }
  665: 
  666:     my ($jsback,$elements) = &crumb_utilities();
  667: 
  668:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
  669:         '<script type="text/javascript">'."\n".
  670:         '// <![CDATA['."\n".
  671:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset})."\n".
  672:         '// ]]>'."\n".
  673:         '</script>'."\n";
  674: 
  675:     my %existingroles=&Apache::lonuserutils::my_custom_roles($crstype);
  676:     if (($env{'form.action'} eq 'custom') && (keys(%existingroles) > 0)
  677:         && (&Apache::lonnet::allowed('mcr','/'))) {
  678:         $jscript .= &customrole_javascript();
  679:     }
  680:     my $helpitem = 'Course_Change_Privileges';
  681:     if ($env{'form.action'} eq 'custom') {
  682:         if ($context eq 'course') {
  683:             $helpitem = 'Course_Editing_Custom_Roles';
  684:         } elsif ($context eq 'domain') {
  685:             $helpitem = 'Domain_Editing_Custom_Roles';
  686:         }
  687:     } elsif ($env{'form.action'} eq 'singlestudent') {
  688:         $helpitem = 'Course_Add_Student';
  689:     } elsif ($env{'form.action'} eq 'accesslogs') {
  690:         $helpitem = 'Domain_User_Access_Logs';
  691:     } elsif ($context eq 'author') {
  692:         $helpitem = 'Author_Change_Privileges';
  693:     } elsif ($context eq 'domain') {
  694:         if ($permission->{'cusr'}) {
  695:             $helpitem = 'Domain_Change_Privileges';
  696:         } elsif ($permission->{'view'}) {
  697:             $helpitem = 'Domain_View_Privileges';
  698:         } else {
  699:             undef($helpitem);
  700:         }
  701:     }
  702:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$defdom);
  703:     if ($env{'form.action'} eq 'custom') {
  704:         push(@{$brcrum},
  705:                  {href=>"javascript:backPage(document.crtuser)",       
  706:                   text=>"Pick custom role",
  707:                   help => $helpitem,}
  708:                  );
  709:     } else {
  710:         push (@{$brcrum},
  711:                   {href => "javascript:backPage(document.crtuser)",
  712:                    text => $breadcrumb_text{'search'},
  713:                    help => $helpitem,
  714:                    faq  => 282,
  715:                    bug  => 'Instructor Interface',}
  716:                   );
  717:     }
  718:     my %loaditems = (
  719:                 'onload' => "javascript:setFormElements(document.$formtoset)",
  720:                     );
  721:     my $args = {bread_crumbs           => $brcrum,
  722:                 bread_crumbs_component => 'User Management',
  723:                 add_entries            => \%loaditems,};
  724:     $r->print(&Apache::loncommon::start_page('User Management',$jscript,$args));
  725: 
  726:     my %lt=&Apache::lonlocal::texthash(
  727:                     'srst' => 'Search for a user and enroll as a student',
  728:                     'srme' => 'Search for a user and enroll as a member',
  729:                     'srad' => 'Search for a user and modify/add user information or roles',
  730:                     'srvu' => 'Search for a user and view user information and roles',
  731:                     'srva' => 'Search for a user and view access log information',
  732: 		    'usr'  => "Username",
  733:                     'dom'  => "Domain",
  734:                     'ecrp' => "Define or Edit Custom Role",
  735:                     'nr'   => "role name",
  736:                     'cre'  => "Next",
  737: 				       );
  738: 
  739:     if ($env{'form.action'} eq 'custom') {
  740:         if (&Apache::lonnet::allowed('mcr','/')) {
  741:             my $newroletext = &mt('Define new custom role:');
  742:             $r->print('<form action="/adm/createuser" method="post" name="docustom">'.
  743:                       '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
  744:                       '<input type="hidden" name="phase" value="selected_custom_edit" />'.
  745:                       '<h3>'.$lt{'ecrp'}.'</h3>'.
  746:                       &Apache::loncommon::start_data_table().
  747:                       &Apache::loncommon::start_data_table_row().
  748:                       '<td>');
  749:             if (keys(%existingroles) > 0) {
  750:                 $r->print('<br /><label><input type="radio" name="customroleaction" value="new" checked="checked" onclick="setCustomFields();" /><b>'.$newroletext.'</b></label>');
  751:             } else {
  752:                 $r->print('<br /><input type="hidden" name="customroleaction" value="new" /><b>'.$newroletext.'</b>');
  753:             }
  754:             $r->print('</td><td align="center">'.$lt{'nr'}.'<br /><input type="text" size="15" name="newrolename" onfocus="setCustomAction('."'new'".');" /></td>'.
  755:                       &Apache::loncommon::end_data_table_row());
  756:             if (keys(%existingroles) > 0) {
  757:                 $r->print(&Apache::loncommon::start_data_table_row().'<td><br />'.
  758:                           '<label><input type="radio" name="customroleaction" value="edit" onclick="setCustomFields();"/><b>'.
  759:                           &mt('View/Modify existing role:').'</b></label></td>'.
  760:                           '<td align="center"><br />'.
  761:                           '<select name="rolename" onchange="setCustomAction('."'edit'".');">'.
  762:                           '<option value="" selected="selected">'.
  763:                           &mt('Select'));
  764:                 foreach my $role (sort(keys(%existingroles))) {
  765:                     $r->print('<option value="'.$role.'">'.$role.'</option>');
  766:                 }
  767:                 $r->print('</select>'.
  768:                           '</td>'.
  769:                           &Apache::loncommon::end_data_table_row());
  770:             }
  771:             $r->print(&Apache::loncommon::end_data_table().'<p>'.
  772:                       '<input name="customeditor" type="submit" value="'.
  773:                       $lt{'cre'}.'" /></p>'.
  774:                       '</form>');
  775:         }
  776:     } else {
  777:         my $actiontext = $lt{'srad'};
  778:         my $fixeddom;
  779:         if ($env{'form.action'} eq 'singlestudent') {
  780:             if ($crstype eq 'Community') {
  781:                 $actiontext = $lt{'srme'};
  782:             } else {
  783:                 $actiontext = $lt{'srst'};
  784:             }
  785:         } elsif ($env{'form.action'} eq 'accesslogs') {
  786:             $actiontext = $lt{'srva'};
  787:             $fixeddom = 1;
  788:         } elsif (($env{'form.action'} eq 'singleuser') &&
  789:                  ($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$defdom))) {
  790:             $actiontext = $lt{'srvu'};
  791:             $fixeddom = 1;
  792:         }
  793:         $r->print("<h3>$actiontext</h3>");
  794:         if ($env{'form.origform'} ne 'crtusername') {
  795:             if ($response) {
  796:                $r->print("\n<div>$response</div>".
  797:                          '<br clear="all" />');
  798:             }
  799:         }
  800:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype,$fixeddom));
  801:     }
  802: }
  803: 
  804: sub customrole_javascript {
  805:     my $js = <<"END";
  806: <script type="text/javascript">
  807: // <![CDATA[
  808: 
  809: function setCustomFields() {
  810:     if (document.docustom.customroleaction.length > 0) {
  811:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  812:             if (document.docustom.customroleaction[i].checked) {
  813:                 if (document.docustom.customroleaction[i].value == 'new') {
  814:                     document.docustom.rolename.selectedIndex = 0;
  815:                 } else {
  816:                     document.docustom.newrolename.value = '';
  817:                 }
  818:             }
  819:         }
  820:     }
  821:     return;
  822: }
  823: 
  824: function setCustomAction(caller) {
  825:     if (document.docustom.customroleaction.length > 0) {
  826:         for (var i=0; i<document.docustom.customroleaction.length; i++) {
  827:             if (document.docustom.customroleaction[i].value == caller) {
  828:                 document.docustom.customroleaction[i].checked = true;
  829:             }
  830:         }
  831:     }
  832:     setCustomFields();
  833:     return;
  834: }
  835: 
  836: // ]]>
  837: </script>
  838: END
  839:     return $js;
  840: }
  841: 
  842: sub entry_form {
  843:     my ($dom,$srch,$forcenewuser,$context,$responsemsg,$crstype,$fixeddom) = @_;
  844:     my ($usertype,$inexact);
  845:     if (ref($srch) eq 'HASH') {
  846:         if (($srch->{'srchin'} eq 'dom') &&
  847:             ($srch->{'srchby'} eq 'uname') &&
  848:             ($srch->{'srchtype'} eq 'exact') &&
  849:             ($srch->{'srchdomain'} ne '') &&
  850:             ($srch->{'srchterm'} ne '')) {
  851:             my (%curr_rules,%got_rules);
  852:             my ($rules,$ruleorder) =
  853:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
  854:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules,\%curr_rules,\%got_rules);
  855:         } else {
  856:             $inexact = 1;
  857:         }
  858:     }
  859:     my ($cancreate,$noinstd);
  860:     if ($env{'form.action'} eq 'accesslogs') {
  861:         $noinstd = 1;
  862:     } else {
  863:         $cancreate =
  864:             &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
  865:     }
  866:     my ($userpicker,$cansearch) = 
  867:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
  868:                                        'document.crtuser',$cancreate,$usertype,$context,$fixeddom,$noinstd);
  869:     my $srchbutton = &mt('Search');
  870:     if ($env{'form.action'} eq 'singlestudent') {
  871:         $srchbutton = &mt('Search and Enroll');
  872:     } elsif ($env{'form.action'} eq 'accesslogs') {
  873:         $srchbutton = &mt('Search');
  874:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
  875:         $srchbutton = &mt('Search or Add New User');
  876:     }
  877:     my $output;
  878:     if ($cansearch) {
  879:         $output = <<"ENDBLOCK";
  880: <form action="/adm/createuser" method="post" name="crtuser">
  881: <input type="hidden" name="action" value="$env{'form.action'}" />
  882: <input type="hidden" name="phase" value="get_user_info" />
  883: $userpicker
  884: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
  885: </form>
  886: ENDBLOCK
  887:     } else {
  888:         $output = '<p>'.$userpicker.'</p>';
  889:     }
  890:     if (($env{'form.phase'} eq '') && ($env{'form.action'} ne 'accesslogs') &&
  891:         (!(($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
  892:         (!&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))))) {
  893:         my $defdom=$env{'request.role.domain'};
  894:         my ($trusted,$untrusted);
  895:         if ($context eq 'course') {
  896:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$defdom);
  897:         } elsif ($context eq 'author') {
  898:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
  899:         } elsif ($context eq 'domain') {
  900:             ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('domroles',$defdom); 
  901:         }
  902:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain',undef,undef,undef,$trusted,$untrusted);
  903:         my %lt=&Apache::lonlocal::texthash(
  904:                   'enro' => 'Enroll one student',
  905:                   'enrm' => 'Enroll one member',
  906:                   'admo' => 'Add/modify a single user',
  907:                   'crea' => 'create new user if required',
  908:                   'uskn' => "username is known",
  909:                   'crnu' => 'Create a new user',
  910:                   'usr'  => 'Username',
  911:                   'dom'  => 'in domain',
  912:                   'enrl' => 'Enroll',
  913:                   'cram'  => 'Create/Modify user',
  914:         );
  915:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
  916:         my ($title,$buttontext,$showresponse);
  917:         if ($env{'form.action'} eq 'singlestudent') {
  918:             if ($crstype eq 'Community') {
  919:                 $title = $lt{'enrm'};
  920:             } else {
  921:                 $title = $lt{'enro'};
  922:             }
  923:             $buttontext = $lt{'enrl'};
  924:         } else {
  925:             $title = $lt{'admo'};
  926:             $buttontext = $lt{'cram'};
  927:         }
  928:         if ($cancreate) {
  929:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
  930:         } else {
  931:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
  932:         }
  933:         if ($env{'form.origform'} eq 'crtusername') {
  934:             $showresponse = $responsemsg;
  935:         }
  936:         $output .= <<"ENDDOCUMENT";
  937: <br />
  938: <form action="/adm/createuser" method="post" name="crtusername">
  939: <input type="hidden" name="action" value="$env{'form.action'}" />
  940: <input type="hidden" name="phase" value="createnewuser" />
  941: <input type="hidden" name="srchtype" value="exact" />
  942: <input type="hidden" name="srchby" value="uname" />
  943: <input type="hidden" name="srchin" value="dom" />
  944: <input type="hidden" name="forcenewuser" value="1" />
  945: <input type="hidden" name="origform" value="crtusername" />
  946: <h3>$title</h3>
  947: $showresponse
  948: <table>
  949:  <tr>
  950:   <td>$lt{'usr'}:</td>
  951:   <td><input type="text" size="15" name="srchterm" /></td>
  952:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
  953:   <td>&nbsp;$sellink&nbsp;</td>
  954:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
  955:  </tr>
  956: </table>
  957: </form>
  958: ENDDOCUMENT
  959:     }
  960:     return $output;
  961: }
  962: 
  963: sub user_modification_js {
  964:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
  965:     
  966:     return <<END;
  967: <script type="text/javascript" language="Javascript">
  968: // <![CDATA[
  969: 
  970:     $pjump_def
  971:     $dc_setcourse_code
  972: 
  973:     function dateset() {
  974:         eval("document.cu."+document.cu.pres_marker.value+
  975:             ".value=document.cu.pres_value.value");
  976:         modalWindow.close();
  977:     }
  978: 
  979:     $nondc_setsection_code
  980: // ]]>
  981: </script>
  982: END
  983: }
  984: 
  985: # =================================================================== Phase two
  986: sub print_user_selection_page {
  987:     my ($r,$response,$srch,$srch_results,$srcharray,$context,$opener_elements,$crstype,$brcrum) = @_;
  988:     my @fields = ('username','domain','lastname','firstname','permanentemail');
  989:     my $sortby = $env{'form.sortby'};
  990: 
  991:     if (!grep(/^\Q$sortby\E$/,@fields)) {
  992:         $sortby = 'lastname';
  993:     }
  994: 
  995:     my ($jsback,$elements) = &crumb_utilities();
  996: 
  997:     my $jscript = (<<ENDSCRIPT);
  998: <script type="text/javascript">
  999: // <![CDATA[
 1000: function pickuser(uname,udom) {
 1001:     document.usersrchform.seluname.value=uname;
 1002:     document.usersrchform.seludom.value=udom;
 1003:     document.usersrchform.phase.value="userpicked";
 1004:     document.usersrchform.submit();
 1005: }
 1006: 
 1007: $jsback
 1008: // ]]>
 1009: </script>
 1010: ENDSCRIPT
 1011: 
 1012:     my %lt=&Apache::lonlocal::texthash(
 1013:                                        'usrch'          => "User Search to add/modify roles",
 1014:                                        'stusrch'        => "User Search to enroll student",
 1015:                                        'memsrch'        => "User Search to enroll member",
 1016:                                        'srcva'          => "Search for a user and view access log information",
 1017:                                        'usrvu'          => "User Search to view user roles",
 1018:                                        'usel'           => "Select a user to add/modify roles",
 1019:                                        'suvr'           => "Select a user to view roles",
 1020:                                        'stusel'         => "Select a user to enroll as a student",
 1021:                                        'memsel'         => "Select a user to enroll as a member",
 1022:                                        'vacsel'         => "Select a user to view access log",
 1023:                                        'username'       => "username",
 1024:                                        'domain'         => "domain",
 1025:                                        'lastname'       => "last name",
 1026:                                        'firstname'      => "first name",
 1027:                                        'permanentemail' => "permanent e-mail",
 1028:                                       );
 1029:     if ($context eq 'requestcrs') {
 1030:         $r->print('<div>');
 1031:     } else {
 1032:         my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$srch->{'srchdomain'});
 1033:         my $helpitem;
 1034:         if ($env{'form.action'} eq 'singleuser') {
 1035:             $helpitem = 'Course_Change_Privileges';
 1036:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1037:             $helpitem = 'Course_Add_Student';
 1038:         } elsif ($context eq 'author') {
 1039:             $helpitem = 'Author_Change_Privileges';
 1040:         } elsif ($context eq 'domain') {
 1041:             $helpitem = 'Domain_Change_Privileges';
 1042:         }
 1043:         push (@{$brcrum},
 1044:                   {href => "javascript:backPage(document.usersrchform,'','')",
 1045:                    text => $breadcrumb_text{'search'},
 1046:                    faq  => 282,
 1047:                    bug  => 'Instructor Interface',},
 1048:                   {href => "javascript:backPage(document.usersrchform,'get_user_info','select')",
 1049:                    text => $breadcrumb_text{'userpicked'},
 1050:                    faq  => 282,
 1051:                    bug  => 'Instructor Interface',
 1052:                    help => $helpitem}
 1053:                   );
 1054:         $r->print(&Apache::loncommon::start_page('User Management',$jscript,{bread_crumbs => $brcrum}));
 1055:         if ($env{'form.action'} eq 'singleuser') {
 1056:             my $readonly;
 1057:             if (($context eq 'domain') && (!&Apache::lonnet::allowed('mau',$srch->{'srchdomain'}))) {
 1058:                 $readonly = 1;
 1059:                 $r->print("<b>$lt{'usrvu'}</b><br />");
 1060:             } else {
 1061:                 $r->print("<b>$lt{'usrch'}</b><br />");
 1062:             }
 1063:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1064:             if ($readonly) {
 1065:                 $r->print('<h3>'.$lt{'suvr'}.'</h3>');
 1066:             } else {
 1067:                 $r->print('<h3>'.$lt{'usel'}.'</h3>');
 1068:             }
 1069:         } elsif ($env{'form.action'} eq 'singlestudent') {
 1070:             $r->print($jscript."<b>");
 1071:             if ($crstype eq 'Community') {
 1072:                 $r->print($lt{'memsrch'});
 1073:             } else {
 1074:                 $r->print($lt{'stusrch'});
 1075:             }
 1076:             $r->print("</b><br />");
 1077:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,$crstype));
 1078:             $r->print('</form><h3>');
 1079:             if ($crstype eq 'Community') {
 1080:                 $r->print($lt{'memsel'});
 1081:             } else {
 1082:                 $r->print($lt{'stusel'});
 1083:             }
 1084:             $r->print('</h3>');
 1085:         } elsif ($env{'form.action'} eq 'accesslogs') {
 1086:             $r->print("<b>$lt{'srcva'}</b><br />");
 1087:             $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context,undef,undef,1));
 1088:             $r->print('<h3>'.$lt{'vacsel'}.'</h3>');
 1089:         }
 1090:     }
 1091:     $r->print('<form name="usersrchform" method="post" action="">'.
 1092:               &Apache::loncommon::start_data_table()."\n".
 1093:               &Apache::loncommon::start_data_table_header_row()."\n".
 1094:               ' <th> </th>'."\n");
 1095:     foreach my $field (@fields) {
 1096:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
 1097:                   "'".$field."'".';document.usersrchform.submit();">'.
 1098:                   $lt{$field}.'</a></th>'."\n");
 1099:     }
 1100:     $r->print(&Apache::loncommon::end_data_table_header_row());
 1101: 
 1102:     my @sorted_users = sort {
 1103:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
 1104:             ||
 1105:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
 1106:             ||
 1107:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
 1108: 	    ||
 1109: 	lc($a) cmp lc($b)
 1110:         } (keys(%$srch_results));
 1111: 
 1112:     foreach my $user (@sorted_users) {
 1113:         my ($uname,$udom) = split(/:/,$user);
 1114:         my $onclick;
 1115:         if ($context eq 'requestcrs') {
 1116:             $onclick =
 1117:                 'onclick="javascript:gochoose('."'$uname','$udom',".
 1118:                                                "'$srch_results->{$user}->{firstname}',".
 1119:                                                "'$srch_results->{$user}->{lastname}',".
 1120:                                                "'$srch_results->{$user}->{permanentemail}'".');"';
 1121:         } else {
 1122:             $onclick =
 1123:                 ' onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".');"';
 1124:         }
 1125:         $r->print(&Apache::loncommon::start_data_table_row().
 1126:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" '.
 1127:                   $onclick.' /></td>'.
 1128:                   '<td><tt>'.$uname.'</tt></td>'.
 1129:                   '<td><tt>'.$udom.'</tt></td>');
 1130:         foreach my $field ('lastname','firstname','permanentemail') {
 1131:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
 1132:         }
 1133:         $r->print(&Apache::loncommon::end_data_table_row());
 1134:     }
 1135:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
 1136:     if (ref($srcharray) eq 'ARRAY') {
 1137:         foreach my $item (@{$srcharray}) {
 1138:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1139:         }
 1140:     }
 1141:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
 1142:               ' <input type="hidden" name="seluname" value="" />'."\n".
 1143:               ' <input type="hidden" name="seludom" value="" />'."\n".
 1144:               ' <input type="hidden" name="currstate" value="select" />'."\n".
 1145:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
 1146:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
 1147:     if ($context eq 'requestcrs') {
 1148:         $r->print($opener_elements.'</form></div>');
 1149:     } else {
 1150:         $r->print($response.'</form>');
 1151:     }
 1152: }
 1153: 
 1154: sub print_user_query_page {
 1155:     my ($r,$caller,$brcrum) = @_;
 1156: # FIXME - this is for a network-wide name search (similar to catalog search)
 1157: # To use frames with similar behavior to catalog/portfolio search.
 1158: # To be implemented. 
 1159:     return;
 1160: }
 1161: 
 1162: sub print_user_modification_page {
 1163:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission,$crstype,
 1164:         $brcrum,$showcredits) = @_;
 1165:     if (($ccuname eq '') || ($ccdomain eq '')) {
 1166:         my $usermsg = &mt('No username and/or domain provided.');
 1167:         $env{'form.phase'} = '';
 1168: 	&print_username_entry_form($r,$context,$usermsg,'','',$crstype,$brcrum,
 1169:                                    $permission);
 1170:         return;
 1171:     }
 1172:     my ($form,$formname);
 1173:     if ($env{'form.action'} eq 'singlestudent') {
 1174:         $form = 'document.enrollstudent';
 1175:         $formname = 'enrollstudent';
 1176:     } else {
 1177:         $form = 'document.cu';
 1178:         $formname = 'cu';
 1179:     }
 1180:     my %abv_auth = &auth_abbrev();
 1181:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
 1182:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
 1183:     if ($uhome eq 'no_host') {
 1184:         my $usertype;
 1185:         my ($rules,$ruleorder) =
 1186:             &Apache::lonnet::inst_userrules($ccdomain,'username');
 1187:             $usertype =
 1188:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules,
 1189:                                                       \%curr_rules,\%got_rules);
 1190:         my $cancreate =
 1191:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
 1192:                                                    $usertype);
 1193:         if (!$cancreate) {
 1194:             my $helplink = 'javascript:helpMenu('."'display'".')';
 1195:             my %usertypetext = (
 1196:                 official   => 'institutional',
 1197:                 unofficial => 'non-institutional',
 1198:             );
 1199:             my $response;
 1200:             if ($env{'form.origform'} eq 'crtusername') {
 1201:                 $response = '<span class="LC_warning">'.
 1202:                             &mt('No match found for the username [_1] in LON-CAPA domain: [_2]',
 1203:                                 '<b>'.$ccuname.'</b>',$ccdomain).
 1204:                             '</span><br />';
 1205:             }
 1206:             $response .= '<p class="LC_warning">'
 1207:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 1208:                         .' ';
 1209:             if ($context eq 'domain') {
 1210:                 $response .= &mt('Please contact a [_1] for assistance.',
 1211:                                  &Apache::lonnet::plaintext('dc'));
 1212:             } else {
 1213:                 $response .= &mt('Please contact the [_1]helpdesk[_2] for assistance.'
 1214:                                 ,'<a href="'.$helplink.'">','</a>');
 1215:             }
 1216:             $response .= '</p><br />';
 1217:             $env{'form.phase'} = '';
 1218:             &print_username_entry_form($r,$context,$response,undef,undef,$crstype,$brcrum,
 1219:                                        $permission);
 1220:             return;
 1221:         }
 1222:         $newuser = 1;
 1223:         my $checkhash;
 1224:         my $checks = { 'username' => 1 };
 1225:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
 1226:         &Apache::loncommon::user_rule_check($checkhash,$checks,
 1227:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
 1228:         if (ref($alerts{'username'}) eq 'HASH') {
 1229:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
 1230:                 my $domdesc =
 1231:                     &Apache::lonnet::domain($ccdomain,'description');
 1232:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
 1233:                     my $userchkmsg;
 1234:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
 1235:                         $userchkmsg = 
 1236:                             &Apache::loncommon::instrule_disallow_msg('username',
 1237:                                                                  $domdesc,1).
 1238:                         &Apache::loncommon::user_rule_formats($ccdomain,
 1239:                             $domdesc,$curr_rules{$ccdomain}{'username'},
 1240:                             'username');
 1241:                     }
 1242:                     $env{'form.phase'} = '';
 1243:                     &print_username_entry_form($r,$context,$userchkmsg,undef,undef,$crstype,$brcrum,
 1244:                                                $permission);
 1245:                     return;
 1246:                 }
 1247:             }
 1248:         }
 1249:     } else {
 1250:         $newuser = 0;
 1251:     }
 1252:     if ($response) {
 1253:         $response = '<br />'.$response;
 1254:     }
 1255: 
 1256:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
 1257:     my $dc_setcourse_code = '';
 1258:     my $nondc_setsection_code = '';                                        
 1259:     my %loaditem;
 1260: 
 1261:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 1262: 
 1263:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,$crstype,
 1264:                                $groupslist,$newuser,$formname,\%loaditem);
 1265:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$ccdomain);
 1266:     my $helpitem = 'Course_Change_Privileges';
 1267:     if ($env{'form.action'} eq 'singlestudent') {
 1268:         $helpitem = 'Course_Add_Student';
 1269:     } elsif ($context eq 'author') {
 1270:         $helpitem = 'Author_Change_Privileges';
 1271:     } elsif ($context eq 'domain') {
 1272:         $helpitem = 'Domain_Change_Privileges';
 1273:     }
 1274:     push (@{$brcrum},
 1275:         {href => "javascript:backPage($form)",
 1276:          text => $breadcrumb_text{'search'},
 1277:          faq  => 282,
 1278:          bug  => 'Instructor Interface',});
 1279:     if ($env{'form.phase'} eq 'userpicked') {
 1280:        push(@{$brcrum},
 1281:               {href => "javascript:backPage($form,'get_user_info','select')",
 1282:                text => $breadcrumb_text{'userpicked'},
 1283:                faq  => 282,
 1284:                bug  => 'Instructor Interface',});
 1285:     }
 1286:     push(@{$brcrum},
 1287:             {href => "javascript:backPage($form,'$env{'form.phase'}','modify')",
 1288:              text => $breadcrumb_text{'modify'},
 1289:              faq  => 282,
 1290:              bug  => 'Instructor Interface',
 1291:              help => $helpitem});
 1292:     my $args = {'add_entries'           => \%loaditem,
 1293:                 'bread_crumbs'          => $brcrum,
 1294:                 'bread_crumbs_component' => 'User Management'};
 1295:     if ($env{'form.popup'}) {
 1296:         $args->{'no_nav_bar'} = 1;
 1297:     }
 1298:     my $start_page =
 1299:         &Apache::loncommon::start_page('User Management',$js,$args);
 1300: 
 1301:     my $forminfo =<<"ENDFORMINFO";
 1302: <form action="/adm/createuser" method="post" name="$formname">
 1303: <input type="hidden" name="phase" value="update_user_data" />
 1304: <input type="hidden" name="ccuname" value="$ccuname" />
 1305: <input type="hidden" name="ccdomain" value="$ccdomain" />
 1306: <input type="hidden" name="pres_value"  value="" />
 1307: <input type="hidden" name="pres_type"   value="" />
 1308: <input type="hidden" name="pres_marker" value="" />
 1309: ENDFORMINFO
 1310:     my (%inccourses,$roledom,$defaultcredits);
 1311:     if ($context eq 'course') {
 1312:         $inccourses{$env{'request.course.id'}}=1;
 1313:         $roledom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1314:         if ($showcredits) {
 1315:             $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1316:         }
 1317:     } elsif ($context eq 'author') {
 1318:         $roledom = $env{'request.role.domain'};
 1319:     } elsif ($context eq 'domain') {
 1320:         foreach my $key (keys(%env)) {
 1321:             $roledom = $env{'request.role.domain'};
 1322:             if ($key=~/^user\.priv\.cm\.\/($roledom)\/($match_username)/) {
 1323:                 $inccourses{$1.'_'.$2}=1;
 1324:             }
 1325:         }
 1326:     } else {
 1327:         foreach my $key (keys(%env)) {
 1328: 	    if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
 1329: 	        $inccourses{$1.'_'.$2}=1;
 1330:             }
 1331:         }
 1332:     }
 1333:     my $title = '';
 1334:     if ($newuser) {
 1335:         my ($portfolioform,$domroleform);
 1336:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
 1337:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
 1338:             # Current user has quota or user tools modification privileges
 1339:             $portfolioform = '<br />'.&user_quotas($ccuname,$ccdomain);
 1340:         }
 1341:         if ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) &&
 1342:             ($ccdomain eq $env{'request.role.domain'})) {
 1343:             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
 1344:         }
 1345:         &initialize_authen_forms($ccdomain,$formname);
 1346:         my %lt=&Apache::lonlocal::texthash(
 1347:                 'lg'             => 'Login Data',
 1348:                 'hs'             => "Home Server",
 1349:         );
 1350: 	$r->print(<<ENDTITLE);
 1351: $start_page
 1352: $response
 1353: $forminfo
 1354: <script type="text/javascript" language="Javascript">
 1355: // <![CDATA[
 1356: $loginscript
 1357: // ]]>
 1358: </script>
 1359: <input type='hidden' name='makeuser' value='1' />
 1360: ENDTITLE
 1361:         if ($env{'form.action'} eq 'singlestudent') {
 1362:             if ($crstype eq 'Community') {
 1363:                 $title = &mt('Create New User [_1] in domain [_2] as a member',
 1364:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1365:             } else {
 1366:                 $title = &mt('Create New User [_1] in domain [_2] as a student',
 1367:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1368:             }
 1369:         } else {
 1370:                 $title = &mt('Create New User [_1] in domain [_2]',
 1371:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1372:         }
 1373:         $r->print('<h2>'.$title.'</h2>'."\n");
 1374:         $r->print('<div class="LC_left_float">');
 1375:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1376:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1377:         # Option to disable student/employee ID conflict checking not offerred for new users.
 1378:         my ($home_server_pick,$numlib) = 
 1379:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
 1380:                                                       'default','hide');
 1381:         if ($numlib > 1) {
 1382:             $r->print("
 1383: <br />
 1384: $lt{'hs'}: $home_server_pick
 1385: <br />");
 1386:         } else {
 1387:             $r->print($home_server_pick);
 1388:         }
 1389:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 1390:             $r->print('<br /><h3>'.
 1391:                       &mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'.
 1392:                       &Apache::loncommon::start_data_table().
 1393:                       &build_tools_display($ccuname,$ccdomain,
 1394:                                            'requestcourses').
 1395:                       &Apache::loncommon::end_data_table());
 1396:         }
 1397:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
 1398:                   $lt{'lg'}.'</h3>');
 1399:         my ($fixedauth,$varauth,$authmsg); 
 1400:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
 1401:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
 1402:             my ($rules,$ruleorder) = 
 1403:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
 1404:             if (ref($rules) eq 'HASH') {
 1405:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
 1406:                     my $authtype = $rules->{$matchedrule}{'authtype'};
 1407:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
 1408:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1409:                     } else { 
 1410:                         my $authparm = $rules->{$matchedrule}{'authparm'};
 1411:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
 1412:                         if ($authtype =~ /^krb(4|5)$/) {
 1413:                             my $ver = $1;
 1414:                             if ($authparm ne '') {
 1415:                                 $fixedauth = <<"KERB"; 
 1416: <input type="hidden" name="login" value="krb" />
 1417: <input type="hidden" name="krbver" value="$ver" />
 1418: <input type="hidden" name="krbarg" value="$authparm" />
 1419: KERB
 1420:                             }
 1421:                         } else {
 1422:                             $fixedauth = 
 1423: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
 1424:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
 1425:                                 $fixedauth .=    
 1426: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
 1427:                             } else {
 1428:                                 if ($authtype eq 'int') {
 1429:                                     $varauth = '<br />'.
 1430: &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>';
 1431:                                 } elsif ($authtype eq 'loc') {
 1432:                                     $varauth = '<br />'.
 1433: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
 1434:                                 } else {
 1435:                                     $varauth =
 1436: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
 1437:                                 }
 1438:                             }
 1439:                         }
 1440:                     }
 1441:                 } else {
 1442:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
 1443:                 }
 1444:             }
 1445:             if ($authmsg) {
 1446:                 $r->print(<<ENDAUTH);
 1447: $fixedauth
 1448: $authmsg
 1449: $varauth
 1450: ENDAUTH
 1451:             }
 1452:         } else {
 1453:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
 1454:         }
 1455:         $r->print($portfolioform.$domroleform);
 1456:         if ($env{'form.action'} eq 'singlestudent') {
 1457:             $r->print(&date_sections_select($context,$newuser,$formname,
 1458:                                             $permission,$crstype,$ccuname,
 1459:                                             $ccdomain,$showcredits));
 1460:         }
 1461:         $r->print('</div><div class="LC_clear_float_footer"></div>');
 1462:     } else { # user already exists
 1463: 	$r->print($start_page.$forminfo);
 1464:         if ($env{'form.action'} eq 'singlestudent') {
 1465:             if ($crstype eq 'Community') {
 1466:                 $title = &mt('Enroll one member: [_1] in domain [_2]',
 1467:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1468:             } else {
 1469:                 $title = &mt('Enroll one student: [_1] in domain [_2]',
 1470:                                  '"'.$ccuname.'"','"'.$ccdomain.'"');
 1471:             }
 1472:         } else {
 1473:             if ($permission->{'cusr'}) {
 1474:                 $title = &mt('Modify existing user: [_1] in domain [_2]',
 1475:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1476:             } else {
 1477:                 $title = &mt('Existing user: [_1] in domain [_2]',
 1478:                              '"'.$ccuname.'"','"'.$ccdomain.'"');
 1479:             }
 1480:         }
 1481:         $r->print('<h2>'.$title.'</h2>'."\n");
 1482:         $r->print('<div class="LC_left_float">');
 1483:         $r->print(&personal_data_display($ccuname,$ccdomain,$newuser,$context,
 1484:                                          $inst_results{$ccuname.':'.$ccdomain}));
 1485:         if ((&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) ||
 1486:             (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) {
 1487:             $r->print('<br /><h3>'.&mt('User Can Request Creation of Courses/Communities in this Domain?').'</h3>'."\n");
 1488:             if (($env{'request.role.domain'} eq $ccdomain) ||
 1489:                 (&Apache::lonnet::will_trust('reqcrs',$ccdomain,$env{'request.role.domain'}))) {
 1490:                 $r->print(&Apache::loncommon::start_data_table());
 1491:                 if ($env{'request.role.domain'} eq $ccdomain) {
 1492:                     $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
 1493:                 } else {
 1494:                     $r->print(&coursereq_externaluser($ccuname,$ccdomain,
 1495:                                                       $env{'request.role.domain'}));
 1496:                 }
 1497:                 $r->print(&Apache::loncommon::end_data_table());
 1498:             } else {
 1499:                 $r->print(&mt('Domain configuration for this domain prohibits course creation by users from domain: "[_1]"',
 1500:                               &Apache::lonnet::domain($ccdomain,'description')));
 1501:             }
 1502:         }
 1503:         $r->print('</div>');
 1504:         my @order = ('auth','quota','tools','requestauthor');
 1505:         my %user_text;
 1506:         my ($isadv,$isauthor) = 
 1507:             &Apache::lonnet::is_advanced_user($ccdomain,$ccuname);
 1508:         if ((!$isauthor) && 
 1509:             ((&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
 1510:              (&Apache::lonnet::allowed('udp',$env{'request.role.domain'}))) &&
 1511:              ($env{'request.role.domain'} eq $ccdomain)) {
 1512:             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
 1513:         }
 1514:         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname,$crstype,$permission);
 1515:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
 1516:             (&Apache::lonnet::allowed('mut',$ccdomain)) ||
 1517:             (&Apache::lonnet::allowed('udp',$ccdomain))) {
 1518:             # Current user has quota modification privileges
 1519:             $user_text{'quota'} = &user_quotas($ccuname,$ccdomain);
 1520:         }
 1521:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
 1522:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1523:                 my %lt=&Apache::lonlocal::texthash(
 1524:                     'dska'  => "Disk quotas for user's portfolio and Authoring Space",
 1525:                     'youd'  => "You do not have privileges to modify the portfolio and/or Authoring Space quotas for this user.",
 1526:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
 1527:                 );
 1528:                 $user_text{'quota'} = <<ENDNOPORTPRIV;
 1529: <h3>$lt{'dska'}</h3>
 1530: $lt{'youd'} $lt{'ichr'}: $ccdomain
 1531: ENDNOPORTPRIV
 1532:             }
 1533:         }
 1534:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
 1535:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
 1536:                 my %lt=&Apache::lonlocal::texthash(
 1537:                     'utav'  => "User Tools Availability",
 1538:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog, WebDAV, or Personal Information Page settings for this user.",
 1539:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1540:                 );
 1541:                 $user_text{'tools'} = <<ENDNOTOOLSPRIV;
 1542: <h3>$lt{'utav'}</h3>
 1543: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 1544: ENDNOTOOLSPRIV
 1545:             }
 1546:         }
 1547:         my $gotdiv = 0; 
 1548:         foreach my $item (@order) {
 1549:             if ($user_text{$item} ne '') {
 1550:                 unless ($gotdiv) {
 1551:                     $r->print('<div class="LC_left_float">');
 1552:                     $gotdiv = 1;
 1553:                 }
 1554:                 $r->print('<br />'.$user_text{$item});
 1555:             }
 1556:         }
 1557:         if ($env{'form.action'} eq 'singlestudent') {
 1558:             unless ($gotdiv) {
 1559:                 $r->print('<div class="LC_left_float">');
 1560:             }
 1561:             my $credits;
 1562:             if ($showcredits) {
 1563:                 $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1564:                 if ($credits eq '') {
 1565:                     $credits = $defaultcredits;
 1566:                 }
 1567:             }
 1568:             $r->print(&date_sections_select($context,$newuser,$formname,
 1569:                                             $permission,$crstype,$ccuname,
 1570:                                             $ccdomain,$showcredits));
 1571:         }
 1572:         if ($gotdiv) {
 1573:             $r->print('</div><div class="LC_clear_float_footer"></div>');
 1574:         }
 1575:         my $statuses;
 1576:         if (($context eq 'domain') && (&Apache::lonnet::allowed('udp',$ccdomain)) &&
 1577:             (!&Apache::lonnet::allowed('mau',$ccdomain))) {
 1578:             $statuses = ['active'];
 1579:         } elsif (($context eq 'course') && ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1580:                  ($env{'request.course.sec'} &&
 1581:                   &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'})))) {
 1582:             $statuses = ['active'];
 1583:         }
 1584:         if ($env{'form.action'} ne 'singlestudent') {
 1585:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses,$context,
 1586:                                     $roledom,$crstype,$showcredits,$statuses);
 1587:         }
 1588:     } ## End of new user/old user logic
 1589:     if ($env{'form.action'} eq 'singlestudent') {
 1590:         my $btntxt;
 1591:         if ($crstype eq 'Community') {
 1592:             $btntxt = &mt('Enroll Member');
 1593:         } else {
 1594:             $btntxt = &mt('Enroll Student');
 1595:         }
 1596:         $r->print('<br /><input type="button" value="'.$btntxt.'" onclick="setSections(this.form)" />'."\n");
 1597:     } elsif ($permission->{'cusr'}) {
 1598:         $r->print('<div class="LC_left_float">'.
 1599:                   '<fieldset><legend>'.&mt('Add Roles').'</legend>');
 1600:         my $addrolesdisplay = 0;
 1601:         if ($context eq 'domain' || $context eq 'author') {
 1602:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
 1603:         }
 1604:         if ($context eq 'domain') {
 1605:             my $add_domainroles = &new_domain_roles($r,$ccdomain);
 1606:             if (!$addrolesdisplay) {
 1607:                 $addrolesdisplay = $add_domainroles;
 1608:             }
 1609:             $r->print(&course_level_dc($env{'request.role.domain'},$showcredits));
 1610:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1611:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setCourse()" />'."\n");
 1612:         } elsif ($context eq 'author') {
 1613:             if ($addrolesdisplay) {
 1614:                 $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1615:                           '<br /><input type="button" value="'.&mt('Save').'"');
 1616:                 if ($newuser) {
 1617:                     $r->print(' onclick="auth_check()" \>'."\n");
 1618:                 } else {
 1619:                     $r->print('onclick="this.form.submit()" \>'."\n");
 1620:                 }
 1621:             } else {
 1622:                 $r->print('</fieldset></div>'.
 1623:                           '<div class="LC_clear_float_footer"></div>'.
 1624:                           '<br /><a href="javascript:backPage(document.cu)">'.
 1625:                           &mt('Back to previous page').'</a>');
 1626:             }
 1627:         } else {
 1628:             $r->print(&course_level_table(\%inccourses,$showcredits,$defaultcredits));
 1629:             $r->print('</fieldset></div><div class="LC_clear_float_footer"></div>'.
 1630:                       '<br /><input type="button" value="'.&mt('Save').'" onclick="setSections(this.form)" />'."\n");
 1631:         }
 1632:     }
 1633:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
 1634:     $r->print('<input type="hidden" name="currstate" value="" />');
 1635:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" /></form><br /><br />');
 1636:     return;
 1637: }
 1638: 
 1639: sub singleuser_breadcrumb {
 1640:     my ($crstype,$context,$domain) = @_;
 1641:     my %breadcrumb_text;
 1642:     if ($env{'form.action'} eq 'singlestudent') {
 1643:         if ($crstype eq 'Community') {
 1644:             $breadcrumb_text{'search'} = 'Enroll a member';
 1645:         } else {
 1646:             $breadcrumb_text{'search'} = 'Enroll a student';
 1647:         }
 1648:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1649:         $breadcrumb_text{'modify'} = 'Set section/dates';
 1650:     } elsif ($env{'form.action'} eq 'accesslogs') {
 1651:         $breadcrumb_text{'search'} = 'View access logs for a user';
 1652:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1653:         $breadcrumb_text{'activity'} = 'Activity';
 1654:     } elsif (($env{'form.action'} eq 'singleuser') && ($context eq 'domain') &&
 1655:              (!&Apache::lonnet::allowed('mau',$domain))) {
 1656:         $breadcrumb_text{'search'} = "View user's roles";
 1657:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1658:         $breadcrumb_text{'modify'} = 'User roles';
 1659:     } else {
 1660:         $breadcrumb_text{'search'} = 'Create/modify a user';
 1661:         $breadcrumb_text{'userpicked'} = 'Select a user';
 1662:         $breadcrumb_text{'modify'} = 'Set user role';
 1663:     }
 1664:     return %breadcrumb_text;
 1665: }
 1666: 
 1667: sub date_sections_select {
 1668:     my ($context,$newuser,$formname,$permission,$crstype,$ccuname,$ccdomain,
 1669:         $showcredits) = @_;
 1670:     my $credits;
 1671:     if ($showcredits) {
 1672:         my $defaultcredits = &Apache::lonuserutils::get_defaultcredits();
 1673:         $credits = &get_user_credits($ccuname,$ccdomain,$defaultcredits);
 1674:         if ($credits eq '') {
 1675:             $credits = $defaultcredits;
 1676:         }
 1677:     }
 1678:     my $cid = $env{'request.course.id'};
 1679:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
 1680:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
 1681:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
 1682:                                                   undef,$formname,$permission);
 1683:     my $rowtitle = 'Section';
 1684:     my $secbox = '<h3>'.&mt('Section and Credits').'</h3>'."\n".
 1685:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
 1686:                                               $permission,$context,'',$crstype,
 1687:                                               $showcredits,$credits);
 1688:     my $output = $date_table.$secbox;
 1689:     return $output;
 1690: }
 1691: 
 1692: sub validation_javascript {
 1693:     my ($context,$ccdomain,$pjump_def,$crstype,$groupslist,$newuser,$formname,
 1694:         $loaditem) = @_;
 1695:     my $dc_setcourse_code = '';
 1696:     my $nondc_setsection_code = '';
 1697:     if ($context eq 'domain') {
 1698:         my $dcdom = $env{'request.role.domain'};
 1699:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
 1700:         $dc_setcourse_code = 
 1701:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
 1702:     } else {
 1703:         my $checkauth; 
 1704:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
 1705:             $checkauth = 1;
 1706:         }
 1707:         if ($context eq 'course') {
 1708:             $nondc_setsection_code =
 1709:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
 1710:                                                               undef,$checkauth,
 1711:                                                               $crstype);
 1712:         }
 1713:         if ($checkauth) {
 1714:             $nondc_setsection_code .= 
 1715:                 &Apache::lonuserutils::verify_authen($formname,$context);
 1716:         }
 1717:     }
 1718:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
 1719:                                    $nondc_setsection_code,$groupslist);
 1720:     my ($jsback,$elements) = &crumb_utilities();
 1721:     $js .= "\n".
 1722:            '<script type="text/javascript">'."\n".
 1723:            '// <![CDATA['."\n".
 1724:            $jsback."\n".
 1725:            '// ]]>'."\n".
 1726:            '</script>'."\n";
 1727:     return $js;
 1728: }
 1729: 
 1730: sub display_existing_roles {
 1731:     my ($r,$ccuname,$ccdomain,$inccourses,$context,$roledom,$crstype,
 1732:         $showcredits,$statuses) = @_;
 1733:     my $now=time;
 1734:     my $showall = 1;
 1735:     my ($showexpired,$showactive);
 1736:     if ((ref($statuses) eq 'ARRAY') && (@{$statuses} > 0)) {
 1737:         $showall = 0;
 1738:         if (grep(/^expired$/,@{$statuses})) {
 1739:             $showexpired = 1;
 1740:         }
 1741:         if (grep(/^active$/,@{$statuses})) {
 1742:             $showactive = 1;
 1743:         }
 1744:         if ($showexpired && $showactive) {
 1745:             $showall = 1;
 1746:         }
 1747:     }
 1748:     my %lt=&Apache::lonlocal::texthash(
 1749:                     'rer'  => "Existing Roles",
 1750:                     'rev'  => "Revoke",
 1751:                     'del'  => "Delete",
 1752:                     'ren'  => "Re-Enable",
 1753:                     'rol'  => "Role",
 1754:                     'ext'  => "Extent",
 1755:                     'crd'  => "Credits",
 1756:                     'sta'  => "Start",
 1757:                     'end'  => "End",
 1758:                                        );
 1759:     my (%rolesdump,%roletext,%sortrole,%roleclass,%rolepriv);
 1760:     if ($context eq 'course' || $context eq 'author') {
 1761:         my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 1762:         my %roleshash = 
 1763:             &Apache::lonnet::get_my_roles($ccuname,$ccdomain,'userroles',
 1764:                               ['active','previous','future'],\@roles,$roledom,1);
 1765:         foreach my $key (keys(%roleshash)) {
 1766:             my ($start,$end) = split(':',$roleshash{$key});
 1767:             next if ($start eq '-1' || $end eq '-1');
 1768:             my ($rnum,$rdom,$role,$sec) = split(':',$key);
 1769:             if ($context eq 'course') {
 1770:                 next unless (($rnum eq $env{'course.'.$env{'request.course.id'}.'.num'})
 1771:                              && ($rdom eq $env{'course.'.$env{'request.course.id'}.'.domain'}));
 1772:             } elsif ($context eq 'author') {
 1773:                 next unless (($rnum eq $env{'user.name'}) && ($rdom eq $env{'request.role.domain'}));
 1774:             }
 1775:             my ($newkey,$newvalue,$newrole);
 1776:             $newkey = '/'.$rdom.'/'.$rnum;
 1777:             if ($sec ne '') {
 1778:                 $newkey .= '/'.$sec;
 1779:             }
 1780:             $newvalue = $role;
 1781:             if ($role =~ /^cr/) {
 1782:                 $newrole = 'cr';
 1783:             } else {
 1784:                 $newrole = $role;
 1785:             }
 1786:             $newkey .= '_'.$newrole;
 1787:             if ($start ne '' && $end ne '') {
 1788:                 $newvalue .= '_'.$end.'_'.$start;
 1789:             } elsif ($end ne '') {
 1790:                 $newvalue .= '_'.$end;
 1791:             }
 1792:             $rolesdump{$newkey} = $newvalue;
 1793:         }
 1794:     } else {
 1795:         %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
 1796:     }
 1797:     # Build up table of user roles to allow revocation and re-enabling of roles.
 1798:     my ($tmp) = keys(%rolesdump);
 1799:     return if ($tmp =~ /^(con_lost|error)/i);
 1800:     foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
 1801:                                 my $b1=join('_',(split('_',$b))[1,0]);
 1802:                                 return $a1 cmp $b1;
 1803:                             } keys(%rolesdump)) {
 1804:         next if ($area =~ /^rolesdef/);
 1805:         my $envkey=$area;
 1806:         my $role = $rolesdump{$area};
 1807:         my $thisrole=$area;
 1808:         $area =~ s/\_\w\w$//;
 1809:         my ($role_code,$role_end_time,$role_start_time) =
 1810:             split(/_/,$role);
 1811:         my $active=1;
 1812:         $active=0 if (($role_end_time) && ($now>$role_end_time));
 1813:         if ($active) {
 1814:             next unless($showall || $showactive);
 1815:         } else {
 1816:             next unless($showall || $showexpired);
 1817:         }
 1818: # Is this a custom role? Get role owner and title.
 1819:         my ($croleudom,$croleuname,$croletitle)=
 1820:             ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
 1821:         my $allowed=0;
 1822:         my $delallowed=0;
 1823:         my $sortkey=$role_code;
 1824:         my $class='Unknown';
 1825:         my $credits='';
 1826:         my $csec;
 1827:         if ($area =~ m{^/($match_domain)/($match_courseid)}) {
 1828:             $class='Course';
 1829:             my ($coursedom,$coursedir) = ($1,$2);
 1830:             my $cid = $1.'_'.$2;
 1831:             # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
 1832:             next if ($envkey =~ m{^/$match_domain/$match_courseid/[A-Za-z0-9]+_gr$});
 1833:             my %coursedata=
 1834:                 &Apache::lonnet::coursedescription($cid);
 1835:             if ($coursedir =~ /^$match_community$/) {
 1836:                 $class='Community';
 1837:             }
 1838:             $sortkey.="\0$coursedom";
 1839:             my $carea;
 1840:             if (defined($coursedata{'description'})) {
 1841:                 $carea=$coursedata{'description'}.
 1842:                     '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
 1843:     &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
 1844:                 $sortkey.="\0".$coursedata{'description'};
 1845:             } else {
 1846:                 if ($class eq 'Community') {
 1847:                     $carea=&mt('Unavailable community').': '.$area;
 1848:                     $sortkey.="\0".&mt('Unavailable community').': '.$area;
 1849:                 } else {
 1850:                     $carea=&mt('Unavailable course').': '.$area;
 1851:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
 1852:                 }
 1853:             }
 1854:             $sortkey.="\0$coursedir";
 1855:             $inccourses->{$cid}=1;
 1856:             if (($showcredits) && ($class eq 'Course') && ($role_code eq 'st')) {
 1857:                 my $defaultcredits = $coursedata{'internal.defaultcredits'};
 1858:                 $credits =
 1859:                     &get_user_credits($ccuname,$ccdomain,$defaultcredits,
 1860:                                       $coursedom,$coursedir);
 1861:                 if ($credits eq '') {
 1862:                     $credits = $defaultcredits;
 1863:                 }
 1864:             }
 1865:             if ((&Apache::lonnet::allowed('c'.$role_code,$coursedom.'/'.$coursedir)) ||
 1866:                 (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1867:                 $allowed=1;
 1868:             }
 1869:             unless ($allowed) {
 1870:                 my $isowner = &Apache::lonuserutils::is_courseowner($cid,$coursedata{'internal.courseowner'});
 1871:                 if ($isowner) {
 1872:                     if (($role_code eq 'co') && ($class eq 'Community')) {
 1873:                         $allowed = 1;
 1874:                     } elsif (($role_code eq 'cc') && ($class eq 'Course')) {
 1875:                         $allowed = 1;
 1876:                     }
 1877:                 }
 1878:             } 
 1879:             if ((&Apache::lonnet::allowed('dro',$coursedom)) ||
 1880:                 (&Apache::lonnet::allowed('dro',$ccdomain))) {
 1881:                 $delallowed=1;
 1882:             }
 1883: # - custom role. Needs more info, too
 1884:             if ($croletitle) {
 1885:                 if (&Apache::lonnet::allowed('ccr',$coursedom.'/'.$coursedir)) {
 1886:                     $allowed=1;
 1887:                     $thisrole.='.'.$role_code;
 1888:                 }
 1889:             }
 1890:             if ($area=~m{^/($match_domain/$match_courseid/(\w+))}) {
 1891:                 $csec = $2;
 1892:                 $carea.='<br />'.&mt('Section: [_1]',$csec);
 1893:                 $sortkey.="\0$csec";
 1894:                 if (!$allowed) {
 1895:                     if ($env{'request.course.sec'} eq $csec) {
 1896:                         if (&Apache::lonnet::allowed('c'.$role_code,$1)) {
 1897:                             $allowed = 1;
 1898:                         }
 1899:                     }
 1900:                 }
 1901:             }
 1902:             $area=$carea;
 1903:         } else {
 1904:             $sortkey.="\0".$area;
 1905:             # Determine if current user is able to revoke privileges
 1906:             if ($area=~m{^/($match_domain)/}) {
 1907:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
 1908:                    (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
 1909:                    $allowed=1;
 1910:                 }
 1911:                 if (((&Apache::lonnet::allowed('dro',$1))  ||
 1912:                     (&Apache::lonnet::allowed('dro',$ccdomain))) &&
 1913:                     ($role_code ne 'dc')) {
 1914:                     $delallowed=1;
 1915:                 }
 1916:             } else {
 1917:                 if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
 1918:                     $allowed=1;
 1919:                 }
 1920:             }
 1921:             if ($role_code eq 'ca' || $role_code eq 'au' || $role_code eq 'aa') {
 1922:                 $class='Authoring Space';
 1923:             } elsif ($role_code eq 'su') {
 1924:                 $class='System';
 1925:             } else {
 1926:                 $class='Domain';
 1927:             }
 1928:         }
 1929:         if (($role_code eq 'ca') || ($role_code eq 'aa')) {
 1930:             $area=~m{/($match_domain)/($match_username)};
 1931:             if (&Apache::lonuserutils::authorpriv($2,$1)) {
 1932:                 $allowed=1;
 1933:             } else {
 1934:                 $allowed=0;
 1935:             }
 1936:         }
 1937:         my $row = '';
 1938:         if ($showall) {
 1939:             $row.= '<td>';
 1940:             if (($active) && ($allowed)) {
 1941:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
 1942:             } else {
 1943:                 if ($active) {
 1944:                     $row.='&nbsp;';
 1945:                 } else {
 1946:                     $row.=&mt('expired or revoked');
 1947:                 }
 1948:             }
 1949:             $row.='</td><td>';
 1950:             if ($allowed && !$active) {
 1951:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1952:             } else {
 1953:                 $row.='&nbsp;';
 1954:             }
 1955:             $row.='</td><td>';
 1956:             if ($delallowed) {
 1957:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1958:             } else {
 1959:                 $row.='&nbsp;';
 1960:             }
 1961:             $row.= '</td>';
 1962:         }
 1963:         my $plaintext='';
 1964:         if (!$croletitle) {
 1965:             $plaintext=&Apache::lonnet::plaintext($role_code,$class);
 1966:             if (($showcredits) && ($credits ne '')) {
 1967:                 $plaintext .= '<br/ ><span class="LC_nobreak">'.
 1968:                               '<span class="LC_fontsize_small">'.
 1969:                               &mt('Credits: [_1]',$credits).
 1970:                               '</span></span>';
 1971:             }
 1972:         } else {
 1973:             $plaintext=
 1974:                 &mt('Custom role [_1][_2]defined by [_3]',
 1975:                         '"'.$croletitle.'"',
 1976:                         '<br />',
 1977:                         $croleuname.':'.$croleudom);
 1978:         }
 1979:         $row.= '<td>'.$plaintext.'</td>'.
 1980:                '<td>'.$area.'</td>'.
 1981:                '<td>'.($role_start_time?&Apache::lonlocal::locallocaltime($role_start_time)
 1982:                                             : '&nbsp;' ).'</td>'.
 1983:                '<td>'.($role_end_time  ?&Apache::lonlocal::locallocaltime($role_end_time)
 1984:                                             : '&nbsp;' ).'</td>';
 1985:         $sortrole{$sortkey}=$envkey;
 1986:         $roletext{$envkey}=$row;
 1987:         $roleclass{$envkey}=$class;
 1988:         if ($allowed) {
 1989:             $rolepriv{$envkey}='edit';
 1990:         } else {
 1991:             if ($context eq 'domain') {
 1992:                 if ((&Apache::lonnet::allowed('vur',$ccdomain)) &&
 1993:                     ($envkey=~m{^/$ccdomain/})) {
 1994:                     $rolepriv{$envkey}='view';
 1995:                 }
 1996:             } elsif ($context eq 'course') {
 1997:                 if ((&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) ||
 1998:                     ($env{'request.course.sec'} && ($env{'request.course.sec'} eq $csec) &&
 1999:                      &Apache::lonnet::allowed('vcl',$env{'request.course.id'}.'/'.$env{'request.course.sec'}))) {
 2000:                     $rolepriv{$envkey}='view';
 2001:                 }
 2002:             }
 2003:         }
 2004:     } # end of foreach        (table building loop)
 2005: 
 2006:     my $rolesdisplay = 0;
 2007:     my %output = ();
 2008:     foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2009:         $output{$type} = '';
 2010:         foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 2011:             if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
 2012:                  $output{$type}.=
 2013:                       &Apache::loncommon::start_data_table_row().
 2014:                       $roletext{$sortrole{$which}}.
 2015:                       &Apache::loncommon::end_data_table_row();
 2016:             }
 2017:         }
 2018:         unless($output{$type} eq '') {
 2019:             $output{$type} = '<tr class="LC_info_row">'.
 2020:                       "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 2021:                       $output{$type};
 2022:             $rolesdisplay = 1;
 2023:         }
 2024:     }
 2025:     if ($rolesdisplay == 1) {
 2026:         my $contextrole='';
 2027:         if ($env{'request.course.id'}) {
 2028:             if (&Apache::loncommon::course_type() eq 'Community') {
 2029:                 $contextrole = &mt('Existing Roles in this Community');
 2030:             } else {
 2031:                 $contextrole = &mt('Existing Roles in this Course');
 2032:             }
 2033:         } elsif ($env{'request.role'} =~ /^au\./) {
 2034:             $contextrole = &mt('Existing Co-Author Roles in your Authoring Space');
 2035:         } else {
 2036:             if ($showall) {
 2037:                 $contextrole = &mt('Existing Roles in this Domain');
 2038:             } elsif ($showactive) {
 2039:                 $contextrole = &mt('Unexpired Roles in this Domain');
 2040:             } elsif ($showexpired) {
 2041:                 $contextrole = &mt('Expired or Revoked Roles in this Domain');
 2042:             }
 2043:         }
 2044:         $r->print('<div class="LC_left_float">'.
 2045: '<fieldset><legend>'.$contextrole.'</legend>'.
 2046: &Apache::loncommon::start_data_table("LC_createuser").
 2047: &Apache::loncommon::start_data_table_header_row());
 2048:         if ($showall) {
 2049:             $r->print(
 2050: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.'</th>'
 2051:             );
 2052:         } elsif ($showexpired) {
 2053:             $r->print('<th>'.$lt{'rev'}.'</th>');
 2054:         }
 2055:         $r->print(
 2056: '<th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>'.
 2057: '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2058: &Apache::loncommon::end_data_table_header_row());
 2059:         foreach my $type ('Authoring Space','Course','Community','Domain','System','Unknown') {
 2060:             if ($output{$type}) {
 2061:                 $r->print($output{$type}."\n");
 2062:             }
 2063:         }
 2064:         $r->print(&Apache::loncommon::end_data_table().
 2065:                   '</fieldset></div>');
 2066:     }
 2067:     return;
 2068: }
 2069: 
 2070: sub new_coauthor_roles {
 2071:     my ($r,$ccuname,$ccdomain) = @_;
 2072:     my $addrolesdisplay = 0;
 2073:     #
 2074:     # Co-Author
 2075:     #
 2076:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
 2077:                                           $env{'request.role.domain'}) &&
 2078:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 2079:         # No sense in assigning co-author role to yourself
 2080:         $addrolesdisplay = 1;
 2081:         my $cuname=$env{'user.name'};
 2082:         my $cudom=$env{'request.role.domain'};
 2083:         my %lt=&Apache::lonlocal::texthash(
 2084:                     'cs'   => "Authoring Space",
 2085:                     'act'  => "Activate",
 2086:                     'rol'  => "Role",
 2087:                     'ext'  => "Extent",
 2088:                     'sta'  => "Start",
 2089:                     'end'  => "End",
 2090:                     'cau'  => "Co-Author",
 2091:                     'caa'  => "Assistant Co-Author",
 2092:                     'ssd'  => "Set Start Date",
 2093:                     'sed'  => "Set End Date"
 2094:                                        );
 2095:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
 2096:                   &Apache::loncommon::start_data_table()."\n".
 2097:                   &Apache::loncommon::start_data_table_header_row()."\n".
 2098:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 2099:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 2100:                   '<th>'.$lt{'end'}.'</th>'."\n".
 2101:                   &Apache::loncommon::end_data_table_header_row()."\n".
 2102:                   &Apache::loncommon::start_data_table_row().'
 2103:            <td>
 2104:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
 2105:            </td>
 2106:            <td>'.$lt{'cau'}.'</td>
 2107:            <td>'.$cudom.'_'.$cuname.'</td>
 2108:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 2109:              <a href=
 2110: "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>
 2111: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 2112: <a href=
 2113: "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".
 2114:               &Apache::loncommon::end_data_table_row()."\n".
 2115:               &Apache::loncommon::start_data_table_row()."\n".
 2116: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 2117: <td>'.$lt{'caa'}.'</td>
 2118: <td>'.$cudom.'_'.$cuname.'</td>
 2119: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 2120: <a href=
 2121: "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>
 2122: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 2123: <a href=
 2124: "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".
 2125:              &Apache::loncommon::end_data_table_row()."\n".
 2126:              &Apache::loncommon::end_data_table());
 2127:     } elsif ($env{'request.role'} =~ /^au\./) {
 2128:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
 2129:                                                 $env{'request.role.domain'}))) {
 2130:             $r->print('<span class="LC_error">'.
 2131:                       &mt('You do not have privileges to assign co-author roles.').
 2132:                       '</span>');
 2133:         } elsif (($env{'user.name'} eq $ccuname) &&
 2134:              ($env{'user.domain'} eq $ccdomain)) {
 2135:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Authoring Space is not permitted'));
 2136:         }
 2137:     }
 2138:     return $addrolesdisplay;;
 2139: }
 2140: 
 2141: sub new_domain_roles {
 2142:     my ($r,$ccdomain) = @_;
 2143:     my $addrolesdisplay = 0;
 2144:     #
 2145:     # Domain level
 2146:     #
 2147:     my $num_domain_level = 0;
 2148:     my $domaintext =
 2149:     '<h4>'.&mt('Domain Level').'</h4>'.
 2150:     &Apache::loncommon::start_data_table().
 2151:     &Apache::loncommon::start_data_table_header_row().
 2152:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 2153:     &mt('Extent').'</th>'.
 2154:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 2155:     &Apache::loncommon::end_data_table_header_row();
 2156:     my @allroles = &Apache::lonuserutils::roles_by_context('domain');
 2157:     my $uprimary = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 2158:     my $uintdom = &Apache::lonnet::internet_dom($uprimary);
 2159:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 2160:         foreach my $role (@allroles) {
 2161:             next if ($role eq 'ad');
 2162:             next if (($role eq 'au') && ($ccdomain ne $thisdomain));
 2163:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 2164:                if ($role eq 'dc') {
 2165:                    unless ($thisdomain eq $env{'request.role.domain'}) {
 2166:                        my $domprim = &Apache::lonnet::domain($thisdomain,'primary');
 2167:                        my $intdom = &Apache::lonnet::internet_dom($domprim);
 2168:                        next unless ($uintdom eq $intdom);
 2169:                    }
 2170:                }
 2171:                my $plrole=&Apache::lonnet::plaintext($role);
 2172:                my %lt=&Apache::lonlocal::texthash(
 2173:                     'ssd'  => "Set Start Date",
 2174:                     'sed'  => "Set End Date"
 2175:                                        );
 2176:                $num_domain_level ++;
 2177:                $domaintext .=
 2178: &Apache::loncommon::start_data_table_row().
 2179: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
 2180: <td>'.$plrole.'</td>
 2181: <td>'.$thisdomain.'</td>
 2182: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 2183: <a href=
 2184: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 2185: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 2186: <a href=
 2187: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 2188: &Apache::loncommon::end_data_table_row();
 2189:             }
 2190:         }
 2191:     }
 2192:     $domaintext.= &Apache::loncommon::end_data_table();
 2193:     if ($num_domain_level > 0) {
 2194:         $r->print($domaintext);
 2195:         $addrolesdisplay = 1;
 2196:     }
 2197:     return $addrolesdisplay;
 2198: }
 2199: 
 2200: sub user_authentication {
 2201:     my ($ccuname,$ccdomain,$formname,$crstype,$permission) = @_;
 2202:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 2203:     my $outcome;
 2204:     my %lt=&Apache::lonlocal::texthash(
 2205:                    'err'   => "ERROR",
 2206:                    'uuas'  => "This user has an unrecognized authentication scheme",
 2207:                    'adcs'  => "Please alert a domain coordinator of this situation",
 2208:                    'sldb'  => "Please specify login data below",
 2209:                    'ld'    => "Login Data"
 2210:     );
 2211:     # Check for a bad authentication type
 2212:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth|lti):/) {
 2213:         # bad authentication scheme
 2214:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2215:             &initialize_authen_forms($ccdomain,$formname);
 2216: 
 2217:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
 2218:             $outcome = <<ENDBADAUTH;
 2219: <script type="text/javascript" language="Javascript">
 2220: // <![CDATA[
 2221: $loginscript
 2222: // ]]>
 2223: </script>
 2224: <span class="LC_error">$lt{'err'}:
 2225: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
 2226: <h3>$lt{'ld'}</h3>
 2227: $choices
 2228: ENDBADAUTH
 2229:         } else {
 2230:             # This user is not allowed to modify the user's
 2231:             # authentication scheme, so just notify them of the problem
 2232:             $outcome = <<ENDBADAUTH;
 2233: <span class="LC_error"> $lt{'err'}: 
 2234: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 2235: </span>
 2236: ENDBADAUTH
 2237:         }
 2238:     } else { # Authentication type is valid
 2239:         
 2240:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
 2241:         my ($authformcurrent,$can_modify,@authform_others) =
 2242:             &modify_login_block($ccdomain,$currentauth);
 2243:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2244:             # Current user has login modification privileges
 2245:             $outcome =
 2246:                        '<script type="text/javascript" language="Javascript">'."\n".
 2247:                        '// <![CDATA['."\n".
 2248:                        $loginscript."\n".
 2249:                        '// ]]>'."\n".
 2250:                        '</script>'."\n".
 2251:                        '<h3>'.$lt{'ld'}.'</h3>'.
 2252:                        &Apache::loncommon::start_data_table().
 2253:                        &Apache::loncommon::start_data_table_row().
 2254:                        '<td>'.$authformnop;
 2255:             if (($can_modify) && (&Apache::lonnet::allowed('mau',$ccdomain))) {
 2256:                 $outcome .= '</td>'."\n".
 2257:                             &Apache::loncommon::end_data_table_row().
 2258:                             &Apache::loncommon::start_data_table_row().
 2259:                             '<td>'.$authformcurrent.'</td>'.
 2260:                             &Apache::loncommon::end_data_table_row()."\n";
 2261:             } else {
 2262:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
 2263:                             &Apache::loncommon::end_data_table_row()."\n";
 2264:             }
 2265:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 2266:                 foreach my $item (@authform_others) { 
 2267:                     $outcome .= &Apache::loncommon::start_data_table_row().
 2268:                                 '<td>'.$item.'</td>'.
 2269:                                 &Apache::loncommon::end_data_table_row()."\n";
 2270:                 }
 2271:             }
 2272:             $outcome .= &Apache::loncommon::end_data_table();
 2273:         } else {
 2274:             if (($currentauth =~ /^internal:/) &&
 2275:                 (&Apache::lonuserutils::can_change_internalpass($ccuname,$ccdomain,$crstype,$permission))) {
 2276:                 $outcome = <<"ENDJS";
 2277: <script type="text/javascript">
 2278: // <![CDATA[
 2279: function togglePwd(form) {
 2280:     if (form.newintpwd.length) {
 2281:         if (document.getElementById('LC_ownersetpwd')) {
 2282:             for (var i=0; i<form.newintpwd.length; i++) {
 2283:                 if (form.newintpwd[i].checked) {
 2284:                     if (form.newintpwd[i].value == 1) {
 2285:                         document.getElementById('LC_ownersetpwd').style.display = 'inline-block';
 2286:                     } else {
 2287:                         document.getElementById('LC_ownersetpwd').style.display = 'none';
 2288:                     }
 2289:                 }
 2290:             }
 2291:         }
 2292:     }
 2293: }
 2294: // ]]>
 2295: </script>
 2296: ENDJS
 2297: 
 2298:                 $outcome .= '<h3>'.$lt{'ld'}.'</h3>'.
 2299:                             &Apache::loncommon::start_data_table().
 2300:                             &Apache::loncommon::start_data_table_row().
 2301:                             '<td>'.&mt('Internally authenticated').'<br />'.&mt("Change user's password?").
 2302:                             '<label><input type="radio" name="newintpwd" value="0" checked="checked" onclick="togglePwd(this.form);" />'.
 2303:                             &mt('No').'</label>'.('&nbsp;'x2).
 2304:                             '<label><input type="radio" name="newintpwd" value="1" onclick="togglePwd(this.form);" />'.&mt('Yes').'</label>'.
 2305:                             '<div id="LC_ownersetpwd" style="display:none">'.
 2306:                             '&nbsp;&nbsp;'.&mt('Password').' <input type="password" size="15" name="intarg" value="" />'.
 2307:                             '<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>'.
 2308:                             &Apache::loncommon::end_data_table_row().
 2309:                             &Apache::loncommon::end_data_table();
 2310:             }
 2311:             if (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2312:                 # Current user has rights to view domain preferences for user's domain
 2313:                 my $result;
 2314:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2315:                     my ($krbver,$krbrealm) = ($1,$2);
 2316:                     if ($krbrealm eq '') {
 2317:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2318:                     } else {
 2319:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2320:                                       $krbrealm,$krbver);
 2321:                     }
 2322:                 } elsif ($currentauth =~ /^internal:/) {
 2323:                     $result = &mt('Currently internally authenticated.');
 2324:                 } elsif ($currentauth =~ /^localauth:/) {
 2325:                     $result = &mt('Currently using local (institutional) authentication.');
 2326:                 } elsif ($currentauth =~ /^unix:/) {
 2327:                     $result = &mt('Currently Filesystem Authenticated.');
 2328:                 } elsif ($currentauth =~ /^lti:/) {
 2329:                     $result = &mt('Currently LTI authenticated.');
 2330:                 }
 2331:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2332:                            &Apache::loncommon::start_data_table().
 2333:                            &Apache::loncommon::start_data_table_row().
 2334:                            '<td>'.$result.'</td>'.
 2335:                            &Apache::loncommon::end_data_table_row()."\n".
 2336:                            &Apache::loncommon::end_data_table();
 2337:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2338:                 my %lt=&Apache::lonlocal::texthash(
 2339:                            'ccld'  => "Change Current Login Data",
 2340:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2341:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2342:                 );
 2343:                 $outcome .= <<ENDNOPRIV;
 2344: <h3>$lt{'ccld'}</h3>
 2345: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2346: <input type="hidden" name="login" value="nochange" />
 2347: ENDNOPRIV
 2348:             }
 2349:         }
 2350:     }  ## End of "check for bad authentication type" logic
 2351:     return $outcome;
 2352: }
 2353: 
 2354: sub modify_login_block {
 2355:     my ($dom,$currentauth) = @_;
 2356:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2357:     my ($authnum,%can_assign) =
 2358:         &Apache::loncommon::get_assignable_auth($dom);
 2359:     my ($authformcurrent,@authform_others,$show_override_msg);
 2360:     if ($currentauth=~/^krb(4|5):/) {
 2361:         $authformcurrent=$authformkrb;
 2362:         if ($can_assign{'int'}) {
 2363:             push(@authform_others,$authformint);
 2364:         }
 2365:         if ($can_assign{'loc'}) {
 2366:             push(@authform_others,$authformloc);
 2367:         }
 2368:         if ($can_assign{'lti'}) {
 2369:             push(@authform_others,$authformlti);
 2370:         }
 2371:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2372:             $show_override_msg = 1;
 2373:         }
 2374:     } elsif ($currentauth=~/^internal:/) {
 2375:         $authformcurrent=$authformint;
 2376:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2377:             push(@authform_others,$authformkrb);
 2378:         }
 2379:         if ($can_assign{'loc'}) {
 2380:             push(@authform_others,$authformloc);
 2381:         }
 2382:         if ($can_assign{'lti'}) {
 2383:             push(@authform_others,$authformlti);
 2384:         }
 2385:         if ($can_assign{'int'}) {
 2386:             $show_override_msg = 1;
 2387:         }
 2388:     } elsif ($currentauth=~/^unix:/) {
 2389:         $authformcurrent=$authformfsys;
 2390:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2391:             push(@authform_others,$authformkrb);
 2392:         }
 2393:         if ($can_assign{'int'}) {
 2394:             push(@authform_others,$authformint);
 2395:         }
 2396:         if ($can_assign{'loc'}) {
 2397:             push(@authform_others,$authformloc);
 2398:         }
 2399:         if ($can_assign{'lti'}) {
 2400:             push(@authform_others,$authformlti);
 2401:         }
 2402:         if ($can_assign{'fsys'}) {
 2403:             $show_override_msg = 1;
 2404:         }
 2405:     } elsif ($currentauth=~/^localauth:/) {
 2406:         $authformcurrent=$authformloc;
 2407:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2408:             push(@authform_others,$authformkrb);
 2409:         }
 2410:         if ($can_assign{'int'}) {
 2411:             push(@authform_others,$authformint);
 2412:         }
 2413:         if ($can_assign{'lti'}) {
 2414:             push(@authform_others,$authformlti);
 2415:         }
 2416:         if ($can_assign{'loc'}) {
 2417:             $show_override_msg = 1;
 2418:         }
 2419:     } elsif ($currentauth=~/^lti:/) {
 2420:         $authformcurrent=$authformlti;
 2421:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2422:             push(@authform_others,$authformkrb);
 2423:         }
 2424:         if ($can_assign{'int'}) {
 2425:             push(@authform_others,$authformint);
 2426:         }
 2427:         if ($can_assign{'loc'}) {
 2428:             push(@authform_others,$authformloc);
 2429:         }
 2430:     }
 2431:     if ($show_override_msg) {
 2432:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2433:                            '</td></tr>'."\n".
 2434:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2435:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2436:                            '<td align="right"><span class="LC_cusr_emph">'.
 2437:                             &mt('will override current values').
 2438:                             '</span></td></tr></table>';
 2439:     }
 2440:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2441: }
 2442: 
 2443: sub personal_data_display {
 2444:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2445:         $now,$captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded) = @_;
 2446:     my ($output,%userenv,%canmodify,%canmodify_status);
 2447:     my @userinfo = ('firstname','middlename','lastname','generation',
 2448:                     'permanentemail','id');
 2449:     my $rowcount = 0;
 2450:     my $editable = 0;
 2451:     my %textboxsize = (
 2452:                        firstname      => '15',
 2453:                        middlename     => '15',
 2454:                        lastname       => '15',
 2455:                        generation     => '5',
 2456:                        permanentemail => '25',
 2457:                        id             => '15',
 2458:                       );
 2459: 
 2460:     my %lt=&Apache::lonlocal::texthash(
 2461:                 'pd'             => "Personal Data",
 2462:                 'firstname'      => "First Name",
 2463:                 'middlename'     => "Middle Name",
 2464:                 'lastname'       => "Last Name",
 2465:                 'generation'     => "Generation",
 2466:                 'permanentemail' => "Permanent e-mail address",
 2467:                 'id'             => "Student/Employee ID",
 2468:                 'lg'             => "Login Data",
 2469:                 'inststatus'     => "Affiliation",
 2470:                 'email'          => 'E-mail address',
 2471:                 'valid'          => 'Validation',
 2472:                 'username'       => 'Username',
 2473:     );
 2474: 
 2475:     %canmodify_status =
 2476:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2477:                                                    ['inststatus'],$rolesarray);
 2478:     if (!$newuser) {
 2479:         # Get the users information
 2480:         %userenv = &Apache::lonnet::get('environment',
 2481:                    ['firstname','middlename','lastname','generation',
 2482:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2483:         %canmodify =
 2484:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2485:                                                        \@userinfo,$rolesarray);
 2486:     } elsif ($context eq 'selfcreate') {
 2487:         if ($newuser eq 'email') {
 2488:             if (ref($emailusername) eq 'HASH') {
 2489:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2490:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2491:                     @userinfo = ();
 2492:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2493:                         foreach my $field (@{$infofields}) { 
 2494:                             if ($emailusername->{$usertype}->{$field}) {
 2495:                                 push(@userinfo,$field);
 2496:                                 $canmodify{$field} = 1;
 2497:                                 unless ($textboxsize{$field}) {
 2498:                                     $textboxsize{$field} = 25;
 2499:                                 }
 2500:                                 unless ($lt{$field}) {
 2501:                                     $lt{$field} = $infotitles->{$field};
 2502:                                 }
 2503:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2504:                                     $lt{$field} .= '<b>*</b>';
 2505:                                 }
 2506:                             }
 2507:                         }
 2508:                     }
 2509:                 }
 2510:             }
 2511:         } else {
 2512:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2513:                                                $inst_results,$rolesarray);
 2514:         }
 2515:     }
 2516: 
 2517:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2518:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2519:               &Apache::lonhtmlcommon::start_pick_box();
 2520:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2521:         my $size = 25;
 2522:         if ($condition) {
 2523:             if ($condition =~ /^\@[^\@]+$/) {
 2524:                 $size = 10;
 2525:             } else {
 2526:                 undef($condition);
 2527:             }
 2528:         } 
 2529:         if ($excluded) {
 2530:             unless ($excluded =~ /^\@[^\@]+$/) {
 2531:                 undef($condition);
 2532:             }
 2533:         }
 2534:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2535:                                                      'LC_oddrow_value')."\n".
 2536:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2537:         if ($condition) {
 2538:             $output .= $condition;
 2539:         } elsif ($excluded) {
 2540:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2541:                                                                      $excluded).'</span>';
 2542:         }
 2543:         if ($usernameset eq 'first') {
 2544:             $output .= '<br /><span style="font-size: smaller">';
 2545:             if ($condition) {
 2546:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2547:                                       $condition);
 2548:             } else {
 2549:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2550:             }
 2551:             $output .= '</span>';
 2552:         }
 2553:         $rowcount ++;
 2554:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2555:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2556:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2557:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2558:                                                     'LC_pick_box_title',
 2559:                                                     'LC_oddrow_value')."\n".
 2560:                    $upassone."\n".
 2561:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2562:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2563:                                                      'LC_pick_box_title',
 2564:                                                      'LC_oddrow_value')."\n".
 2565:                    $upasstwo.
 2566:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2567:         if ($usernameset eq 'free') {
 2568:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2569:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2570:                        '<span class="LC_nobreak">'.&mt('Use e-mail address: ').
 2571:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.
 2572:                        &mt('Yes').'</label>'.('&nbsp;'x2).
 2573:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.
 2574:                        &mt('No').'</label></span>'."\n".
 2575:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2576:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2577:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2578:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2579:             $rowcount ++;
 2580:         }
 2581:     }
 2582:     foreach my $item (@userinfo) {
 2583:         my $rowtitle = $lt{$item};
 2584:         my $hiderow = 0;
 2585:         if ($item eq 'generation') {
 2586:             $rowtitle = $genhelp.$rowtitle;
 2587:         }
 2588:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2589:         if ($newuser) {
 2590:             if (ref($inst_results) eq 'HASH') {
 2591:                 if ($inst_results->{$item} ne '') {
 2592:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2593:                 } else {
 2594:                     if ($context eq 'selfcreate') {
 2595:                         if ($canmodify{$item}) {
 2596:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2597:                             $editable ++;
 2598:                         } else {
 2599:                             $hiderow = 1;
 2600:                         }
 2601:                     } else {
 2602:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2603:                     }
 2604:                 }
 2605:             } else {
 2606:                 if ($context eq 'selfcreate') {
 2607:                     if ($canmodify{$item}) {
 2608:                         if ($newuser eq 'email') {
 2609:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2610:                         } else {
 2611:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2612:                         }
 2613:                         $editable ++;
 2614:                     } else {
 2615:                         $hiderow = 1;
 2616:                     }
 2617:                 } else {
 2618:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2619:                 }
 2620:             }
 2621:         } else {
 2622:             if ($canmodify{$item}) {
 2623:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2624:                 if (($item eq 'id') && (!$newuser)) {
 2625:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2626:                 }
 2627:             } else {
 2628:                 $row .= $userenv{$item};
 2629:             }
 2630:         }
 2631:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2632:         if (!$hiderow) {
 2633:             $output .= $row;
 2634:             $rowcount ++;
 2635:         }
 2636:     }
 2637:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2638:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2639:         if (ref($types) eq 'ARRAY') {
 2640:             if (@{$types} > 0) {
 2641:                 my ($hiderow,$shown);
 2642:                 if ($canmodify_status{'inststatus'}) {
 2643:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2644:                 } else {
 2645:                     if ($userenv{'inststatus'} eq '') {
 2646:                         $hiderow = 1;
 2647:                     } else {
 2648:                         my @showitems;
 2649:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2650:                             if (exists($usertypes->{$item})) {
 2651:                                 push(@showitems,$usertypes->{$item});
 2652:                             } else {
 2653:                                 push(@showitems,$item);
 2654:                             }
 2655:                         }
 2656:                         if (@showitems) {
 2657:                             $shown = join(', ',@showitems);
 2658:                         } else {
 2659:                             $hiderow = 1;
 2660:                         }
 2661:                     }
 2662:                 }
 2663:                 if (!$hiderow) {
 2664:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2665:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2666:                     if ($context eq 'selfcreate') {
 2667:                         $rowcount ++;
 2668:                     }
 2669:                     $output .= $row;
 2670:                 }
 2671:             }
 2672:         }
 2673:     }
 2674:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2675:         if ($captchaform) {
 2676:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2677:                                                          'LC_pick_box_title')."\n".
 2678:                        $captchaform."\n".
 2679:                        &Apache::lonhtmlcommon::row_closure(1); 
 2680:             $rowcount ++;
 2681:         }
 2682:         my $submit_text = &mt('Create account');
 2683:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2684:                    '<br /><input type="submit" name="createaccount" value="'.
 2685:                    $submit_text.'" />'.
 2686:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2687:                    &Apache::lonhtmlcommon::row_closure(1);
 2688:     }
 2689:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2690:     if (wantarray) {
 2691:         if ($context eq 'selfcreate') {
 2692:             return($output,$rowcount,$editable);
 2693:         } else {
 2694:             return $output;
 2695:         }
 2696:     } else {
 2697:         return $output;
 2698:     }
 2699: }
 2700: 
 2701: sub pick_inst_statuses {
 2702:     my ($curr,$usertypes,$types) = @_;
 2703:     my ($output,$rem,@currtypes);
 2704:     if ($curr ne '') {
 2705:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2706:     }
 2707:     my $numinrow = 2;
 2708:     if (ref($types) eq 'ARRAY') {
 2709:         $output = '<table>';
 2710:         my $lastcolspan; 
 2711:         for (my $i=0; $i<@{$types}; $i++) {
 2712:             if (defined($usertypes->{$types->[$i]})) {
 2713:                 my $rem = $i%($numinrow);
 2714:                 if ($rem == 0) {
 2715:                     if ($i<@{$types}-1) {
 2716:                         if ($i > 0) { 
 2717:                             $output .= '</tr>';
 2718:                         }
 2719:                         $output .= '<tr>';
 2720:                     }
 2721:                 } elsif ($i==@{$types}-1) {
 2722:                     my $colsleft = $numinrow - $rem;
 2723:                     if ($colsleft > 1) {
 2724:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2725:                     }
 2726:                 }
 2727:                 my $check = ' ';
 2728:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2729:                     $check = ' checked="checked" ';
 2730:                 }
 2731:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2732:                            '<span class="LC_nobreak"><label>'.
 2733:                            '<input type="checkbox" name="inststatus" '.
 2734:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2735:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2736:             }
 2737:         }
 2738:         $output .= '</tr></table>';
 2739:     }
 2740:     return $output;
 2741: }
 2742: 
 2743: sub selfcreate_canmodify {
 2744:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2745:     if (ref($inst_results) eq 'HASH') {
 2746:         my @inststatuses = &get_inststatuses($inst_results);
 2747:         if (@inststatuses == 0) {
 2748:             @inststatuses = ('default');
 2749:         }
 2750:         $rolesarray = \@inststatuses;
 2751:     }
 2752:     my %canmodify =
 2753:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2754:                                                    $rolesarray);
 2755:     return %canmodify;
 2756: }
 2757: 
 2758: sub get_inststatuses {
 2759:     my ($insthashref) = @_;
 2760:     my @inststatuses = ();
 2761:     if (ref($insthashref) eq 'HASH') {
 2762:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2763:             @inststatuses = @{$insthashref->{'inststatus'}};
 2764:         }
 2765:     }
 2766:     return @inststatuses;
 2767: }
 2768: 
 2769: # ================================================================= Phase Three
 2770: sub update_user_data {
 2771:     my ($r,$context,$crstype,$brcrum,$showcredits,$permission) = @_; 
 2772:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2773:                                           $env{'form.ccdomain'});
 2774:     # Error messages
 2775:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2776:     my $end       = '</span><br /><br />';
 2777:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2778:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2779:                     &mt('Return to previous page').'</a>'.
 2780:                     &Apache::loncommon::end_page();
 2781:     my $now = time;
 2782:     my $title;
 2783:     if (exists($env{'form.makeuser'})) {
 2784: 	$title='Set Privileges for New User';
 2785:     } else {
 2786:         $title='Modify User Privileges';
 2787:     }
 2788:     my $newuser = 0;
 2789:     my ($jsback,$elements) = &crumb_utilities();
 2790:     my $jscript = '<script type="text/javascript">'."\n".
 2791:                   '// <![CDATA['."\n".
 2792:                   $jsback."\n".
 2793:                   '// ]]>'."\n".
 2794:                   '</script>'."\n";
 2795:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2796:     push (@{$brcrum},
 2797:              {href => "javascript:backPage(document.userupdate)",
 2798:               text => $breadcrumb_text{'search'},
 2799:               faq  => 282,
 2800:               bug  => 'Instructor Interface',}
 2801:              );
 2802:     if ($env{'form.prevphase'} eq 'userpicked') {
 2803:         push(@{$brcrum},
 2804:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2805:                 text => $breadcrumb_text{'userpicked'},
 2806:                 faq  => 282,
 2807:                 bug  => 'Instructor Interface',});
 2808:     }
 2809:     my $helpitem = 'Course_Change_Privileges';
 2810:     if ($env{'form.action'} eq 'singlestudent') {
 2811:         $helpitem = 'Course_Add_Student';
 2812:     } elsif ($context eq 'author') {
 2813:         $helpitem = 'Author_Change_Privileges';
 2814:     } elsif ($context eq 'domain') {
 2815:         $helpitem = 'Domain_Change_Privileges';
 2816:     }
 2817:     push(@{$brcrum}, 
 2818:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2819:              text => $breadcrumb_text{'modify'},
 2820:              faq  => 282,
 2821:              bug  => 'Instructor Interface',},
 2822:             {href => "/adm/createuser",
 2823:              text => "Result",
 2824:              faq  => 282,
 2825:              bug  => 'Instructor Interface',
 2826:              help => $helpitem});
 2827:     my $args = {bread_crumbs          => $brcrum,
 2828:                 bread_crumbs_component => 'User Management'};
 2829:     if ($env{'form.popup'}) {
 2830:         $args->{'no_nav_bar'} = 1;
 2831:     }
 2832:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2833:     $r->print(&update_result_form($uhome));
 2834:     # Check Inputs
 2835:     if (! $env{'form.ccuname'} ) {
 2836: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2837: 	return;
 2838:     }
 2839:     if (  $env{'form.ccuname'} ne 
 2840: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2841: 	$r->print($error.&mt('Invalid login name.').'  '.
 2842: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2843: 		  $end.$rtnlink);
 2844: 	return;
 2845:     }
 2846:     if (! $env{'form.ccdomain'}       ) {
 2847: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2848: 	return;
 2849:     }
 2850:     if (  $env{'form.ccdomain'} ne
 2851: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2852: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2853: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2854: 		  $end.$rtnlink);
 2855: 	return;
 2856:     }
 2857:     if ($uhome eq 'no_host') {
 2858:         $newuser = 1;
 2859:     }
 2860:     if (! exists($env{'form.makeuser'})) {
 2861:         # Modifying an existing user, so check the validity of the name
 2862:         if ($uhome eq 'no_host') {
 2863:             $r->print(
 2864:                 $error
 2865:                .'<p class="LC_error">'
 2866:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2867:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2868:                .'</p>');
 2869:             return;
 2870:         }
 2871:     }
 2872:     # Determine authentication method and password for the user being modified
 2873:     my $amode='';
 2874:     my $genpwd='';
 2875:     if ($env{'form.login'} eq 'krb') {
 2876: 	$amode='krb';
 2877: 	$amode.=$env{'form.krbver'};
 2878: 	$genpwd=$env{'form.krbarg'};
 2879:     } elsif ($env{'form.login'} eq 'int') {
 2880: 	$amode='internal';
 2881: 	$genpwd=$env{'form.intarg'};
 2882:     } elsif ($env{'form.login'} eq 'fsys') {
 2883: 	$amode='unix';
 2884: 	$genpwd=$env{'form.fsysarg'};
 2885:     } elsif ($env{'form.login'} eq 'loc') {
 2886: 	$amode='localauth';
 2887: 	$genpwd=$env{'form.locarg'};
 2888: 	$genpwd=" " if (!$genpwd);
 2889:     } elsif ($env{'form.login'} eq 'lti') {
 2890:         $amode='lti';
 2891:         $genpwd=" ";
 2892:     } elsif (($env{'form.login'} eq 'nochange') ||
 2893:              ($env{'form.login'} eq ''        )) { 
 2894:         # There is no need to tell the user we did not change what they
 2895:         # did not ask us to change.
 2896:         # If they are creating a new user but have not specified login
 2897:         # information this will be caught below.
 2898:     } else {
 2899:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2900:             return;
 2901:     }
 2902: 
 2903:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2904:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2905:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2906:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2907: 
 2908:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2909:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2910:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2911:     my @requestcourses = ('official','unofficial','community','textbook','placement','lti');
 2912:     my @requestauthor = ('requestauthor');
 2913:     my ($othertitle,$usertypes,$types) = 
 2914:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2915:     my %canmodify_status =
 2916:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2917:                                                    ['inststatus']);
 2918:     if ($env{'form.makeuser'}) {
 2919: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2920:         # Check for the authentication mode and password
 2921:         if (! $amode || ! $genpwd) {
 2922: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2923: 	    return;
 2924: 	}
 2925:         # Determine desired host
 2926:         my $desiredhost = $env{'form.hserver'};
 2927:         if (lc($desiredhost) eq 'default') {
 2928:             $desiredhost = undef;
 2929:         } else {
 2930:             my %home_servers = 
 2931: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2932:             if (! exists($home_servers{$desiredhost})) {
 2933:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2934:                 return;
 2935:             }
 2936:         }
 2937:         # Check ID format
 2938:         my %checkhash;
 2939:         my %checks = ('id' => 1);
 2940:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2941:             'newuser' => $newuser, 
 2942:             'id' => $env{'form.cid'},
 2943:         );
 2944:         if ($env{'form.cid'} ne '') {
 2945:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2946:                                           \%rulematch,\%inst_results,\%curr_rules);
 2947:             if (ref($alerts{'id'}) eq 'HASH') {
 2948:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2949:                     my $domdesc =
 2950:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2951:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2952:                         my $userchkmsg;
 2953:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2954:                             $userchkmsg  = 
 2955:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2956:                                                                     $domdesc,1).
 2957:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2958:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2959:                         }
 2960:                         $r->print($error.&mt('Invalid ID format').$end.
 2961:                                   $userchkmsg.$rtnlink);
 2962:                         return;
 2963:                     }
 2964:                 }
 2965:             }
 2966:         }
 2967:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2968: 	# Call modifyuser
 2969: 	my $result = &Apache::lonnet::modifyuser
 2970: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2971:              $amode,$genpwd,$env{'form.cfirstname'},
 2972:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2973:              $env{'form.cgeneration'},undef,$desiredhost,
 2974:              $env{'form.cpermanentemail'});
 2975: 	$r->print(&mt('Generating user').': '.$result);
 2976:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2977:                                                $env{'form.ccdomain'});
 2978:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2979:         if ($uhome ne 'no_host') {
 2980:             if ($context eq 'domain') {
 2981:                 foreach my $name ('portfolio','author') {
 2982:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2983:                         if ($env{'form.'.$name.'quota'} eq '') {
 2984:                             $newcustom{$name.'quota'} = 0;
 2985:                         } else {
 2986:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2987:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2988:                         }
 2989:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2990:                             $changed{$name.'quota'} = 1;
 2991:                         }
 2992:                     }
 2993:                 }
 2994:                 foreach my $item (@usertools) {
 2995:                     if ($env{'form.custom'.$item} == 1) {
 2996:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2997:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2998:                                                      \%changeHash,'tools');
 2999:                     }
 3000:                 }
 3001:                 foreach my $item (@requestcourses) {
 3002:                     if ($env{'form.custom'.$item} == 1) {
 3003:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 3004:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 3005:                             $newcustom{$item} .= '=';
 3006:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 3007:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 3008:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 3009:                             }
 3010:                         }
 3011:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 3012:                                                       \%changeHash,'requestcourses');
 3013:                     }
 3014:                 }
 3015:                 if ($env{'form.customrequestauthor'} == 1) {
 3016:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 3017:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 3018:                                                     $newcustom{'requestauthor'},
 3019:                                                     \%changeHash,'requestauthor');
 3020:                 }
 3021:             }
 3022:             if ($canmodify_status{'inststatus'}) {
 3023:                 if (exists($env{'form.inststatus'})) {
 3024:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3025:                     if (@inststatuses > 0) {
 3026:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 3027:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 3028:                     }
 3029:                 }
 3030:             }
 3031:             if (keys(%changed)) {
 3032:                 foreach my $item (@userinfo) {
 3033:                     $changeHash{$item}  = $env{'form.c'.$item};
 3034:                 }
 3035:                 my $chgresult =
 3036:                      &Apache::lonnet::put('environment',\%changeHash,
 3037:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3038:             } 
 3039:         }
 3040:         $r->print('<br />'.&mt('Home Server').': '.$uhome.' '.
 3041:                   &Apache::lonnet::hostname($uhome));
 3042:     } elsif (($env{'form.login'} ne 'nochange') &&
 3043:              ($env{'form.login'} ne ''        )) {
 3044: 	# Modify user privileges
 3045:         if (! $amode || ! $genpwd) {
 3046: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3047: 	    return;
 3048: 	}
 3049: 	# Only allow authentication modification if the person has authority
 3050: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3051: 	    $r->print('Modifying authentication: '.
 3052:                       &Apache::lonnet::modifyuserauth(
 3053: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3054:                        $amode,$genpwd));
 3055:             $r->print('<br />'.&mt('Home Server').': '.&Apache::lonnet::homeserver
 3056: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3057: 	} else {
 3058: 	    # Okay, this is a non-fatal error.
 3059: 	    $r->print($error.&mt('You do not have privileges to modify the authentication configuration for this user.').$end);
 3060: 	}
 3061:     } elsif (($env{'form.intarg'} ne '') &&
 3062:              (&Apache::lonnet::queryauthenticate($env{'form.ccuname'},$env{'form.ccdomain'}) =~ /^internal:/) &&
 3063:              (&Apache::lonuserutils::can_change_internalpass($env{'form.ccuname'},$env{'form.ccdomain'},$crstype,$permission))) {
 3064:         $r->print('Modifying authentication: '.
 3065:                   &Apache::lonnet::modifyuserauth(
 3066:                   $env{'form.ccdomain'},$env{'form.ccuname'},
 3067:                   'internal',$env{'form.intarg'}));
 3068:     }
 3069:     $r->rflush(); # Finish display of header before time consuming actions start
 3070:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3071:     ##
 3072:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3073:     if ($context eq 'course') {
 3074:         ($cnum,$cdom) =
 3075:             &Apache::lonuserutils::get_course_identity();
 3076:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3077:         if ($showcredits) {
 3078:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3079:         }
 3080:     }
 3081:     if (! $env{'form.makeuser'} ) {
 3082:         # Check for need to change
 3083:         my %userenv = &Apache::lonnet::get
 3084:             ('environment',['firstname','middlename','lastname','generation',
 3085:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3086:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 3087:              'requestcourses.official','requestcourses.unofficial',
 3088:              'requestcourses.community','requestcourses.textbook',
 3089:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3090:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3091:              'reqcrsotherdom.placement','requestauthor'],
 3092:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3093:         my ($tmp) = keys(%userenv);
 3094:         if ($tmp =~ /^(con_lost|error)/i) { 
 3095:             %userenv = ();
 3096:         }
 3097:         my $no_forceid_alert;
 3098:         # Check to see if user information can be changed
 3099:         my %domconfig =
 3100:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3101:                                      $env{'form.ccdomain'});
 3102:         my @statuses = ('active','future');
 3103:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3104:         my ($auname,$audom);
 3105:         if ($context eq 'author') {
 3106:             $auname = $env{'user.name'};
 3107:             $audom = $env{'user.domain'};     
 3108:         }
 3109:         foreach my $item (keys(%roles)) {
 3110:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3111:             if ($context eq 'course') {
 3112:                 if ($cnum ne '' && $cdom ne '') {
 3113:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3114:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3115:                             push(@userroles,$role);
 3116:                         }
 3117:                     }
 3118:                 }
 3119:             } elsif ($context eq 'author') {
 3120:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3121:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 3122:                         push(@userroles,$role);
 3123:                     }
 3124:                 }
 3125:             }
 3126:         }
 3127:         if ($env{'form.action'} eq 'singlestudent') {
 3128:             if (!grep(/^st$/,@userroles)) {
 3129:                 push(@userroles,'st');
 3130:             }
 3131:         } else {
 3132:             # Check for course or co-author roles being activated or re-enabled
 3133:             if ($context eq 'author' || $context eq 'course') {
 3134:                 foreach my $key (keys(%env)) {
 3135:                     if ($context eq 'author') {
 3136:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3137:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3138:                                 push(@userroles,$1);
 3139:                             }
 3140:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3141:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3142:                                 push(@userroles,$1);
 3143:                             }
 3144:                         }
 3145:                     } elsif ($context eq 'course') {
 3146:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3147:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3148:                                 push(@userroles,$1);
 3149:                             }
 3150:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3151:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3152:                                 push(@userroles,$1);
 3153:                             }
 3154:                         }
 3155:                     }
 3156:                 }
 3157:             }
 3158:         }
 3159:         #Check to see if we can change personal data for the user 
 3160:         my (@mod_disallowed,@longroles);
 3161:         foreach my $role (@userroles) {
 3162:             if ($role eq 'cr') {
 3163:                 push(@longroles,'Custom');
 3164:             } else {
 3165:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3166:             }
 3167:         }
 3168:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3169:         foreach my $item (@userinfo) {
 3170:             # Strip leading and trailing whitespace
 3171:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3172:             if (!$canmodify{$item}) {
 3173:                 if (defined($env{'form.c'.$item})) {
 3174:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3175:                         push(@mod_disallowed,$item);
 3176:                     }
 3177:                 }
 3178:                 $env{'form.c'.$item} = $userenv{$item};
 3179:             }
 3180:         }
 3181:         # Check to see if we can change the Student/Employee ID
 3182:         my $forceid = $env{'form.forceid'};
 3183:         my $recurseid = $env{'form.recurseid'};
 3184:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3185:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3186:                                             $env{'form.ccuname'});
 3187:         if (($uidhash{$env{'form.ccuname'}}) && 
 3188:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3189:             (!$forceid)) {
 3190:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3191:                 $env{'form.cid'} = $userenv{'id'};
 3192:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3193:                                    .'<br />'
 3194:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3195:                                    .'<br />'."\n";
 3196:             }
 3197:         }
 3198:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3199:             my $checkhash;
 3200:             my $checks = { 'id' => 1 };
 3201:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3202:                    { 'newuser' => $newuser,
 3203:                      'id'  => $env{'form.cid'}, 
 3204:                    };
 3205:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3206:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3207:             if (ref($alerts{'id'}) eq 'HASH') {
 3208:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3209:                    $env{'form.cid'} = $userenv{'id'};
 3210:                 }
 3211:             }
 3212:         }
 3213:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3214:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3215:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3216:             %oldsettingstatus,%newsettingstatus);
 3217:         @disporder = ('inststatus');
 3218:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3219:             push(@disporder,'requestcourses','requestauthor');
 3220:         } else {
 3221:             push(@disporder,'reqcrsotherdom');
 3222:         }
 3223:         push(@disporder,('quota','tools'));
 3224:         $oldinststatus = $userenv{'inststatus'};
 3225:         foreach my $name ('portfolio','author') {
 3226:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3227:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3228:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3229:         }
 3230:         my %canshow;
 3231:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3232:             $canshow{'quota'} = 1;
 3233:         }
 3234:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3235:             $canshow{'tools'} = 1;
 3236:         }
 3237:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3238:             $canshow{'requestcourses'} = 1;
 3239:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3240:             $canshow{'reqcrsotherdom'} = 1;
 3241:         }
 3242:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3243:             $canshow{'inststatus'} = 1;
 3244:         }
 3245:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3246:             $canshow{'requestauthor'} = 1;
 3247:         }
 3248:         my (%changeHash,%changed);
 3249:         if ($oldinststatus eq '') {
 3250:             $oldsettings{'inststatus'} = $othertitle; 
 3251:         } else {
 3252:             if (ref($usertypes) eq 'HASH') {
 3253:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3254:             } else {
 3255:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3256:             }
 3257:         }
 3258:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3259:         if ($canmodify_status{'inststatus'}) {
 3260:             $canshow{'inststatus'} = 1;
 3261:             if (exists($env{'form.inststatus'})) {
 3262:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3263:                 if (@inststatuses > 0) {
 3264:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3265:                     $changeHash{'inststatus'} = $newinststatus;
 3266:                     if ($newinststatus ne $oldinststatus) {
 3267:                         $changed{'inststatus'} = $newinststatus;
 3268:                         foreach my $name ('portfolio','author') {
 3269:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3270:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3271:                         }
 3272:                     }
 3273:                     if (ref($usertypes) eq 'HASH') {
 3274:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3275:                     } else {
 3276:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3277:                     }
 3278:                 }
 3279:             } else {
 3280:                 $newinststatus = '';
 3281:                 $changeHash{'inststatus'} = $newinststatus;
 3282:                 $newsettings{'inststatus'} = $othertitle;
 3283:                 if ($newinststatus ne $oldinststatus) {
 3284:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3285:                     foreach my $name ('portfolio','author') {
 3286:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3287:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3288:                     }
 3289:                 }
 3290:             }
 3291:         } elsif ($context ne 'selfcreate') {
 3292:             $canshow{'inststatus'} = 1;
 3293:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3294:         }
 3295:         foreach my $name ('portfolio','author') {
 3296:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3297:         }
 3298:         if ($context eq 'domain') {
 3299:             foreach my $name ('portfolio','author') {
 3300:                 if ($userenv{$name.'quota'} ne '') {
 3301:                     $oldquota{$name} = $userenv{$name.'quota'};
 3302:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3303:                         if ($env{'form.'.$name.'quota'} eq '') {
 3304:                             $newquota{$name} = 0;
 3305:                         } else {
 3306:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3307:                             $newquota{$name} =~ s/[^\d\.]//g;
 3308:                         }
 3309:                         if ($newquota{$name} != $oldquota{$name}) {
 3310:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3311:                                 $changed{$name.'quota'} = 1;
 3312:                             }
 3313:                         }
 3314:                     } else {
 3315:                         if (&quota_admin('',\%changeHash,$name)) {
 3316:                             $changed{$name.'quota'} = 1;
 3317:                             $newquota{$name} = $newdefquota{$name};
 3318:                             $newisdefault{$name} = 1;
 3319:                         }
 3320:                     }
 3321:                 } else {
 3322:                     $oldisdefault{$name} = 1;
 3323:                     $oldquota{$name} = $olddefquota{$name};
 3324:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3325:                         if ($env{'form.'.$name.'quota'} eq '') {
 3326:                             $newquota{$name} = 0;
 3327:                         } else {
 3328:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3329:                             $newquota{$name} =~ s/[^\d\.]//g;
 3330:                         }
 3331:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3332:                             $changed{$name.'quota'} = 1;
 3333:                         }
 3334:                     } else {
 3335:                         $newquota{$name} = $newdefquota{$name};
 3336:                         $newisdefault{$name} = 1;
 3337:                     }
 3338:                 }
 3339:                 if ($oldisdefault{$name}) {
 3340:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3341:                 }  else {
 3342:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3343:                 }
 3344:                 if ($newisdefault{$name}) {
 3345:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3346:                 } else {
 3347:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3348:                 }
 3349:             }
 3350:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3351:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3352:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3353:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3354:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3355:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3356:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3357:             } else {
 3358:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3359:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3360:             }
 3361:         }
 3362:         foreach my $item (@userinfo) {
 3363:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3364:                 $namechanged{$item} = 1;
 3365:             }
 3366:         }
 3367:         foreach my $name ('portfolio','author') {
 3368:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3369:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3370:         }
 3371:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3372:             my ($chgresult,$namechgresult);
 3373:             if (keys(%changed) > 0) {
 3374:                 $chgresult = 
 3375:                     &Apache::lonnet::put('environment',\%changeHash,
 3376:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3377:                 if ($chgresult eq 'ok') {
 3378:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3379:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3380:                         my %newenvhash;
 3381:                         foreach my $key (keys(%changed)) {
 3382:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3383:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3384:                                 ($key eq 'placement') || ($key eq 'lti')) {
 3385:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3386:                                     $changeHash{'requestcourses.'.$key};
 3387:                                 if ($changeHash{'requestcourses.'.$key}) {
 3388:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3389:                                 } else {
 3390:                                     $newenvhash{'environment.canrequest.'.$key} =
 3391:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3392:                                             $key,'reload','requestcourses');
 3393:                                 }
 3394:                             } elsif ($key eq 'requestauthor') {
 3395:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3396:                                 if ($changeHash{$key}) {
 3397:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3398:                                 } else {
 3399:                                     $newenvhash{'environment.canrequest.author'} =
 3400:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3401:                                             $key,'reload','requestauthor');
 3402:                                 }
 3403:                             } elsif ($key ne 'quota') {
 3404:                                 $newenvhash{'environment.tools.'.$key} = 
 3405:                                     $changeHash{'tools.'.$key};
 3406:                                 if ($changeHash{'tools.'.$key} ne '') {
 3407:                                     $newenvhash{'environment.availabletools.'.$key} =
 3408:                                         $changeHash{'tools.'.$key};
 3409:                                 } else {
 3410:                                     $newenvhash{'environment.availabletools.'.$key} =
 3411:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3412:           $key,'reload','tools');
 3413:                                 }
 3414:                             }
 3415:                         }
 3416:                         if (keys(%newenvhash)) {
 3417:                             &Apache::lonnet::appenv(\%newenvhash);
 3418:                         }
 3419:                     }
 3420:                 }
 3421:             }
 3422:             if (keys(%namechanged) > 0) {
 3423:                 foreach my $field (@userinfo) {
 3424:                     $changeHash{$field}  = $env{'form.c'.$field};
 3425:                 }
 3426: # Make the change
 3427:                 $namechgresult =
 3428:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3429:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3430:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3431:                         $changeHash{'lastname'},$changeHash{'generation'},
 3432:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3433:                 %userupdate = (
 3434:                                lastname   => $env{'form.clastname'},
 3435:                                middlename => $env{'form.cmiddlename'},
 3436:                                firstname  => $env{'form.cfirstname'},
 3437:                                generation => $env{'form.cgeneration'},
 3438:                                id         => $env{'form.cid'},
 3439:                              );
 3440:             }
 3441:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3442:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3443:             # Tell the user we changed the name
 3444:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3445:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3446:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3447:                                   \%newsettingstext);
 3448:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3449:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3450:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3451:                     if (($recurseid) &&
 3452:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3453:                         my $idresult = 
 3454:                             &Apache::lonuserutils::propagate_id_change(
 3455:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3456:                                 \%userupdate);
 3457:                         $r->print('<br />'.$idresult.'<br />');
 3458:                     }
 3459:                 }
 3460:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3461:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3462:                     my %newenvhash;
 3463:                     foreach my $key (keys(%changeHash)) {
 3464:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3465:                     }
 3466:                     &Apache::lonnet::appenv(\%newenvhash);
 3467:                 }
 3468:             } else { # error occurred
 3469:                 $r->print(
 3470:                     '<p class="LC_error">'
 3471:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3472:                             '"'.$env{'form.ccuname'}.'"',
 3473:                             '"'.$env{'form.ccdomain'}.'"')
 3474:                    .'</p>');
 3475:             }
 3476:         } else { # End of if ($env ... ) logic
 3477:             # They did not want to change the users name, quota, tool availability,
 3478:             # or ability to request creation of courses, 
 3479:             # but we can still tell them what the name and quota and availabilities are  
 3480:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3481:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3482:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3483:         }
 3484:         if (@mod_disallowed) {
 3485:             my ($rolestr,$contextname);
 3486:             if (@longroles > 0) {
 3487:                 $rolestr = join(', ',@longroles);
 3488:             } else {
 3489:                 $rolestr = &mt('No roles');
 3490:             }
 3491:             if ($context eq 'course') {
 3492:                 $contextname = 'course';
 3493:             } elsif ($context eq 'author') {
 3494:                 $contextname = 'co-author';
 3495:             }
 3496:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3497:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3498:             foreach my $field (@mod_disallowed) {
 3499:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3500:             }
 3501:             $r->print('</ul>');
 3502:             if (@mod_disallowed == 1) {
 3503:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3504:             } else {
 3505:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3506:             }
 3507:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3508:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3509:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3510:                          ,'<a href="'.$helplink.'">','</a>')
 3511:                       .'<br />');
 3512:         }
 3513:         $r->print('<span class="LC_warning">'
 3514:                   .$no_forceid_alert
 3515:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3516:                   .'</span>');
 3517:     }
 3518:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3519:     if ($env{'form.action'} eq 'singlestudent') {
 3520:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3521:                                $crstype,$showcredits,$defaultcredits);
 3522:         my $linktext = ($crstype eq 'Community' ?
 3523:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3524:         $r->print(
 3525:             &Apache::lonhtmlcommon::actionbox([
 3526:                 '<a href="javascript:backPage(document.userupdate)">'
 3527:                .($crstype eq 'Community' ? 
 3528:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3529:                .'</a>']));
 3530:     } else {
 3531:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3532:         if (keys(%namechanged) > 0) {
 3533:             if ($context eq 'course') {
 3534:                 if (@userroles > 0) {
 3535:                     if ((@rolechanges == 0) || 
 3536:                         (!(grep(/^st$/,@rolechanges)))) {
 3537:                         if (grep(/^st$/,@userroles)) {
 3538:                             my $classlistupdated =
 3539:                                 &Apache::lonuserutils::update_classlist($cdom,
 3540:                                               $cnum,$env{'form.ccdomain'},
 3541:                                        $env{'form.ccuname'},\%userupdate);
 3542:                         }
 3543:                     }
 3544:                 }
 3545:             }
 3546:         }
 3547:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3548:                                                      $env{'form.ccdomain'});
 3549:         if ($env{'form.popup'}) {
 3550:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3551:         } else {
 3552:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3553:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3554:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3555:         }
 3556:     }
 3557: }
 3558: 
 3559: sub display_userinfo {
 3560:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3561:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3562:         $newsetting,$newsettingtext) = @_;
 3563:     return unless (ref($order) eq 'ARRAY' &&
 3564:                    ref($canshow) eq 'HASH' && 
 3565:                    ref($requestcourses) eq 'ARRAY' && 
 3566:                    ref($requestauthor) eq 'ARRAY' &&
 3567:                    ref($usertools) eq 'ARRAY' && 
 3568:                    ref($userenv) eq 'HASH' &&
 3569:                    ref($changedhash) eq 'HASH' &&
 3570:                    ref($oldsetting) eq 'HASH' &&
 3571:                    ref($oldsettingtext) eq 'HASH' &&
 3572:                    ref($newsetting) eq 'HASH' &&
 3573:                    ref($newsettingtext) eq 'HASH');
 3574:     my %lt=&Apache::lonlocal::texthash(
 3575:          'ui'             => 'User Information',
 3576:          'uic'            => 'User Information Changed',
 3577:          'firstname'      => 'First Name',
 3578:          'middlename'     => 'Middle Name',
 3579:          'lastname'       => 'Last Name',
 3580:          'generation'     => 'Generation',
 3581:          'id'             => 'Student/Employee ID',
 3582:          'permanentemail' => 'Permanent e-mail address',
 3583:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3584:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3585:          'blog'           => 'Blog Availability',
 3586:          'webdav'         => 'WebDAV Availability',
 3587:          'aboutme'        => 'Personal Information Page Availability',
 3588:          'portfolio'      => 'Portfolio Availability',
 3589:          'official'       => 'Can Request Official Courses',
 3590:          'unofficial'     => 'Can Request Unofficial Courses',
 3591:          'community'      => 'Can Request Communities',
 3592:          'textbook'       => 'Can Request Textbook Courses',
 3593:          'placement'      => 'Can Request Placement Tests',
 3594:          'lti'            => 'Can Request LTI Courses',
 3595:          'requestauthor'  => 'Can Request Author Role',
 3596:          'inststatus'     => "Affiliation",
 3597:          'prvs'           => 'Previous Value:',
 3598:          'chto'           => 'Changed To:'
 3599:     );
 3600:     if ($changed) {
 3601:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3602:                 &Apache::loncommon::start_data_table().
 3603:                 &Apache::loncommon::start_data_table_header_row());
 3604:         $r->print("<th>&nbsp;</th>\n");
 3605:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3606:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3607:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3608:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3609: 
 3610:         foreach my $item (@userinfo) {
 3611:             my $value = $env{'form.c'.$item};
 3612:             #show changes only:
 3613:             unless ($value eq $userenv->{$item}){
 3614:                 $r->print(&Apache::loncommon::start_data_table_row());
 3615:                 $r->print("<td>$lt{$item}</td>\n");
 3616:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3617:                 $r->print("<td>$value </td>\n");
 3618:                 $r->print(&Apache::loncommon::end_data_table_row());
 3619:             }
 3620:         }
 3621:         foreach my $entry (@{$order}) {
 3622:             if ($canshow->{$entry}) {
 3623:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3624:                     my @items;
 3625:                     if ($entry eq 'requestauthor') {
 3626:                         @items = ($entry);
 3627:                     } else {
 3628:                         @items = @{$requestcourses};
 3629:                     }
 3630:                     foreach my $item (@items) {
 3631:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3632:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3633:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3634:                             $r->print("<td>$lt{$item}</td>\n");
 3635:                             $r->print("<td>".$oldsetting->{$item});
 3636:                             if ($oldsettingtext->{$item}) {
 3637:                                 if ($oldsetting->{$item}) {
 3638:                                     $r->print(' -- ');
 3639:                                 }
 3640:                                 $r->print($oldsettingtext->{$item});
 3641:                             }
 3642:                             $r->print("</td>\n");
 3643:                             $r->print("<td>".$newsetting->{$item});
 3644:                             if ($newsettingtext->{$item}) {
 3645:                                 if ($newsetting->{$item}) {
 3646:                                     $r->print(' -- ');
 3647:                                 }
 3648:                                 $r->print($newsettingtext->{$item});
 3649:                             }
 3650:                             $r->print("</td>\n");
 3651:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3652:                         }
 3653:                     }
 3654:                 } elsif ($entry eq 'tools') {
 3655:                     foreach my $item (@{$usertools}) {
 3656:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3657:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3658:                             $r->print("<td>$lt{$item}</td>\n");
 3659:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3660:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3661:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3662:                         }
 3663:                     }
 3664:                 } elsif ($entry eq 'quota') {
 3665:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3666:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3667:                         foreach my $name ('portfolio','author') {
 3668:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3669:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3670:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3671:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3672:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3673:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3674:                             }
 3675:                         }
 3676:                     }
 3677:                 } else {
 3678:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3679:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3680:                         $r->print("<td>$lt{$entry}</td>\n");
 3681:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3682:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3683:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3684:                     }
 3685:                 }
 3686:             }
 3687:         }
 3688:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3689:     } else {
 3690:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3691:                   '<p>'.&mt('No changes made to user information').'</p>');
 3692:     }
 3693:     return;
 3694: }
 3695: 
 3696: sub tool_changes {
 3697:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3698:         $changed,$newaccess,$newaccesstext) = @_;
 3699:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3700:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3701:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3702:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3703:         return;
 3704:     }
 3705:     my %reqdisplay = &requestchange_display();
 3706:     if ($context eq 'reqcrsotherdom') {
 3707:         my @options = ('approval','validate','autolimit');
 3708:         my $optregex = join('|',@options);
 3709:         my $cdom = $env{'request.role.domain'};
 3710:         foreach my $tool (@{$usertools}) {
 3711:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3712:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3713:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3714:             my ($newop,$limit);
 3715:             if ($env{'form.'.$context.'_'.$tool}) {
 3716:                 $newop = $env{'form.'.$context.'_'.$tool};
 3717:                 if ($newop eq 'autolimit') {
 3718:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3719:                     $limit =~ s/\D+//g;
 3720:                     $newop .= '='.$limit;
 3721:                 }
 3722:             }
 3723:             if ($userenv->{$context.'.'.$tool} eq '') {
 3724:                 if ($newop) {
 3725:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3726:                                                   $changeHash,$context);
 3727:                     if ($changed->{$tool}) {
 3728:                         if ($newop =~ /^autolimit/) {
 3729:                             if ($limit) {
 3730:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3731:                             } else {
 3732:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3733:                             }
 3734:                         } else {
 3735:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3736:                         }
 3737:                     } else {
 3738:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3739:                     }
 3740:                 }
 3741:             } else {
 3742:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3743:                 my @new;
 3744:                 my $changedoms;
 3745:                 foreach my $req (@curr) {
 3746:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3747:                         my $oldop = $1;
 3748:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3749:                             my $limit = $1;
 3750:                             if ($limit) {
 3751:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3752:                             } else {
 3753:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3754:                             }
 3755:                         } else {
 3756:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3757:                         }
 3758:                         if ($oldop ne $newop) {
 3759:                             $changedoms = 1;
 3760:                             foreach my $item (@curr) {
 3761:                                 my ($reqdom,$option) = split(':',$item);
 3762:                                 unless ($reqdom eq $cdom) {
 3763:                                     push(@new,$item);
 3764:                                 }
 3765:                             }
 3766:                             if ($newop) {
 3767:                                 push(@new,$cdom.':'.$newop);
 3768:                             }
 3769:                             @new = sort(@new);
 3770:                         }
 3771:                         last;
 3772:                     }
 3773:                 }
 3774:                 if ((!$changedoms) && ($newop)) {
 3775:                     $changedoms = 1;
 3776:                     @new = sort(@curr,$cdom.':'.$newop);
 3777:                 }
 3778:                 if ($changedoms) {
 3779:                     my $newdomstr;
 3780:                     if (@new) {
 3781:                         $newdomstr = join(',',@new);
 3782:                     }
 3783:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3784:                                                   $context);
 3785:                     if ($changed->{$tool}) {
 3786:                         if ($env{'form.'.$context.'_'.$tool}) {
 3787:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3788:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3789:                                 $limit =~ s/\D+//g;
 3790:                                 if ($limit) {
 3791:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3792:                                 } else {
 3793:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3794:                                 }
 3795:                             } else {
 3796:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3797:                             }
 3798:                         } else {
 3799:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3800:                         }
 3801:                     }
 3802:                 }
 3803:             }
 3804:         }
 3805:         return;
 3806:     }
 3807:     foreach my $tool (@{$usertools}) {
 3808:         my ($newval,$limit,$envkey);
 3809:         $envkey = $context.'.'.$tool;
 3810:         if ($context eq 'requestcourses') {
 3811:             $newval = $env{'form.crsreq_'.$tool};
 3812:             if ($newval eq 'autolimit') {
 3813:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3814:                 $limit =~ s/\D+//g;
 3815:                 $newval .= '='.$limit;
 3816:             }
 3817:         } elsif ($context eq 'requestauthor') {
 3818:             $newval = $env{'form.'.$context};
 3819:             $envkey = $context;
 3820:         } else {
 3821:             $newval = $env{'form.'.$context.'_'.$tool};
 3822:         }
 3823:         if ($userenv->{$envkey} ne '') {
 3824:             $oldaccess->{$tool} = &mt('custom');
 3825:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3826:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3827:                     my $currlimit = $1;
 3828:                     if ($currlimit eq '') {
 3829:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3830:                     } else {
 3831:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3832:                     }
 3833:                 } elsif ($userenv->{$envkey}) {
 3834:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3835:                 } else {
 3836:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3837:                 }
 3838:             } else {
 3839:                 if ($userenv->{$envkey}) {
 3840:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3841:                 } else {
 3842:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3843:                 }
 3844:             }
 3845:             $changeHash->{$envkey} = $userenv->{$envkey};
 3846:             if ($env{'form.custom'.$tool} == 1) {
 3847:                 if ($newval ne $userenv->{$envkey}) {
 3848:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3849:                                                     $context);
 3850:                     if ($changed->{$tool}) {
 3851:                         $newaccess->{$tool} = &mt('custom');
 3852:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3853:                             if ($newval =~ /^autolimit/) {
 3854:                                 if ($limit) {
 3855:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3856:                                 } else {
 3857:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3858:                                 }
 3859:                             } elsif ($newval) {
 3860:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3861:                             } else {
 3862:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3863:                             }
 3864:                         } else {
 3865:                             if ($newval) {
 3866:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3867:                             } else {
 3868:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3869:                             }
 3870:                         }
 3871:                     } else {
 3872:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3873:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3874:                             if ($newval =~ /^autolimit/) {
 3875:                                 if ($limit) {
 3876:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3877:                                 } else {
 3878:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3879:                                 }
 3880:                             } elsif ($newval) {
 3881:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3882:                             } else {
 3883:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3884:                             }
 3885:                         } else {
 3886:                             if ($userenv->{$context.'.'.$tool}) {
 3887:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3888:                             } else {
 3889:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3890:                             }
 3891:                         }
 3892:                     }
 3893:                 } else {
 3894:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3895:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3896:                 }
 3897:             } else {
 3898:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3899:                 if ($changed->{$tool}) {
 3900:                     $newaccess->{$tool} = &mt('default');
 3901:                 } else {
 3902:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3903:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3904:                         if ($newval =~ /^autolimit/) {
 3905:                             if ($limit) {
 3906:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3907:                             } else {
 3908:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3909:                             }
 3910:                         } elsif ($newval) {
 3911:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3912:                         } else {
 3913:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3914:                         }
 3915:                     } else {
 3916:                         if ($userenv->{$context.'.'.$tool}) {
 3917:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3918:                         } else {
 3919:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3920:                         }
 3921:                     }
 3922:                 }
 3923:             }
 3924:         } else {
 3925:             $oldaccess->{$tool} = &mt('default');
 3926:             if ($env{'form.custom'.$tool} == 1) {
 3927:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3928:                                                 $context);
 3929:                 if ($changed->{$tool}) {
 3930:                     $newaccess->{$tool} = &mt('custom');
 3931:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3932:                         if ($newval =~ /^autolimit/) {
 3933:                             if ($limit) {
 3934:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3935:                             } else {
 3936:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3937:                             }
 3938:                         } elsif ($newval) {
 3939:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3940:                         } else {
 3941:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3942:                         }
 3943:                     } else {
 3944:                         if ($newval) {
 3945:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3946:                         } else {
 3947:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3948:                         }
 3949:                     }
 3950:                 } else {
 3951:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3952:                 }
 3953:             } else {
 3954:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3955:             }
 3956:         }
 3957:     }
 3958:     return;
 3959: }
 3960: 
 3961: sub update_roles {
 3962:     my ($r,$context,$showcredits) = @_;
 3963:     my $now=time;
 3964:     my @rolechanges;
 3965:     my %disallowed;
 3966:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3967:     foreach my $key (keys(%env)) {
 3968: 	next if (! $env{$key});
 3969:         next if ($key eq 'form.action');
 3970: 	# Revoke roles
 3971: 	if ($key=~/^form\.rev/) {
 3972: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3973: # Revoke standard role
 3974: 		my ($scope,$role) = ($1,$2);
 3975: 		my $result =
 3976: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3977: 						$env{'form.ccuname'},
 3978: 						$scope,$role,'','',$context);
 3979:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3980:                             &mt('Revoking [_1] in [_2]',
 3981:                                 &Apache::lonnet::plaintext($role),
 3982:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3983:                                 $result ne "ok").'<br />');
 3984:                 if ($result ne "ok") {
 3985:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3986:                 }
 3987: 		if ($role eq 'st') {
 3988: 		    my $result = 
 3989:                         &Apache::lonuserutils::classlist_drop($scope,
 3990:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3991: 			    $now);
 3992:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3993: 		}
 3994:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3995:                     push(@rolechanges,$role);
 3996:                 }
 3997: 	    }
 3998: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3999: # Revoke custom role
 4000:                 my $result = &Apache::lonnet::revokecustomrole(
 4001:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 4002:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4003:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 4004:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4005:                             $result ne 'ok').'<br />');
 4006:                 if ($result ne "ok") {
 4007:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4008:                 }
 4009:                 if (!grep(/^cr$/,@rolechanges)) {
 4010:                     push(@rolechanges,'cr');
 4011:                 }
 4012: 	    }
 4013: 	} elsif ($key=~/^form\.del/) {
 4014: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 4015: # Delete standard role
 4016: 		my ($scope,$role) = ($1,$2);
 4017: 		my $result =
 4018: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 4019: 						$env{'form.ccuname'},
 4020: 						$scope,$role,$now,0,1,'',
 4021:                                                 $context);
 4022:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4023:                             &mt('Deleting [_1] in [_2]',
 4024:                                 &Apache::lonnet::plaintext($role),
 4025:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 4026:                             $result ne 'ok').'<br />');
 4027:                 if ($result ne "ok") {
 4028:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4029:                 }
 4030: 
 4031: 		if ($role eq 'st') {
 4032: 		    my $result = 
 4033:                         &Apache::lonuserutils::classlist_drop($scope,
 4034:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 4035: 			    $now);
 4036: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 4037: 		}
 4038:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4039:                     push(@rolechanges,$role);
 4040:                 }
 4041:             }
 4042: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4043:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4044: # Delete custom role
 4045:                 my $result =
 4046:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4047:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4048:                         0,1,$context);
 4049:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4050:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4051:                       $result ne "ok").'<br />');
 4052:                 if ($result ne "ok") {
 4053:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4054:                 }
 4055: 
 4056:                 if (!grep(/^cr$/,@rolechanges)) {
 4057:                     push(@rolechanges,'cr');
 4058:                 }
 4059:             }
 4060: 	} elsif ($key=~/^form\.ren/) {
 4061:             my $udom = $env{'form.ccdomain'};
 4062:             my $uname = $env{'form.ccuname'};
 4063: # Re-enable standard role
 4064: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4065:                 my $url = $1;
 4066:                 my $role = $2;
 4067:                 my $logmsg;
 4068:                 my $output;
 4069:                 if ($role eq 'st') {
 4070:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4071:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4072:                         my $credits;
 4073:                         if ($showcredits) {
 4074:                             my $defaultcredits = 
 4075:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4076:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4077:                         }
 4078:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4079:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4080:                             if ($result eq 'refused' && $logmsg) {
 4081:                                 $output = $logmsg;
 4082:                             } else { 
 4083:                                 $output = &mt('Error: [_1]',$result)."\n";
 4084:                             }
 4085:                         } else {
 4086:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4087:                                         &Apache::lonnet::plaintext($role),
 4088:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4089:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4090:                         }
 4091:                     }
 4092:                 } else {
 4093: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4094:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4095:                                $context);
 4096:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4097:                                         &Apache::lonnet::plaintext($role),
 4098:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4099:                     if ($result ne "ok") {
 4100:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4101:                     }
 4102:                 }
 4103:                 $r->print($output);
 4104:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4105:                     push(@rolechanges,$role);
 4106:                 }
 4107: 	    }
 4108: # Re-enable custom role
 4109: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4110:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4111:                 my $result = &Apache::lonnet::assigncustomrole(
 4112:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4113:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4114:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4115:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4116:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4117:                     $result ne "ok").'<br />');
 4118:                 if ($result ne "ok") {
 4119:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4120:                 }
 4121:                 if (!grep(/^cr$/,@rolechanges)) {
 4122:                     push(@rolechanges,'cr');
 4123:                 }
 4124:             }
 4125: 	} elsif ($key=~/^form\.act/) {
 4126:             my $udom = $env{'form.ccdomain'};
 4127:             my $uname = $env{'form.ccuname'};
 4128: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4129:                 # Activate a custom role
 4130: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4131: 		my $url='/'.$one.'/'.$two;
 4132: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4133: 
 4134:                 my $start = ( $env{'form.start_'.$full} ?
 4135:                               $env{'form.start_'.$full} :
 4136:                               $now );
 4137:                 my $end   = ( $env{'form.end_'.$full} ?
 4138:                               $env{'form.end_'.$full} :
 4139:                               0 );
 4140:                                                                                      
 4141:                 # split multiple sections
 4142:                 my %sections = ();
 4143:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 4144:                 if ($num_sections == 0) {
 4145:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4146:                 } else {
 4147: 		    my %curr_groups =
 4148: 			&Apache::longroup::coursegroups($one,$two);
 4149:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4150:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4151:                             exists($curr_groups{$sec})) {
 4152:                             $disallowed{$sec} = $url;
 4153:                             next;
 4154:                         }
 4155:                         my $securl = $url.'/'.$sec;
 4156: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4157:                     }
 4158:                 }
 4159:                 if (!grep(/^cr$/,@rolechanges)) {
 4160:                     push(@rolechanges,'cr');
 4161:                 }
 4162: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4163: 		# Activate roles for sections with 3 id numbers
 4164: 		# set start, end times, and the url for the class
 4165: 		my ($one,$two,$three)=($1,$2,$3);
 4166: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4167: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4168: 			      $now );
 4169: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4170: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4171: 			      0 );
 4172: 		my $url='/'.$one.'/'.$two;
 4173:                 my $type = 'three';
 4174:                 # split multiple sections
 4175:                 my %sections = ();
 4176:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4177:                 my $credits;
 4178:                 if ($three eq 'st') {
 4179:                     if ($showcredits) { 
 4180:                         my $defaultcredits = 
 4181:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4182:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4183:                         $credits =~ s/[^\d\.]//g;
 4184:                         if ($credits eq $defaultcredits) {
 4185:                             undef($credits);
 4186:                         }
 4187:                     }
 4188:                 }
 4189:                 if ($num_sections == 0) {
 4190:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4191:                 } else {
 4192:                     my %curr_groups = 
 4193: 			&Apache::longroup::coursegroups($one,$two);
 4194:                     my $emptysec = 0;
 4195:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4196:                         $sec =~ s/\W//g;
 4197:                         if ($sec ne '') {
 4198:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4199:                                 exists($curr_groups{$sec})) {
 4200:                                 $disallowed{$sec} = $url;
 4201:                                 next;
 4202:                             }
 4203:                             my $securl = $url.'/'.$sec;
 4204:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4205:                         } else {
 4206:                             $emptysec = 1;
 4207:                         }
 4208:                     }
 4209:                     if ($emptysec) {
 4210:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4211:                     }
 4212:                 }
 4213:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4214:                     push(@rolechanges,$three);
 4215:                 }
 4216: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4217: 		# Activate roles for sections with two id numbers
 4218: 		# set start, end times, and the url for the class
 4219: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4220: 			      $env{'form.start_'.$1.'_'.$2} : 
 4221: 			      $now );
 4222: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4223: 			      $env{'form.end_'.$1.'_'.$2} :
 4224: 			      0 );
 4225:                 my $one = $1;
 4226:                 my $two = $2;
 4227: 		my $url='/'.$one.'/';
 4228:                 # split multiple sections
 4229:                 my %sections = ();
 4230:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4231:                 if ($num_sections == 0) {
 4232:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4233:                 } else {
 4234:                     my $emptysec = 0;
 4235:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4236:                         if ($sec ne '') {
 4237:                             my $securl = $url.'/'.$sec;
 4238:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4239:                         } else {
 4240:                             $emptysec = 1;
 4241:                         }
 4242:                     }
 4243:                     if ($emptysec) {
 4244:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4245:                     }
 4246:                 }
 4247:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4248:                     push(@rolechanges,$two);
 4249:                 }
 4250: 	    } else {
 4251: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4252:             }
 4253:             foreach my $key (sort(keys(%disallowed))) {
 4254:                 $r->print('<p class="LC_warning">');
 4255:                 if (($key eq 'none') || ($key eq 'all')) {  
 4256:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4257:                 } else {
 4258:                     $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>'));
 4259:                 }
 4260:                 $r->print('</p><p>'
 4261:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4262:                              ,'<a href="javascript:history.go(-1)'
 4263:                              ,'</a>')
 4264:                          .'</p><br />'
 4265:                 );
 4266:             }
 4267: 	}
 4268:     } # End of foreach (keys(%env))
 4269: # Flush the course logs so reverse user roles immediately updated
 4270:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4271:     if (@rolechanges == 0) {
 4272:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4273:     }
 4274:     return @rolechanges;
 4275: }
 4276: 
 4277: sub get_user_credits {
 4278:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4279:     if ($cdom eq '' || $cnum eq '') {
 4280:         return unless ($env{'request.course.id'});
 4281:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4282:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4283:     }
 4284:     my $credits;
 4285:     my %currhash =
 4286:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4287:     if (keys(%currhash) > 0) {
 4288:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4289:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4290:         $credits = $items[$crdidx];
 4291:         $credits =~ s/[^\d\.]//g;
 4292:     }
 4293:     if ($credits eq $defaultcredits) {
 4294:         undef($credits);
 4295:     }
 4296:     return $credits;
 4297: }
 4298: 
 4299: sub enroll_single_student {
 4300:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4301:         $showcredits,$defaultcredits) = @_;
 4302:     $r->print('<h3>');
 4303:     if ($crstype eq 'Community') {
 4304:         $r->print(&mt('Enrolling Member'));
 4305:     } else {
 4306:         $r->print(&mt('Enrolling Student'));
 4307:     }
 4308:     $r->print('</h3>');
 4309: 
 4310:     # Remove non alphanumeric values from section
 4311:     $env{'form.sections'}=~s/\W//g;
 4312: 
 4313:     my $credits;
 4314:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4315:         $credits = $env{'form.credits'};
 4316:         $credits =~ s/[^\d\.]//g;
 4317:         if ($credits ne '') {
 4318:             if ($credits eq $defaultcredits) {
 4319:                 undef($credits);
 4320:             }
 4321:         }
 4322:     }
 4323: 
 4324:     # Clean out any old student roles the user has in this class.
 4325:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4326:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4327:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4328:     my $enroll_result =
 4329:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4330:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4331:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4332:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4333:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4334:             $credits);
 4335:     if ($enroll_result =~ /^ok/) {
 4336:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4337:         if ($env{'form.sections'} ne '') {
 4338:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4339:         }
 4340:         my ($showstart,$showend);
 4341:         if ($startdate <= $now) {
 4342:             $showstart = &mt('Access starts immediately');
 4343:         } else {
 4344:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4345:         }
 4346:         if ($enddate == 0) {
 4347:             $showend = &mt('ends: no ending date');
 4348:         } else {
 4349:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4350:         }
 4351:         $r->print('.<br />'.$showstart.'; '.$showend);
 4352:         if ($startdate <= $now && !$newuser) {
 4353:             $r->print('<p class="LC_info">');
 4354:             if ($crstype eq 'Community') {
 4355:                 $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.'));
 4356:             } else {
 4357:                 $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.'));
 4358:            }
 4359:            $r->print('</p>');
 4360:         }
 4361:     } else {
 4362:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4363:     }
 4364:     return;
 4365: }
 4366: 
 4367: sub get_defaultquota_text {
 4368:     my ($settingstatus) = @_;
 4369:     my $defquotatext; 
 4370:     if ($settingstatus eq '') {
 4371:         $defquotatext = &mt('default');
 4372:     } else {
 4373:         my ($usertypes,$order) =
 4374:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4375:         if ($usertypes->{$settingstatus} eq '') {
 4376:             $defquotatext = &mt('default');
 4377:         } else {
 4378:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4379:         }
 4380:     }
 4381:     return $defquotatext;
 4382: }
 4383: 
 4384: sub update_result_form {
 4385:     my ($uhome) = @_;
 4386:     my $outcome = 
 4387:     '<form name="userupdate" method="post" action="">'."\n";
 4388:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4389:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4390:     }
 4391:     if ($env{'form.origname'} ne '') {
 4392:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4393:     }
 4394:     foreach my $item ('sortby','seluname','seludom') {
 4395:         if (exists($env{'form.'.$item})) {
 4396:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4397:         }
 4398:     }
 4399:     if ($uhome eq 'no_host') {
 4400:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4401:     }
 4402:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4403:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4404:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4405:                 '</form>';
 4406:     return $outcome;
 4407: }
 4408: 
 4409: sub quota_admin {
 4410:     my ($setquota,$changeHash,$name) = @_;
 4411:     my $quotachanged;
 4412:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4413:         # Current user has quota modification privileges
 4414:         if (ref($changeHash) eq 'HASH') {
 4415:             $quotachanged = 1;
 4416:             $changeHash->{$name.'quota'} = $setquota;
 4417:         }
 4418:     }
 4419:     return $quotachanged;
 4420: }
 4421: 
 4422: sub tool_admin {
 4423:     my ($tool,$settool,$changeHash,$context) = @_;
 4424:     my $canchange = 0; 
 4425:     if ($context eq 'requestcourses') {
 4426:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4427:             $canchange = 1;
 4428:         }
 4429:     } elsif ($context eq 'reqcrsotherdom') {
 4430:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4431:             $canchange = 1;
 4432:         }
 4433:     } elsif ($context eq 'requestauthor') {
 4434:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4435:             $canchange = 1;
 4436:         }
 4437:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4438:         # Current user has quota modification privileges
 4439:         $canchange = 1;
 4440:     }
 4441:     my $toolchanged;
 4442:     if ($canchange) {
 4443:         if (ref($changeHash) eq 'HASH') {
 4444:             $toolchanged = 1;
 4445:             if ($tool eq 'requestauthor') {
 4446:                 $changeHash->{$context} = $settool;
 4447:             } else {
 4448:                 $changeHash->{$context.'.'.$tool} = $settool;
 4449:             }
 4450:         }
 4451:     }
 4452:     return $toolchanged;
 4453: }
 4454: 
 4455: sub build_roles {
 4456:     my ($sectionstr,$sections,$role) = @_;
 4457:     my $num_sections = 0;
 4458:     if ($sectionstr=~ /,/) {
 4459:         my @secnums = split/,/,$sectionstr;
 4460:         if ($role eq 'st') {
 4461:             $secnums[0] =~ s/\W//g;
 4462:             $$sections{$secnums[0]} = 1;
 4463:             $num_sections = 1;
 4464:         } else {
 4465:             foreach my $sec (@secnums) {
 4466:                 $sec =~ ~s/\W//g;
 4467:                 if (!($sec eq "")) {
 4468:                     if (exists($$sections{$sec})) {
 4469:                         $$sections{$sec} ++;
 4470:                     } else {
 4471:                         $$sections{$sec} = 1;
 4472:                         $num_sections ++;
 4473:                     }
 4474:                 }
 4475:             }
 4476:         }
 4477:     } else {
 4478:         $sectionstr=~s/\W//g;
 4479:         unless ($sectionstr eq '') {
 4480:             $$sections{$sectionstr} = 1;
 4481:             $num_sections ++;
 4482:         }
 4483:     }
 4484: 
 4485:     return $num_sections;
 4486: }
 4487: 
 4488: # ========================================================== Custom Role Editor
 4489: 
 4490: sub custom_role_editor {
 4491:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4492:     my $action = $env{'form.customroleaction'};
 4493:     my ($rolename,$helpitem);
 4494:     if ($action eq 'new') {
 4495:         $rolename=$env{'form.newrolename'};
 4496:     } else {
 4497:         $rolename=$env{'form.rolename'};
 4498:     }
 4499: 
 4500:     my ($crstype,$context);
 4501:     if ($env{'request.course.id'}) {
 4502:         $crstype = &Apache::loncommon::course_type();
 4503:         $context = 'course';
 4504:         $helpitem = 'Course_Editing_Custom_Roles';
 4505:     } else {
 4506:         $context = 'domain';
 4507:         $crstype = 'course';
 4508:         $helpitem = 'Domain_Editing_Custom_Roles';
 4509:     }
 4510: 
 4511:     $rolename=~s/[^A-Za-z0-9]//gs;
 4512:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4513: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 4514:                                    $permission);
 4515:         return;
 4516:     }
 4517: 
 4518:     my $formname = 'form1';
 4519:     my %privs=();
 4520:     my $body_top = '<h2>';
 4521: # ------------------------------------------------------- Does this role exist?
 4522:     my ($rdummy,$roledef)=
 4523: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4524:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4525:         $body_top .= &mt('Existing Role').' "';
 4526: # ------------------------------------------------- Get current role privileges
 4527:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4528:         if ($privs{'system'} =~ /bre\&S/) {
 4529:             if ($context eq 'domain') {
 4530:                 $crstype = 'Course';
 4531:             } elsif ($crstype eq 'Community') {
 4532:                 $privs{'system'} =~ s/bre\&S//;
 4533:             }
 4534:         } elsif ($context eq 'domain') {
 4535:             $crstype = 'Course';
 4536:         }
 4537:     } else {
 4538:         $body_top .= &mt('New Role').' "';
 4539:         $roledef='';
 4540:     }
 4541:     $body_top .= $rolename.'"</h2>';
 4542: 
 4543: # ------------------------------------------------------- What can be assigned?
 4544:     my %full=();
 4545:     my %levels=(
 4546:                  course => {},
 4547:                  domain => {},
 4548:                  system => {},
 4549:                );
 4550:     my %levelscurrent=(
 4551:                         course => {},
 4552:                         domain => {},
 4553:                         system => {},
 4554:                       );
 4555:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4556:     my ($jsback,$elements) = &crumb_utilities();
 4557:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4558:     my $head_script =
 4559:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4560:                                                   \%full,\@templateroles,$jsback);
 4561:     push (@{$brcrum},
 4562:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4563:                text => "Pick custom role",
 4564:                faq  => 282,bug=>'Instructor Interface',},
 4565:               {href => "javascript:backPage(document.$formname,'','')",
 4566:                text => "Edit custom role",
 4567:                faq  => 282,
 4568:                bug  => 'Instructor Interface',
 4569:                help => $helpitem}
 4570:               );
 4571:     my $args = { bread_crumbs          => $brcrum,
 4572:                  bread_crumbs_component => 'User Management'};
 4573:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4574:                                              $head_script,$args).
 4575:               $body_top);
 4576:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4577:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4578:                                                         \@templateroles,$prefix));
 4579: 
 4580:     $r->print(<<ENDCCF);
 4581: <input type="hidden" name="phase" value="set_custom_roles" />
 4582: <input type="hidden" name="rolename" value="$rolename" />
 4583: ENDCCF
 4584:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4585:                                                        \%levelscurrent,$prefix));
 4586:     $r->print(&Apache::loncommon::end_data_table().
 4587:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4588:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4589:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4590:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4591:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4592: }
 4593: 
 4594: # ---------------------------------------------------------- Call to definerole
 4595: sub set_custom_role {
 4596:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4597:     my $rolename=$env{'form.rolename'};
 4598:     $rolename=~s/[^A-Za-z0-9]//gs;
 4599:     if (!$rolename) {
 4600: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4601:         return;
 4602:     }
 4603:     my ($jsback,$elements) = &crumb_utilities();
 4604:     my $jscript = '<script type="text/javascript">'
 4605:                  .'// <![CDATA['."\n"
 4606:                  .$jsback."\n"
 4607:                  .'// ]]>'."\n"
 4608:                  .'</script>'."\n";
 4609:     my $helpitem = 'Course_Editing_Custom_Roles';
 4610:     if ($context eq 'domain') {
 4611:         $helpitem = 'Domain_Editing_Custom_Roles';
 4612:     }
 4613:     push(@{$brcrum},
 4614:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4615:          text => "Pick custom role",
 4616:          faq  => 282,
 4617:          bug  => 'Instructor Interface',},
 4618:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4619:          text => "Edit custom role",
 4620:          faq  => 282,
 4621:          bug  => 'Instructor Interface',},
 4622:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4623:          text => "Result",
 4624:          faq  => 282,
 4625:          bug  => 'Instructor Interface',
 4626:          help => $helpitem,}
 4627:         );
 4628:     my $args = { bread_crumbs           => $brcrum,
 4629:                  bread_crumbs_component => 'User Management'};
 4630:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4631: 
 4632:     my $newrole;
 4633:     my ($rdummy,$roledef)=
 4634: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4635: 
 4636: # ------------------------------------------------------- Does this role exist?
 4637:     $r->print('<h3>');
 4638:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4639: 	$r->print(&mt('Existing Role').' "');
 4640:     } else {
 4641: 	$r->print(&mt('New Role').' "');
 4642: 	$roledef='';
 4643:         $newrole = 1;
 4644:     }
 4645:     $r->print($rolename.'"</h3>');
 4646: # ------------------------------------------------- Assign role and show result
 4647: 
 4648:     my $errmsg;
 4649:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4650:     # Assign role and return result
 4651:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4652:                                              $newprivs{'c'});
 4653:     if ($result ne 'ok') {
 4654:         $errmsg = ': '.$result;
 4655:     }
 4656:     my $message =
 4657:         &Apache::lonhtmlcommon::confirm_success(
 4658:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4659:     if ($env{'request.course.id'}) {
 4660:         my $url='/'.$env{'request.course.id'};
 4661:         $url=~s/\_/\//g;
 4662:         $result =
 4663:             &Apache::lonnet::assigncustomrole(
 4664:                 $env{'user.domain'},$env{'user.name'},
 4665:                 $url,
 4666:                 $env{'user.domain'},$env{'user.name'},
 4667:                 $rolename,undef,undef,undef,$context);
 4668:         if ($result ne 'ok') {
 4669:             $errmsg = ': '.$result;
 4670:         }
 4671:         $message .=
 4672:             '<br />'
 4673:            .&Apache::lonhtmlcommon::confirm_success(
 4674:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4675:     }
 4676:     $r->print(
 4677:         &Apache::loncommon::confirmwrapper($message)
 4678:        .'<br />'
 4679:        .&Apache::lonhtmlcommon::actionbox([
 4680:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4681:            .&mt('Create or edit another custom role')
 4682:            .'</a>'])
 4683:        .'<form name="customresult" method="post" action="">'
 4684:        .&Apache::lonhtmlcommon::echo_form_input([])
 4685:        .'</form>'
 4686:     );
 4687: }
 4688: 
 4689: # ================================================================ Main Handler
 4690: sub handler {
 4691:     my $r = shift;
 4692:     if ($r->header_only) {
 4693:        &Apache::loncommon::content_type($r,'text/html');
 4694:        $r->send_http_header;
 4695:        return OK;
 4696:     }
 4697:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 4698: 
 4699:     if ($env{'request.course.id'}) {
 4700:         $context = 'course';
 4701:         $crstype = &Apache::loncommon::course_type();
 4702:     } elsif ($env{'request.role'} =~ /^au\./) {
 4703:         $context = 'author';
 4704:     } else {
 4705:         $context = 'domain';
 4706:     }
 4707: 
 4708:     my ($permission,$allowed) =
 4709:         &Apache::lonuserutils::get_permission($context,$crstype);
 4710: 
 4711:     if ($allowed) {
 4712:         my @allhelp;
 4713:         if ($context eq 'course') {
 4714:             $cid = $env{'request.course.id'};
 4715:             $cdom = $env{'course.'.$cid.'.domain'};
 4716:             $cnum = $env{'course.'.$cid.'.num'};
 4717: 
 4718:             if ($permission->{'cusr'}) {
 4719:                 push(@allhelp,'Course_Create_Class_List');
 4720:             }
 4721:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4722:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 4723:             }
 4724:             if ($permission->{'custom'}) {
 4725:                 push(@allhelp,'Course_Editing_Custom_Roles');
 4726:             }
 4727:             if ($permission->{'cusr'}) {
 4728:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 4729:             }
 4730:             unless ($permission->{'cusr_section'}) {
 4731:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 4732:                     push(@allhelp,'Course_Automated_Enrollment');
 4733:                 }
 4734:                 if ($permission->{'selfenrolladmin'}) {
 4735:                     push(@allhelp,'Course_Approve_Selfenroll');
 4736:                 }
 4737:             }
 4738:             if ($permission->{'grp_manage'}) {
 4739:                 push(@allhelp,'Course_Manage_Group');
 4740:             }
 4741:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4742:                 push(@allhelp,'Course_User_Logs');
 4743:             }
 4744:         } elsif ($context eq 'author') {
 4745:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 4746:                            'Author_View_Coauthor_List','Author_User_Logs'));
 4747:         } else {
 4748:             if ($permission->{'cusr'}) {
 4749:                 push(@allhelp,'Domain_Change_Privileges');
 4750:                 if ($permission->{'activity'}) {
 4751:                     push(@allhelp,'Domain_User_Access_Logs');
 4752:                 }
 4753:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 4754:                 if ($permission->{'custom'}) {
 4755:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 4756:                 }
 4757:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 4758:             } elsif ($permission->{'view'}) {
 4759:                 push(@allhelp,'Domain_View_Privileges');
 4760:                 if ($permission->{'activity'}) {
 4761:                     push(@allhelp,'Domain_User_Access_Logs');
 4762:                 }
 4763:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 4764:             }
 4765:         }
 4766:         if (@allhelp) {
 4767:             $allhelpitems = join(',',@allhelp);
 4768:         }
 4769:     }
 4770: 
 4771:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4772:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4773:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4774:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4775:     my $args;
 4776:     my $brcrum = [];
 4777:     my $bread_crumbs_component = 'User Management';
 4778:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4779:         $brcrum = [{href=>"/adm/createuser",
 4780:                     text=>"User Management",
 4781:                     help=>$allhelpitems}
 4782:                   ];
 4783:     }
 4784:     if (!$allowed) {
 4785:         if ($context eq 'course') {
 4786:             $r->internal_redirect('/adm/viewclasslist');
 4787:             return OK;
 4788:         }
 4789:         $env{'user.error.msg'}=
 4790:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4791:                                  "or view user status.";
 4792:         return HTTP_NOT_ACCEPTABLE;
 4793:     }
 4794: 
 4795:     &Apache::loncommon::content_type($r,'text/html');
 4796:     $r->send_http_header;
 4797: 
 4798:     my $showcredits;
 4799:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4800:          ($context eq 'domain')) {
 4801:         my %domdefaults = 
 4802:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4803:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4804:             $showcredits = 1;
 4805:         }
 4806:     }
 4807: 
 4808:     # Main switch on form.action and form.state, as appropriate
 4809:     if (! exists($env{'form.action'})) {
 4810:         $args = {bread_crumbs => $brcrum,
 4811:                  bread_crumbs_component => $bread_crumbs_component}; 
 4812:         $r->print(&header(undef,$args));
 4813:         $r->print(&print_main_menu($permission,$context,$crstype));
 4814:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4815:         my $helpitem = 'Course_Create_Class_List';
 4816:         if ($context eq 'author') {
 4817:             $helpitem = 'Author_Create_Coauthor_List';
 4818:         } elsif ($context eq 'domain') {
 4819:             $helpitem = 'Domain_Create_Users';
 4820:         }
 4821:         push(@{$brcrum},
 4822:               { href => '/adm/createuser?action=upload&state=',
 4823:                 text => 'Upload Users List',
 4824:                 help => $helpitem,
 4825:               });
 4826:         $bread_crumbs_component = 'Upload Users List';
 4827:         $args = {bread_crumbs           => $brcrum,
 4828:                  bread_crumbs_component => $bread_crumbs_component};
 4829:         $r->print(&header(undef,$args));
 4830:         $r->print('<form name="studentform" method="post" '.
 4831:                   'enctype="multipart/form-data" '.
 4832:                   ' action="/adm/createuser">'."\n");
 4833:         if (! exists($env{'form.state'})) {
 4834:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4835:         } elsif ($env{'form.state'} eq 'got_file') {
 4836:             my $result = 
 4837:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 4838:                                                                  $permission,
 4839:                                                                  $crstype,$showcredits);
 4840:             if ($result eq 'missingdata') {
 4841:                 delete($env{'form.state'});
 4842:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4843:             }
 4844:         } elsif ($env{'form.state'} eq 'enrolling') {
 4845:             if ($env{'form.datatoken'}) {
 4846:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 4847:                                                                     $permission,
 4848:                                                                     $showcredits);
 4849:                 if ($result eq 'missingdata') {
 4850:                     delete($env{'form.state'});
 4851:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4852:                 } elsif ($result eq 'invalidhome') {
 4853:                     $env{'form.state'} = 'got_file';
 4854:                     delete($env{'form.lcserver'});
 4855:                     my $result =
 4856:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4857:                                                                          $crstype,$showcredits);
 4858:                     if ($result eq 'missingdata') {
 4859:                         delete($env{'form.state'});
 4860:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4861:                     }
 4862:                 }
 4863:             } else {
 4864:                 delete($env{'form.state'});
 4865:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4866:             }
 4867:         } else {
 4868:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4869:         }
 4870:         $r->print('</form>');
 4871:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4872:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4873:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4874:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4875:         my $phase = $env{'form.phase'};
 4876:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4877: 	&Apache::loncreateuser::restore_prev_selections();
 4878: 	my $srch;
 4879: 	foreach my $item (@search) {
 4880: 	    $srch->{$item} = $env{'form.'.$item};
 4881: 	}
 4882:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4883:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4884:             if ($env{'form.phase'} eq 'createnewuser') {
 4885:                 my $response;
 4886:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4887:                     my $response =
 4888:                         '<span class="LC_warning">'
 4889:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4890:                            .' letters numbers - . @')
 4891:                        .'</span>';
 4892:                     $env{'form.phase'} = '';
 4893:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4894:                                                $crstype,$brcrum,$permission);
 4895:                 } else {
 4896:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4897:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4898:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4899:                                                   $srch,$response,$context,
 4900:                                                   $permission,$crstype,$brcrum,
 4901:                                                   $showcredits);
 4902:                 }
 4903:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4904:                 my ($currstate,$response,$forcenewuser,$results) = 
 4905:                     &user_search_result($context,$srch);
 4906:                 if ($env{'form.currstate'} eq 'modify') {
 4907:                     $currstate = $env{'form.currstate'};
 4908:                 }
 4909:                 if ($currstate eq 'select') {
 4910:                     &print_user_selection_page($r,$response,$srch,$results,
 4911:                                                \@search,$context,undef,$crstype,
 4912:                                                $brcrum);
 4913:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4914:                     my ($ccuname,$ccdomain,$uhome);
 4915:                     if (($srch->{'srchby'} eq 'uname') && 
 4916:                         ($srch->{'srchtype'} eq 'exact')) {
 4917:                         $ccuname = $srch->{'srchterm'};
 4918:                         $ccdomain= $srch->{'srchdomain'};
 4919:                     } else {
 4920:                         my @matchedunames = keys(%{$results});
 4921:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4922:                     }
 4923:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4924:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4925:                     if ($env{'form.action'} eq 'accesslogs') {
 4926:                         my $uhome;
 4927:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4928:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4929:                         }
 4930:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4931:                             $env{'form.phase'} = '';
 4932:                             undef($forcenewuser);
 4933:                             #if ($response) {
 4934:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4935:                             #        $response .= '<br /><br />';
 4936:                             #    }
 4937:                             #}
 4938:                             &print_username_entry_form($r,$context,$response,$srch,
 4939:                                                        $forcenewuser,$crstype,$brcrum,
 4940:                                                        $permission);
 4941:                         } else {
 4942:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4943:                         }
 4944:                     } else {
 4945:                         if ($env{'form.forcenewuser'}) {
 4946:                             $response = '';
 4947:                         }
 4948:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4949:                                                       $srch,$response,$context,
 4950:                                                       $permission,$crstype,$brcrum);
 4951:                     }
 4952:                 } elsif ($currstate eq 'query') {
 4953:                     &print_user_query_page($r,'createuser',$brcrum);
 4954:                 } else {
 4955:                     $env{'form.phase'} = '';
 4956:                     &print_username_entry_form($r,$context,$response,$srch,
 4957:                                                $forcenewuser,$crstype,$brcrum,
 4958:                                                $permission);
 4959:                 }
 4960:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4961:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4962:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4963:                 if ($env{'form.action'} eq 'accesslogs') {
 4964:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4965:                 } else {
 4966:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4967:                                                   $context,$permission,$crstype,
 4968:                                                   $brcrum);
 4969:                 }
 4970:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4971:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4972:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4973:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4974:             }
 4975:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4976:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits,$permission);
 4977:         } else {
 4978:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4979:                                        $brcrum,$permission);
 4980:         }
 4981:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4982:         my $prefix;
 4983:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4984:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 4985:         } else {
 4986:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4987:         }
 4988:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4989:              ($permission->{'cusr'}) && 
 4990:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4991:         push(@{$brcrum},
 4992:                  {href => '/adm/createuser?action=processauthorreq',
 4993:                   text => 'Authoring Space requests',
 4994:                   help => 'Domain_Role_Approvals'});
 4995:         $bread_crumbs_component = 'Authoring requests';
 4996:         if ($env{'form.state'} eq 'done') {
 4997:             push(@{$brcrum},
 4998:                      {href => '/adm/createuser?action=authorreqqueue',
 4999:                       text => 'Result',
 5000:                       help => 'Domain_Role_Approvals'});
 5001:             $bread_crumbs_component = 'Authoring request result';
 5002:         }
 5003:         $args = { bread_crumbs           => $brcrum,
 5004:                   bread_crumbs_component => $bread_crumbs_component};
 5005:         my $js = &usernamerequest_javascript();
 5006:         $r->print(&header(&add_script($js),$args));
 5007:         if (!exists($env{'form.state'})) {
 5008:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 5009:                                                                             $env{'request.role.domain'}));
 5010:         } elsif ($env{'form.state'} eq 'done') {
 5011:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 5012:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 5013:                                                                          $env{'request.role.domain'}));
 5014:         }
 5015:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 5016:              ($permission->{'cusr'}) &&
 5017:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 5018:         push(@{$brcrum},
 5019:                  {href => '/adm/createuser?action=processusernamereq',
 5020:                   text => 'LON-CAPA account requests',
 5021:                   help => 'Domain_Username_Approvals'});
 5022:         $bread_crumbs_component = 'Account requests';
 5023:         if ($env{'form.state'} eq 'done') {
 5024:             push(@{$brcrum},
 5025:                      {href => '/adm/createuser?action=usernamereqqueue',
 5026:                       text => 'Result',
 5027:                       help => 'Domain_Username_Approvals'});
 5028:             $bread_crumbs_component = 'LON-CAPA account request result';
 5029:         }
 5030:         $args = { bread_crumbs           => $brcrum,
 5031:                   bread_crumbs_component => $bread_crumbs_component};
 5032:         my $js = &usernamerequest_javascript();
 5033:         $r->print(&header(&add_script($js),$args));
 5034:         if (!exists($env{'form.state'})) {
 5035:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 5036:                                                                             $env{'request.role.domain'}));
 5037:         } elsif ($env{'form.state'} eq 'done') {
 5038:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 5039:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 5040:                                                                          $env{'request.role.domain'}));
 5041:         }
 5042:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 5043:              ($permission->{'cusr'})) {
 5044:         my $dom = $env{'form.domain'};
 5045:         my $uname = $env{'form.username'};
 5046:         my $warning;
 5047:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 5048:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 5049:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 5050:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 5051:                     if ($uhome eq 'no_host') {
 5052:                         my $queue = $env{'form.queue'};
 5053:                         my $reqkey = &escape($uname).'_'.$queue; 
 5054:                         my $namespace = 'usernamequeue';
 5055:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 5056:                         my %queued =
 5057:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 5058:                         unless ($queued{$reqkey}) {
 5059:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 5060:                         }
 5061:                     } else {
 5062:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 5063:                     }
 5064:                 } else {
 5065:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 5066:                 }
 5067:             } else {
 5068:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 5069:             }
 5070:         } else {
 5071:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 5072:         }
 5073:         my $args = { only_body => 1 };
 5074:         $r->print(&header(undef,$args).
 5075:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 5076:         if ($warning ne '') {
 5077:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 5078:         } else {
 5079:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 5080:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 5081:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 5082:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 5083:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 5084:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 5085:                         my %info =
 5086:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 5087:                         if (ref($info{$uname}) eq 'HASH') {
 5088:                             my $usertype = $info{$uname}{'inststatus'};
 5089:                             unless ($usertype) {
 5090:                                 $usertype = 'default';
 5091:                             }
 5092:                             my ($showstatus,$showemail,$pickstart);
 5093:                             my $numextras = 0;
 5094:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5095:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 5096:                                 if (ref($usertypes) eq 'HASH') {
 5097:                                     if ($usertypes->{$usertype}) {
 5098:                                         $showstatus = $usertypes->{$usertype};
 5099:                                     } else {
 5100:                                         $showstatus = $othertitle;
 5101:                                     }
 5102:                                     if ($showstatus) {
 5103:                                         $numextras ++;
 5104:                                     }
 5105:                                 }
 5106:                             }
 5107:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 5108:                                 $showemail = $info{$uname}{'email'};
 5109:                                 $numextras ++;
 5110:                             }
 5111:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 5112:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 5113:                                     $pickstart = 1;
 5114:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5115:                                     my ($num,$count);
 5116:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 5117:                                     $count += $numextras;
 5118:                                     foreach my $field (@{$infofields}) {
 5119:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 5120:                                         next unless ($infotitles->{$field});
 5121:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 5122:                                                   $info{$uname}{$field});
 5123:                                         $num ++;
 5124:                                         unless ($count == $num) {
 5125:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 5126:                                         }
 5127:                                     }
 5128:                                 }
 5129:                             }
 5130:                             if ($numextras) {
 5131:                                 unless ($pickstart) {
 5132:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5133:                                     $pickstart = 1;
 5134:                                 }
 5135:                                 if ($showemail) {
 5136:                                     my $closure = '';
 5137:                                     unless ($showstatus) {
 5138:                                         $closure = 1;
 5139:                                     }
 5140:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 5141:                                               $showemail.
 5142:                                               &Apache::lonhtmlcommon::row_closure($closure));
 5143:                                 }
 5144:                                 if ($showstatus) {
 5145:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 5146:                                               $showstatus.
 5147:                                               &Apache::lonhtmlcommon::row_closure(1));
 5148:                                 }
 5149:                             }
 5150:                             if ($pickstart) { 
 5151:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 5152:                             } else {
 5153:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 5154:                             }
 5155:                         } else {
 5156:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 5157:                         }
 5158:                     }
 5159:                 }
 5160:             }
 5161:         }
 5162:         $r->print(&close_popup_form());
 5163:     } elsif (($env{'form.action'} eq 'listusers') && 
 5164:              ($permission->{'view'} || $permission->{'cusr'})) {
 5165:         my $helpitem = 'Course_View_Class_List';
 5166:         if ($context eq 'author') {
 5167:             $helpitem = 'Author_View_Coauthor_List';
 5168:         } elsif ($context eq 'domain') {
 5169:             $helpitem = 'Domain_View_Users_List';
 5170:         }
 5171:         if ($env{'form.phase'} eq 'bulkchange') {
 5172:             push(@{$brcrum},
 5173:                     {href => '/adm/createuser?action=listusers',
 5174:                      text => "List Users"},
 5175:                     {href => "/adm/createuser",
 5176:                      text => "Result",
 5177:                      help => $helpitem});
 5178:             $bread_crumbs_component = 'Update Users';
 5179:             $args = {bread_crumbs           => $brcrum,
 5180:                      bread_crumbs_component => $bread_crumbs_component};
 5181:             $r->print(&header(undef,$args));
 5182:             my $setting = $env{'form.roletype'};
 5183:             my $choice = $env{'form.bulkaction'};
 5184:             if ($permission->{'cusr'}) {
 5185:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 5186:             } else {
 5187:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 5188:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 5189:             }
 5190:         } else {
 5191:             push(@{$brcrum},
 5192:                     {href => '/adm/createuser?action=listusers',
 5193:                      text => "List Users",
 5194:                      help => $helpitem});
 5195:             $bread_crumbs_component = 'List Users';
 5196:             $args = {bread_crumbs           => $brcrum,
 5197:                      bread_crumbs_component => $bread_crumbs_component};
 5198:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5199:             my $formname = 'studentform';
 5200:             my $hidecall = "hide_searching();";
 5201:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5202:                 ($env{'form.roletype'} eq 'community'))) {
 5203:                 if ($env{'form.roletype'} eq 'course') {
 5204:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5205:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5206:                                                                 $formname);
 5207:                 } elsif ($env{'form.roletype'} eq 'community') {
 5208:                     $cb_jscript = 
 5209:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5210:                     my %elements = (
 5211:                                       coursepick => 'radio',
 5212:                                       coursetotal => 'text',
 5213:                                       courselist => 'text',
 5214:                                    );
 5215:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5216:                 }
 5217:                 $jscript .= &verify_user_display($context)."\n".
 5218:                             &Apache::loncommon::check_uncheck_jscript();
 5219:                 my $js = &add_script($jscript).$cb_jscript;
 5220:                 my $loadcode = 
 5221:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5222:                 if ($loadcode ne '') {
 5223:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5224:                 } else {
 5225:                     $args->{add_entries} = {onload => $hidecall};
 5226:                 }
 5227:                 $r->print(&header($js,$args));
 5228:             } else {
 5229:                 $args->{add_entries} = {onload => $hidecall};
 5230:                 $jscript = &verify_user_display($context).
 5231:                            &Apache::loncommon::check_uncheck_jscript(); 
 5232:                 $r->print(&header(&add_script($jscript),$args));
 5233:             }
 5234:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5235:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5236:                          $showcredits);
 5237:         }
 5238:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5239:         my $brtext;
 5240:         if ($crstype eq 'Community') {
 5241:             $brtext = 'Drop Members';
 5242:         } else {
 5243:             $brtext = 'Drop Students';
 5244:         }
 5245:         push(@{$brcrum},
 5246:                 {href => '/adm/createuser?action=drop',
 5247:                  text => $brtext,
 5248:                  help => 'Course_Drop_Student'});
 5249:         if ($env{'form.state'} eq 'done') {
 5250:             push(@{$brcrum},
 5251:                      {href=>'/adm/createuser?action=drop',
 5252:                       text=>"Result"});
 5253:         }
 5254:         $bread_crumbs_component = $brtext;
 5255:         $args = {bread_crumbs           => $brcrum,
 5256:                  bread_crumbs_component => $bread_crumbs_component}; 
 5257:         $r->print(&header(undef,$args));
 5258:         if (!exists($env{'form.state'})) {
 5259:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5260:         } elsif ($env{'form.state'} eq 'done') {
 5261:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5262:                                                     $env{'form.action'});
 5263:         }
 5264:     } elsif ($env{'form.action'} eq 'dateselect') {
 5265:         if ($permission->{'cusr'}) {
 5266:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5267:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5268:                                                                    $crstype,$showcredits));
 5269:         } else {
 5270:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5271:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5272:         }
 5273:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5274:         if ($permission->{selfenrolladmin}) {
 5275:             my %currsettings = (
 5276:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5277:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5278:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5279:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5280:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5281:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5282:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5283:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5284:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5285:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5286:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5287:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5288:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5289:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5290:             );
 5291:             push(@{$brcrum},
 5292:                     {href => '/adm/createuser?action=selfenroll',
 5293:                      text => "Configure Self-enrollment",
 5294:                      help => 'Course_Self_Enrollment'});
 5295:             if (!exists($env{'form.state'})) {
 5296:                 $args = { bread_crumbs           => $brcrum,
 5297:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5298:                 $r->print(&header(undef,$args));
 5299:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5300:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5301:             } elsif ($env{'form.state'} eq 'done') {
 5302:                 push (@{$brcrum},
 5303:                           {href=>'/adm/createuser?action=selfenroll',
 5304:                            text=>"Result"});
 5305:                 $args = { bread_crumbs           => $brcrum,
 5306:                           bread_crumbs_component => 'Self-enrollment result'};
 5307:                 $r->print(&header(undef,$args));
 5308:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5309:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5310:             }
 5311:         } else {
 5312:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5313:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5314:         }
 5315:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5316:         if ($permission->{selfenrolladmin}) {
 5317:             push(@{$brcrum},
 5318:                      {href => '/adm/createuser?action=selfenrollqueue',
 5319:                       text => 'Enrollment requests',
 5320:                       help => 'Course_Approve_Selfenroll'});
 5321:             $bread_crumbs_component = 'Enrollment requests';
 5322:             if ($env{'form.state'} eq 'done') {
 5323:                 push(@{$brcrum},
 5324:                          {href => '/adm/createuser?action=selfenrollqueue',
 5325:                           text => 'Result',
 5326:                           help => 'Course_Approve_Selfenroll'});
 5327:                 $bread_crumbs_component = 'Enrollment result';
 5328:             }
 5329:             $args = { bread_crumbs           => $brcrum,
 5330:                       bread_crumbs_component => $bread_crumbs_component};
 5331:             $r->print(&header(undef,$args));
 5332:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5333:             if (!exists($env{'form.state'})) {
 5334:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5335:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5336:                                                                                 $cdom,$cnum));
 5337:             } elsif ($env{'form.state'} eq 'done') {
 5338:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5339:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5340:                               $cdom,$cnum,$coursedesc));
 5341:             }
 5342:         } else {
 5343:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5344:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5345:         }
 5346:     } elsif ($env{'form.action'} eq 'changelogs') {
 5347:         if ($permission->{cusr} || $permission->{view}) {
 5348:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5349:         } else {
 5350:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5351:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5352:         }
 5353:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5354:         if (($permission->{'owner'}) || ($permission->{'co-owner'})) {
 5355:             if ($env{'form.state'} eq 'process') {
 5356:                 if ($permission->{'owner'}) {
 5357:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5358:                 } else {
 5359:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5360:                 }
 5361:             } else {
 5362:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5363:             }
 5364:         } else {
 5365:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5366:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5367:         }
 5368:     } else {
 5369:         $bread_crumbs_component = 'User Management';
 5370:         $args = { bread_crumbs           => $brcrum,
 5371:                   bread_crumbs_component => $bread_crumbs_component};
 5372:         $r->print(&header(undef,$args));
 5373:         $r->print(&print_main_menu($permission,$context,$crstype));
 5374:     }
 5375:     $r->print(&Apache::loncommon::end_page());
 5376:     return OK;
 5377: }
 5378: 
 5379: sub header {
 5380:     my ($jscript,$args) = @_;
 5381:     my $start_page;
 5382:     if (ref($args) eq 'HASH') {
 5383:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5384:     } else {
 5385:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5386:     }
 5387:     return $start_page;
 5388: }
 5389: 
 5390: sub add_script {
 5391:     my ($js) = @_;
 5392:     return '<script type="text/javascript">'."\n"
 5393:           .'// <![CDATA['."\n"
 5394:           .$js."\n"
 5395:           .'// ]]>'."\n"
 5396:           .'</script>'."\n";
 5397: }
 5398: 
 5399: sub usernamerequest_javascript {
 5400:     my $js = <<ENDJS;
 5401: 
 5402: function openusernamereqdisplay(dom,uname,queue) {
 5403:     var url = '/adm/createuser?action=displayuserreq';
 5404:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5405:     var title = 'Account_Request_Browser';
 5406:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5407:     options += ',width=700,height=600';
 5408:     var stdeditbrowser = open(url,title,options,'1');
 5409:     stdeditbrowser.focus();
 5410:     return;
 5411: }
 5412:  
 5413: ENDJS
 5414: }
 5415: 
 5416: sub close_popup_form {
 5417:     my $close= &mt('Close Window');
 5418:     return << "END";
 5419: <p><form name="displayreq" action="" method="post">
 5420: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5421: </form></p>
 5422: END
 5423: }
 5424: 
 5425: sub verify_user_display {
 5426:     my ($context) = @_;
 5427:     my %lt = &Apache::lonlocal::texthash (
 5428:         course    => 'course(s): description, section(s), status',
 5429:         community => 'community(s): description, section(s), status',
 5430:         author    => 'author',
 5431:     );
 5432:     my $photos;
 5433:     if (($context eq 'course') && $env{'request.course.id'}) {
 5434:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5435:     }
 5436:     my $output = <<"END";
 5437: 
 5438: function hide_searching() {
 5439:     if (document.getElementById('searching')) {
 5440:         document.getElementById('searching').style.display = 'none';
 5441:     }
 5442:     return;
 5443: }
 5444: 
 5445: function display_update() {
 5446:     document.studentform.action.value = 'listusers';
 5447:     document.studentform.phase.value = 'display';
 5448:     document.studentform.submit();
 5449: }
 5450: 
 5451: function updateCols(caller) {
 5452:     var context = '$context';
 5453:     var photos = '$photos';
 5454:     if (caller == 'Status') {
 5455:         if ((context == 'domain') && 
 5456:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5457:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5458:             document.getElementById('showcolstatus').checked = false;
 5459:             document.getElementById('showcolstatus').disabled = 'disabled';
 5460:             document.getElementById('showcolstart').checked = false;
 5461:             document.getElementById('showcolend').checked = false;
 5462:         } else {
 5463:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5464:                 document.getElementById('showcolstatus').checked = true;
 5465:                 document.getElementById('showcolstatus').disabled = '';
 5466:                 document.getElementById('showcolstart').checked = true;
 5467:                 document.getElementById('showcolend').checked = true;
 5468:             } else {
 5469:                 document.getElementById('showcolstatus').checked = false;
 5470:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5471:                 document.getElementById('showcolstart').checked = false;
 5472:                 document.getElementById('showcolend').checked = false;
 5473:             }
 5474:         }
 5475:     }
 5476:     if (caller == 'output') {
 5477:         if (photos == 1) {
 5478:             if (document.getElementById('showcolphoto')) {
 5479:                 var photoitem = document.getElementById('showcolphoto');
 5480:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5481:                     photoitem.checked = true;
 5482:                     photoitem.disabled = '';
 5483:                 } else {
 5484:                     photoitem.checked = false;
 5485:                     photoitem.disabled = 'disabled';
 5486:                 }
 5487:             }
 5488:         }
 5489:     }
 5490:     if (caller == 'showrole') {
 5491:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5492:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5493:             document.getElementById('showcolrole').checked = true;
 5494:             document.getElementById('showcolrole').disabled = '';
 5495:         } else {
 5496:             document.getElementById('showcolrole').checked = false;
 5497:             document.getElementById('showcolrole').disabled = 'disabled';
 5498:         }
 5499:         if (context == 'domain') {
 5500:             var quotausageshow = 0;
 5501:             if ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5502:                 (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community')) {
 5503:                 document.getElementById('showcolstatus').checked = false;
 5504:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5505:                 document.getElementById('showcolstart').checked = false;
 5506:                 document.getElementById('showcolend').checked = false;
 5507:             } else {
 5508:                 if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5509:                     document.getElementById('showcolstatus').checked = true;
 5510:                     document.getElementById('showcolstatus').disabled = '';
 5511:                     document.getElementById('showcolstart').checked = true;
 5512:                     document.getElementById('showcolend').checked = true;
 5513:                 }
 5514:             }
 5515:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5516:                 document.getElementById('showcolextent').disabled = 'disabled';
 5517:                 document.getElementById('showcolextent').checked = 'false';
 5518:                 document.getElementById('showextent').style.display='none';
 5519:                 document.getElementById('showcoltextextent').innerHTML = '';
 5520:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5521:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5522:                     if (document.getElementById('showcolauthorusage')) {
 5523:                         document.getElementById('showcolauthorusage').disabled = '';
 5524:                     }
 5525:                     if (document.getElementById('showcolauthorquota')) {
 5526:                         document.getElementById('showcolauthorquota').disabled = '';
 5527:                     }
 5528:                     quotausageshow = 1;
 5529:                 }
 5530:             } else {
 5531:                 document.getElementById('showextent').style.display='block';
 5532:                 document.getElementById('showextent').style.textAlign='left';
 5533:                 document.getElementById('showextent').style.textFace='normal';
 5534:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5535:                     document.getElementById('showcolextent').disabled = '';
 5536:                     document.getElementById('showcolextent').checked = 'true';
 5537:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5538:                 } else {
 5539:                     document.getElementById('showcolextent').disabled = '';
 5540:                     document.getElementById('showcolextent').checked = 'true';
 5541:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5542:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5543:                     } else {
 5544:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5545:                     }
 5546:                 }
 5547:             }
 5548:             if (quotausageshow == 0)  {
 5549:                 if (document.getElementById('showcolauthorusage')) {
 5550:                     document.getElementById('showcolauthorusage').checked = false;
 5551:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5552:                 }
 5553:                 if (document.getElementById('showcolauthorquota')) {
 5554:                     document.getElementById('showcolauthorquota').checked = false;
 5555:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5556:                 }
 5557:             }
 5558:         }
 5559:     }
 5560:     return;
 5561: }
 5562: 
 5563: END
 5564:     return $output;
 5565: 
 5566: }
 5567: 
 5568: ###############################################################
 5569: ###############################################################
 5570: #  Menu Phase One
 5571: sub print_main_menu {
 5572:     my ($permission,$context,$crstype) = @_;
 5573:     my $linkcontext = $context;
 5574:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5575:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5576:         $linkcontext = lc($crstype);
 5577:         $stuterm = 'Members';
 5578:     }
 5579:     my %links = (
 5580:                 domain => {
 5581:                             upload     => 'Upload a File of Users',
 5582:                             singleuser => 'Add/Modify a User',
 5583:                             listusers  => 'Manage Users',
 5584:                             },
 5585:                 author => {
 5586:                             upload     => 'Upload a File of Co-authors',
 5587:                             singleuser => 'Add/Modify a Co-author',
 5588:                             listusers  => 'Manage Co-authors',
 5589:                             },
 5590:                 course => {
 5591:                             upload     => 'Upload a File of Course Users',
 5592:                             singleuser => 'Add/Modify a Course User',
 5593:                             listusers  => 'List and Modify Multiple Course Users',
 5594:                             },
 5595:                 community => {
 5596:                             upload     => 'Upload a File of Community Users',
 5597:                             singleuser => 'Add/Modify a Community User',
 5598:                             listusers  => 'List and Modify Multiple Community Users',
 5599:                            },
 5600:                 );
 5601:      my %linktitles = (
 5602:                 domain => {
 5603:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5604:                             listusers  => 'Show and manage users in this domain.',
 5605:                             },
 5606:                 author => {
 5607:                             singleuser => 'Add a user with a co- or assistant author role.',
 5608:                             listusers  => 'Show and manage co- or assistant authors.',
 5609:                             },
 5610:                 course => {
 5611:                             singleuser => 'Add a user with a certain role to this course.',
 5612:                             listusers  => 'Show and manage users in this course.',
 5613:                             },
 5614:                 community => {
 5615:                             singleuser => 'Add a user with a certain role to this community.',
 5616:                             listusers  => 'Show and manage users in this community.',
 5617:                            },
 5618:                 );
 5619:   if ($linkcontext eq 'domain') {
 5620:       unless ($permission->{'cusr'}) {
 5621:           $links{'domain'}{'singleuser'} = 'View a User';
 5622:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5623:       }
 5624:   } elsif ($linkcontext eq 'course') {
 5625:       unless ($permission->{'cusr'}) {
 5626:           $links{'course'}{'singleuser'} = 'View a Course User';
 5627:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5628:           $links{'course'}{'listusers'} = 'List Course Users';
 5629:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5630:       }
 5631:   } elsif ($linkcontext eq 'community') {
 5632:       unless ($permission->{'cusr'}) {
 5633:           $links{'community'}{'singleuser'} = 'View a Community User';
 5634:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5635:           $links{'community'}{'listusers'} = 'List Community Users';
 5636:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5637:       }
 5638:   }
 5639:   my @menu = ( {categorytitle => 'Single Users', 
 5640:          items =>
 5641:          [
 5642:             {
 5643:              linktext => $links{$linkcontext}{'singleuser'},
 5644:              icon => 'edit-redo.png',
 5645:              #help => 'Course_Change_Privileges',
 5646:              url => '/adm/createuser?action=singleuser',
 5647:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5648:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5649:             },
 5650:          ]},
 5651: 
 5652:          {categorytitle => 'Multiple Users',
 5653:          items => 
 5654:          [
 5655:             {
 5656:              linktext => $links{$linkcontext}{'upload'},
 5657:              icon => 'uplusr.png',
 5658:              #help => 'Course_Create_Class_List',
 5659:              url => '/adm/createuser?action=upload',
 5660:              permission => $permission->{'cusr'},
 5661:              linktitle => 'Upload a CSV or a text file containing users.',
 5662:             },
 5663:             {
 5664:              linktext => $links{$linkcontext}{'listusers'},
 5665:              icon => 'mngcu.png',
 5666:              #help => 'Course_View_Class_List',
 5667:              url => '/adm/createuser?action=listusers',
 5668:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5669:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5670:             },
 5671: 
 5672:          ]},
 5673: 
 5674:          {categorytitle => 'Administration',
 5675:          items => [ ]},
 5676:        );
 5677: 
 5678:     if ($context eq 'domain'){
 5679:         push(@{  $menu[0]->{items} }, # Single Users
 5680:             {
 5681:              linktext => 'User Access Log',
 5682:              icon => 'document-properties.png',
 5683:              #help => 'Domain_User_Access_Logs',
 5684:              url => '/adm/createuser?action=accesslogs',
 5685:              permission => $permission->{'activity'},
 5686:              linktitle => 'View user access log.',
 5687:             }
 5688:         );
 5689:         
 5690:         push(@{ $menu[2]->{items} }, #Category: Administration
 5691:             {
 5692:              linktext => 'Custom Roles',
 5693:              icon => 'emblem-photos.png',
 5694:              #help => 'Course_Editing_Custom_Roles',
 5695:              url => '/adm/createuser?action=custom',
 5696:              permission => $permission->{'custom'},
 5697:              linktitle => 'Configure a custom role.',
 5698:             },
 5699:             {
 5700:              linktext => 'Authoring Space Requests',
 5701:              icon => 'selfenrl-queue.png',
 5702:              #help => 'Domain_Role_Approvals',
 5703:              url => '/adm/createuser?action=processauthorreq',
 5704:              permission => $permission->{'cusr'},
 5705:              linktitle => 'Approve or reject author role requests',
 5706:             },
 5707:             {
 5708:              linktext => 'LON-CAPA Account Requests',
 5709:              icon => 'list-add.png',
 5710:              #help => 'Domain_Username_Approvals',
 5711:              url => '/adm/createuser?action=processusernamereq',
 5712:              permission => $permission->{'cusr'},
 5713:              linktitle => 'Approve or reject LON-CAPA account requests',
 5714:             },
 5715:             {
 5716:              linktext => 'Change Log',
 5717:              icon => 'document-properties.png',
 5718:              #help => 'Course_User_Logs',
 5719:              url => '/adm/createuser?action=changelogs',
 5720:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5721:              linktitle => 'View change log.',
 5722:             },
 5723:         );
 5724:         
 5725:     }elsif ($context eq 'course'){
 5726:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5727: 
 5728:         my %linktext = (
 5729:                          'Course'    => {
 5730:                                           single => 'Add/Modify a Student', 
 5731:                                           drop   => 'Drop Students',
 5732:                                           groups => 'Course Groups',
 5733:                                         },
 5734:                          'Community' => {
 5735:                                           single => 'Add/Modify a Member', 
 5736:                                           drop   => 'Drop Members',
 5737:                                           groups => 'Community Groups',
 5738:                                         },
 5739:                        );
 5740:         $linktext{'Placement'} = $linktext{'Course'};
 5741: 
 5742:         my %linktitle = (
 5743:             'Course' => {
 5744:                   single => 'Add a user with the role of student to this course',
 5745:                   drop   => 'Remove a student from this course.',
 5746:                   groups => 'Manage course groups',
 5747:                         },
 5748:             'Community' => {
 5749:                   single => 'Add a user with the role of member to this community',
 5750:                   drop   => 'Remove a member from this community.',
 5751:                   groups => 'Manage community groups',
 5752:                            },
 5753:         );
 5754: 
 5755:         $linktitle{'Placement'} = $linktitle{'Course'};
 5756: 
 5757:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5758:             {   
 5759:              linktext => $linktext{$crstype}{'single'},
 5760:              #help => 'Course_Add_Student',
 5761:              icon => 'list-add.png',
 5762:              url => '/adm/createuser?action=singlestudent',
 5763:              permission => $permission->{'cusr'},
 5764:              linktitle => $linktitle{$crstype}{'single'},
 5765:             },
 5766:         );
 5767:         
 5768:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5769:             {
 5770:              linktext => $linktext{$crstype}{'drop'},
 5771:              icon => 'edit-undo.png',
 5772:              #help => 'Course_Drop_Student',
 5773:              url => '/adm/createuser?action=drop',
 5774:              permission => $permission->{'cusr'},
 5775:              linktitle => $linktitle{$crstype}{'drop'},
 5776:             },
 5777:         );
 5778:         push(@{ $menu[2]->{items} }, #Category: Administration
 5779:             {
 5780:              linktext => 'Helpdesk Access',
 5781:              icon => 'helpdesk-access.png',
 5782:              #help => 'Course_Helpdesk_Access',
 5783:              url => '/adm/createuser?action=helpdesk',
 5784:              permission => ($permission->{'owner'} || $permission->{'co-owner'}),
 5785:              linktitle => 'Helpdesk access options',
 5786:             },
 5787:             {
 5788:              linktext => 'Custom Roles',
 5789:              icon => 'emblem-photos.png',
 5790:              #help => 'Course_Editing_Custom_Roles',
 5791:              url => '/adm/createuser?action=custom',
 5792:              permission => $permission->{'custom'},
 5793:              linktitle => 'Configure a custom role.',
 5794:             },
 5795:             {
 5796:              linktext => $linktext{$crstype}{'groups'},
 5797:              icon => 'grps.png',
 5798:              #help => 'Course_Manage_Group',
 5799:              url => '/adm/coursegroups?refpage=cusr',
 5800:              permission => $permission->{'grp_manage'},
 5801:              linktitle => $linktitle{$crstype}{'groups'},
 5802:             },
 5803:             {
 5804:              linktext => 'Change Log',
 5805:              icon => 'document-properties.png',
 5806:              #help => 'Course_User_Logs',
 5807:              url => '/adm/createuser?action=changelogs',
 5808:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5809:              linktitle => 'View change log.',
 5810:             },
 5811:         );
 5812:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5813:             push(@{ $menu[2]->{items} },
 5814:                     {
 5815:                      linktext => 'Enrollment Requests',
 5816:                      icon => 'selfenrl-queue.png',
 5817:                      #help => 'Course_Approve_Selfenroll',
 5818:                      url => '/adm/createuser?action=selfenrollqueue',
 5819:                      permission => $permission->{'selfenrolladmin'},
 5820:                      linktitle =>'Approve or reject enrollment requests.',
 5821:                     },
 5822:             );
 5823:         }
 5824:         
 5825:         if (!exists($permission->{'cusr_section'})){
 5826:             if ($crstype ne 'Community') {
 5827:                 push(@{ $menu[2]->{items} },
 5828:                     {
 5829:                      linktext => 'Automated Enrollment',
 5830:                      icon => 'roles.png',
 5831:                      #help => 'Course_Automated_Enrollment',
 5832:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5833:                                          && (($permission->{'cusr'}) ||
 5834:                                              ($permission->{'view'}))),
 5835:                      url  => '/adm/populate',
 5836:                      linktitle => 'Automated enrollment manager.',
 5837:                     }
 5838:                 );
 5839:             }
 5840:             push(@{ $menu[2]->{items} }, 
 5841:                 {
 5842:                  linktext => 'User Self-Enrollment',
 5843:                  icon => 'self_enroll.png',
 5844:                  #help => 'Course_Self_Enrollment',
 5845:                  url => '/adm/createuser?action=selfenroll',
 5846:                  permission => $permission->{'selfenrolladmin'},
 5847:                  linktitle => 'Configure user self-enrollment.',
 5848:                 },
 5849:             );
 5850:         }
 5851:     } elsif ($context eq 'author') {
 5852:         push(@{ $menu[2]->{items} }, #Category: Administration
 5853:             {
 5854:              linktext => 'Change Log',
 5855:              icon => 'document-properties.png',
 5856:              #help => 'Course_User_Logs',
 5857:              url => '/adm/createuser?action=changelogs',
 5858:              permission => $permission->{'cusr'},
 5859:              linktitle => 'View change log.',
 5860:             },
 5861:         );
 5862:     }
 5863:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5864: #               { text => 'View Log-in History',
 5865: #                 help => 'Course_User_Logins',
 5866: #                 action => 'logins',
 5867: #                 permission => $permission->{'cusr'},
 5868: #               });
 5869: }
 5870: 
 5871: sub restore_prev_selections {
 5872:     my %saveable_parameters = ('srchby'   => 'scalar',
 5873: 			       'srchin'   => 'scalar',
 5874: 			       'srchtype' => 'scalar',
 5875: 			       );
 5876:     &Apache::loncommon::store_settings('user','user_picker',
 5877: 				       \%saveable_parameters);
 5878:     &Apache::loncommon::restore_settings('user','user_picker',
 5879: 					 \%saveable_parameters);
 5880: }
 5881: 
 5882: sub print_selfenroll_menu {
 5883:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5884:     my $crstype = &Apache::loncommon::course_type();
 5885:     my $formname = 'selfenroll';
 5886:     my $nolink = 1;
 5887:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5888:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5889:     my $setsec_js = 
 5890:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5891:     my %alerts = &Apache::lonlocal::texthash(
 5892:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5893:         butn => 'but no user types have been checked.',
 5894:         wilf => "Please uncheck 'activate' or check at least one type.",
 5895:     );
 5896:     my $disabled;
 5897:     if ($readonly) {
 5898:        $disabled = ' disabled="disabled"';
 5899:     }
 5900:     &js_escape(\%alerts);
 5901:     my $selfenroll_js = <<"ENDSCRIPT";
 5902: function update_types(caller,num) {
 5903:     var delidx = getIndexByName('selfenroll_delete');
 5904:     var actidx = getIndexByName('selfenroll_activate');
 5905:     if (caller == 'selfenroll_all') {
 5906:         var selall;
 5907:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5908:             if (document.$formname.selfenroll_all[i].checked) {
 5909:                 selall = document.$formname.selfenroll_all[i].value;
 5910:             }
 5911:         }
 5912:         if (selall == 1) {
 5913:             if (delidx != -1) {
 5914:                 if (document.$formname.selfenroll_delete.length) {
 5915:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5916:                         document.$formname.selfenroll_delete[j].checked = true;
 5917:                     }
 5918:                 } else {
 5919:                     document.$formname.elements[delidx].checked = true;
 5920:                 }
 5921:             }
 5922:             if (actidx != -1) {
 5923:                 if (document.$formname.selfenroll_activate.length) {
 5924:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5925:                         document.$formname.selfenroll_activate[j].checked = false;
 5926:                     }
 5927:                 } else {
 5928:                     document.$formname.elements[actidx].checked = false;
 5929:                 }
 5930:             }
 5931:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5932:         }
 5933:     }
 5934:     if (caller == 'selfenroll_activate') {
 5935:         if (document.$formname.selfenroll_activate.length) {
 5936:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5937:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5938:                     if (document.$formname.selfenroll_activate[j].checked) {
 5939:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5940:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5941:                                 document.$formname.selfenroll_all[i].checked = false;
 5942:                             }
 5943:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5944:                                 document.$formname.selfenroll_all[i].checked = true;
 5945:                             }
 5946:                         }
 5947:                     }
 5948:                 }
 5949:             }
 5950:         } else {
 5951:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5952:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5953:                     document.$formname.selfenroll_all[i].checked = false;
 5954:                 }
 5955:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5956:                     document.$formname.selfenroll_all[i].checked = true;
 5957:                 }
 5958:             }
 5959:         }
 5960:     }
 5961:     if (caller == 'selfenroll_delete') {
 5962:         if (document.$formname.selfenroll_delete.length) {
 5963:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5964:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5965:                     if (document.$formname.selfenroll_delete[j].checked) {
 5966:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5967:                         if (delindex != -1) { 
 5968:                             if (document.$formname.elements[delindex].length) {
 5969:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5970:                                     document.$formname.elements[delindex][k].checked = false;
 5971:                                 }
 5972:                             } else {
 5973:                                 document.$formname.elements[delindex].checked = false;
 5974:                             }
 5975:                         }
 5976:                     }
 5977:                 }
 5978:             }
 5979:         } else {
 5980:             if (document.$formname.selfenroll_delete.checked) {
 5981:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5982:                 if (delindex != -1) {
 5983:                     if (document.$formname.elements[delindex].length) {
 5984:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5985:                             document.$formname.elements[delindex][k].checked = false;
 5986:                         }
 5987:                     } else {
 5988:                         document.$formname.elements[delindex].checked = false;
 5989:                     }
 5990:                 }
 5991:             }
 5992:         }
 5993:     }
 5994:     return;
 5995: }
 5996: 
 5997: function validate_types(form) {
 5998:     var needaction = new Array();
 5999:     var countfail = 0;
 6000:     var actidx = getIndexByName('selfenroll_activate');
 6001:     if (actidx != -1) {
 6002:         if (document.$formname.selfenroll_activate.length) {
 6003:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 6004:                 var num = document.$formname.selfenroll_activate[j].value;
 6005:                 if (document.$formname.selfenroll_activate[j].checked) {
 6006:                     countfail = check_types(num,countfail,needaction)
 6007:                 }
 6008:             }
 6009:         } else {
 6010:             if (document.$formname.selfenroll_activate.checked) {
 6011:                 var num = document.$formname.selfenroll_activate.value;
 6012:                 countfail = check_types(num,countfail,needaction)
 6013:             }
 6014:         }
 6015:     }
 6016:     if (countfail > 0) {
 6017:         var msg = "$alerts{'acto'}\\n";
 6018:         var loopend = needaction.length -1;
 6019:         if (loopend > 0) {
 6020:             for (var m=0; m<loopend; m++) {
 6021:                 msg += needaction[m]+", ";
 6022:             }
 6023:         }
 6024:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 6025:         alert(msg);
 6026:         return; 
 6027:     }
 6028:     setSections(form);
 6029: }
 6030: 
 6031: function check_types(num,countfail,needaction) {
 6032:     var boxname = 'selfenroll_types_'+num;
 6033:     var typeidx = getIndexByName(boxname);
 6034:     var count = 0;
 6035:     if (typeidx != -1) {
 6036:         if (document.$formname.elements[boxname].length) {
 6037:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 6038:                 if (document.$formname.elements[boxname][k].checked) {
 6039:                     count ++;
 6040:                 }
 6041:             }
 6042:         } else {
 6043:             if (document.$formname.elements[typeidx].checked) {
 6044:                 count ++;
 6045:             }
 6046:         }
 6047:         if (count == 0) {
 6048:             var domidx = getIndexByName('selfenroll_dom_'+num);
 6049:             if (domidx != -1) {
 6050:                 var domname = document.$formname.elements[domidx].value;
 6051:                 needaction[countfail] = domname;
 6052:                 countfail ++;
 6053:             }
 6054:         }
 6055:     }
 6056:     return countfail;
 6057: }
 6058: 
 6059: function toggleNotify() {
 6060:     var selfenrollApproval = 0;
 6061:     if (document.$formname.selfenroll_approval.length) {
 6062:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 6063:             if (document.$formname.selfenroll_approval[i].checked) {
 6064:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 6065:                 break;        
 6066:             }
 6067:         }
 6068:     }
 6069:     if (document.getElementById('notified')) {
 6070:         if (selfenrollApproval == 0) {
 6071:             document.getElementById('notified').style.display='none';
 6072:         } else {
 6073:             document.getElementById('notified').style.display='block';
 6074:         }
 6075:     }
 6076:     return;
 6077: }
 6078: 
 6079: function getIndexByName(item) {
 6080:     for (var i=0;i<document.$formname.elements.length;i++) {
 6081:         if (document.$formname.elements[i].name == item) {
 6082:             return i;
 6083:         }
 6084:     }
 6085:     return -1;
 6086: }
 6087: ENDSCRIPT
 6088: 
 6089:     my $output = '<script type="text/javascript">'."\n".
 6090:                  '// <![CDATA['."\n".
 6091:                  $setsec_js."\n".$selfenroll_js."\n".
 6092:                  '// ]]>'."\n".
 6093:                  '</script>'."\n".
 6094:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 6095:  
 6096:     my $visactions = &cat_visibility();
 6097:     my ($cathash,%cattype);
 6098:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 6099:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 6100:         $cathash = $domconfig{'coursecategories'}{'cats'};
 6101:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 6102:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 6103:         if ($cattype{'auth'} eq '') {
 6104:             $cattype{'auth'} = 'std';
 6105:         }
 6106:         if ($cattype{'unauth'} eq '') {
 6107:             $cattype{'unauth'} = 'std';
 6108:         }
 6109:     } else {
 6110:         $cathash = {};
 6111:         $cattype{'auth'} = 'std';
 6112:         $cattype{'unauth'} = 'std';
 6113:     }
 6114:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 6115:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6116:                   '<br />'.
 6117:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6118:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 6119:                   '</ul>');
 6120:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 6121:         if ($currsettings->{'uniquecode'}) {
 6122:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 6123:         } else {
 6124:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6125:                   '<br />'.
 6126:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6127:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 6128:                   '</ul><br />');
 6129:         }
 6130:     } else {
 6131:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 6132:         if (ref($visactions) eq 'HASH') {
 6133:             if ($visible) {
 6134:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 6135:            } else {
 6136:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 6137:                           .$visactions->{'yous'}.
 6138:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 6139:                 if (ref($vismsgs) eq 'ARRAY') {
 6140:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 6141:                     foreach my $item (@{$vismsgs}) {
 6142:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 6143:                     }
 6144:                     $output .= '</ul>';
 6145:                 }
 6146:                 $output .= '</p>';
 6147:             }
 6148:         }
 6149:     }
 6150:     my $actionhref = '/adm/createuser';
 6151:     if ($context eq 'domain') {
 6152:         $actionhref = '/adm/modifycourse';
 6153:     }
 6154: 
 6155:     my %noedit;
 6156:     unless ($context eq 'domain') {
 6157:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 6158:     }
 6159:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 6160:                &Apache::lonhtmlcommon::start_pick_box();
 6161:     if (ref($row) eq 'ARRAY') {
 6162:         foreach my $item (@{$row}) {
 6163:             my $title = $item; 
 6164:             if (ref($lt) eq 'HASH') {
 6165:                 $title = $lt->{$item};
 6166:             }
 6167:             $output .= &Apache::lonhtmlcommon::row_title($title);
 6168:             if ($item eq 'types') {
 6169:                 my $curr_types;
 6170:                 if (ref($currsettings) eq 'HASH') {
 6171:                     $curr_types = $currsettings->{'selfenroll_types'};
 6172:                 }
 6173:                 if ($noedit{$item}) {
 6174:                     if ($curr_types eq '*') {
 6175:                         $output .= &mt('Any user in any domain');   
 6176:                     } else {
 6177:                         my @entries = split(/;/,$curr_types);
 6178:                         if (@entries > 0) {
 6179:                             $output .= '<ul>'; 
 6180:                             foreach my $entry (@entries) {
 6181:                                 my ($currdom,$typestr) = split(/:/,$entry);
 6182:                                 next if ($typestr eq '');
 6183:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 6184:                                 my @currinsttypes = split(',',$typestr);
 6185:                                 my ($othertitle,$usertypes,$types) = 
 6186:                                     &Apache::loncommon::sorted_inst_types($currdom);
 6187:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6188:                                     $usertypes->{'any'} = &mt('any user'); 
 6189:                                     if (keys(%{$usertypes}) > 0) {
 6190:                                         $usertypes->{'other'} = &mt('other users');
 6191:                                     }
 6192:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 6193:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 6194:                                  }
 6195:                             }
 6196:                             $output .= '</ul>';
 6197:                         } else {
 6198:                             $output .= &mt('None');
 6199:                         }
 6200:                     }
 6201:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6202:                     next;
 6203:                 }
 6204:                 my $showdomdesc = 1;
 6205:                 my $includeempty = 1;
 6206:                 my $num = 0;
 6207:                 $output .= &Apache::loncommon::start_data_table().
 6208:                            &Apache::loncommon::start_data_table_row()
 6209:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6210:                            .&mt('Any user in any domain:')
 6211:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6212:                 if ($curr_types eq '*') {
 6213:                     $output .= ' checked="checked" '; 
 6214:                 }
 6215:                 $output .= 'onchange="javascript:update_types('.
 6216:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6217:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6218:                 if ($curr_types ne '*') {
 6219:                     $output .= ' checked="checked" ';
 6220:                 }
 6221:                 $output .= ' onchange="javascript:update_types('.
 6222:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6223:                            &Apache::loncommon::end_data_table_row().
 6224:                            &Apache::loncommon::end_data_table().
 6225:                            &mt('Or').'<br />'.
 6226:                            &Apache::loncommon::start_data_table();
 6227:                 my %currdoms;
 6228:                 if ($curr_types eq '') {
 6229:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6230:                 } elsif ($curr_types ne '*') {
 6231:                     my @entries = split(/;/,$curr_types);
 6232:                     if (@entries > 0) {
 6233:                         foreach my $entry (@entries) {
 6234:                             my ($currdom,$typestr) = split(/:/,$entry);
 6235:                             $currdoms{$currdom} = 1;
 6236:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6237:                             my @currinsttypes = split(',',$typestr);
 6238:                             $output .= &Apache::loncommon::start_data_table_row()
 6239:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6240:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6241:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6242:                                        .'" value="'.$currdom.'" /></span><br />'
 6243:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6244:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6245:                                        .&mt('Delete').'</label></span></td>';
 6246:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6247:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6248:                                        .&Apache::loncommon::end_data_table_row();
 6249:                             $num ++;
 6250:                         }
 6251:                     }
 6252:                 }
 6253:                 my $add_domtitle = &mt('Users in additional domain:');
 6254:                 if ($curr_types eq '*') { 
 6255:                     $add_domtitle = &mt('Users in specific domain:');
 6256:                 } elsif ($curr_types eq '') {
 6257:                     $add_domtitle = &mt('Users in other domain:');
 6258:                 }
 6259:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 6260:                 $output .= &Apache::loncommon::start_data_table_row()
 6261:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6262:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6263:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 6264:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6265:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6266:                            .&Apache::loncommon::end_data_table();
 6267:             } elsif ($item eq 'registered') {
 6268:                 my ($regon,$regoff);
 6269:                 my $registered;
 6270:                 if (ref($currsettings) eq 'HASH') {
 6271:                     $registered = $currsettings->{'selfenroll_registered'};
 6272:                 }
 6273:                 if ($noedit{$item}) {
 6274:                     if ($registered) {
 6275:                         $output .= &mt('Must be registered in course');
 6276:                     } else {
 6277:                         $output .= &mt('No requirement');
 6278:                     }
 6279:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6280:                     next;
 6281:                 }
 6282:                 if ($registered) {
 6283:                     $regon = ' checked="checked" ';
 6284:                     $regoff = '';
 6285:                 } else {
 6286:                     $regon = '';
 6287:                     $regoff = ' checked="checked" ';
 6288:                 }
 6289:                 $output .= '<label>'.
 6290:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6291:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6292:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6293:                            &mt('No').'</label>';
 6294:             } elsif ($item eq 'enroll_dates') {
 6295:                 my ($starttime,$endtime);
 6296:                 if (ref($currsettings) eq 'HASH') {
 6297:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6298:                     $endtime = $currsettings->{'selfenroll_end_date'};
 6299:                     if ($starttime eq '') {
 6300:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6301:                     }
 6302:                     if ($endtime eq '') {
 6303:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6304:                     }
 6305:                 }
 6306:                 if ($noedit{$item}) {
 6307:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6308:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6309:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6310:                     next;
 6311:                 }
 6312:                 my $startform =
 6313:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6314:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6315:                 my $endform =
 6316:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6317:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6318:                 $output .= &selfenroll_date_forms($startform,$endform);
 6319:             } elsif ($item eq 'access_dates') {
 6320:                 my ($starttime,$endtime);
 6321:                 if (ref($currsettings) eq 'HASH') {
 6322:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6323:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6324:                     if ($starttime eq '') {
 6325:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6326:                     }
 6327:                     if ($endtime eq '') {
 6328:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6329:                     }
 6330:                 }
 6331:                 if ($noedit{$item}) {
 6332:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6333:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6334:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6335:                     next;
 6336:                 }
 6337:                 my $startform =
 6338:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6339:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6340:                 my $endform =
 6341:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6342:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6343:                 $output .= &selfenroll_date_forms($startform,$endform);
 6344:             } elsif ($item eq 'section') {
 6345:                 my $currsec;
 6346:                 if (ref($currsettings) eq 'HASH') {
 6347:                     $currsec = $currsettings->{'selfenroll_section'};
 6348:                 }
 6349:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6350:                 my $newsecval;
 6351:                 if ($currsec ne 'none' && $currsec ne '') {
 6352:                     if (!defined($sections_count{$currsec})) {
 6353:                         $newsecval = $currsec;
 6354:                     }
 6355:                 }
 6356:                 if ($noedit{$item}) {
 6357:                     if ($currsec ne '') {
 6358:                         $output .= $currsec;
 6359:                     } else {
 6360:                         $output .= &mt('No specific section');
 6361:                     }
 6362:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6363:                     next;
 6364:                 }
 6365:                 my $sections_select = 
 6366:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6367:                 $output .= '<table class="LC_createuser">'."\n".
 6368:                            '<tr class="LC_section_row">'."\n".
 6369:                            '<td align="center">'.&mt('Existing sections')."\n".
 6370:                            '<br />'.$sections_select.'</td><td align="center">'.
 6371:                            &mt('New section').'<br />'."\n".
 6372:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6373:                            '<input type="hidden" name="sections" value="" />'."\n".
 6374:                            '</td></tr></table>'."\n";
 6375:             } elsif ($item eq 'approval') {
 6376:                 my ($currnotified,$currapproval,%appchecked);
 6377:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6378:                 if (ref($currsettings) eq 'HASH') {
 6379:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6380:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6381:                 }
 6382:                 if ($currapproval !~ /^[012]$/) {
 6383:                     $currapproval = 0;
 6384:                 }
 6385:                 if ($noedit{$item}) {
 6386:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6387:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6388:                     next;
 6389:                 }
 6390:                 $appchecked{$currapproval} = ' checked="checked"';
 6391:                 for my $i (0..2) {
 6392:                     $output .= '<label>'.
 6393:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6394:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6395:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6396:                 }
 6397:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6398:                 my (@ccs,%notified);
 6399:                 my $ccrole = 'cc';
 6400:                 if ($crstype eq 'Community') {
 6401:                     $ccrole = 'co';
 6402:                 }
 6403:                 if ($advhash{$ccrole}) {
 6404:                     @ccs = split(/,/,$advhash{$ccrole});
 6405:                 }
 6406:                 if ($currnotified) {
 6407:                     foreach my $current (split(/,/,$currnotified)) {
 6408:                         $notified{$current} = 1;
 6409:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6410:                             push(@ccs,$current);
 6411:                         }
 6412:                     }
 6413:                 }
 6414:                 if (@ccs) {
 6415:                     my $style;
 6416:                     unless ($currapproval) {
 6417:                         $style = ' style="display: none;"'; 
 6418:                     }
 6419:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6420:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6421:                                &Apache::loncommon::start_data_table().
 6422:                                &Apache::loncommon::start_data_table_row();
 6423:                     my $count = 0;
 6424:                     my $numcols = 4;
 6425:                     foreach my $cc (sort(@ccs)) {
 6426:                         my $notifyon;
 6427:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6428:                         if ($notified{$cc}) {
 6429:                             $notifyon = ' checked="checked" ';
 6430:                         }
 6431:                         if ($count && !$count%$numcols) {
 6432:                             $output .= &Apache::loncommon::end_data_table_row().
 6433:                                        &Apache::loncommon::start_data_table_row()
 6434:                         }
 6435:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6436:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6437:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6438:                                    '</label></span></td>';
 6439:                         $count ++;
 6440:                     }
 6441:                     my $rem = $count%$numcols;
 6442:                     if ($rem) {
 6443:                         my $emptycols = $numcols - $rem;
 6444:                         for (my $i=0; $i<$emptycols; $i++) { 
 6445:                             $output .= '<td>&nbsp;</td>';
 6446:                         }
 6447:                     }
 6448:                     $output .= &Apache::loncommon::end_data_table_row().
 6449:                                &Apache::loncommon::end_data_table().
 6450:                                '</div>';
 6451:                 }
 6452:             } elsif ($item eq 'limit') {
 6453:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6454:                 if (ref($currsettings) eq 'HASH') {
 6455:                     $currlim = $currsettings->{'selfenroll_limit'};
 6456:                     $currcap = $currsettings->{'selfenroll_cap'};
 6457:                 }
 6458:                 if ($noedit{$item}) {
 6459:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6460:                         if ($currlim eq 'allstudents') {
 6461:                             $output .= &mt('Limit by total students');
 6462:                         } elsif ($currlim eq 'selfenrolled') {
 6463:                             $output .= &mt('Limit by total self-enrolled students');
 6464:                         }
 6465:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6466:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6467:                     } else {
 6468:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6469:                     }
 6470:                     next;
 6471:                 }
 6472:                 if ($currlim eq 'allstudents') {
 6473:                     $crslimit = ' checked="checked" ';
 6474:                     $selflimit = ' ';
 6475:                     $nolimit = ' ';
 6476:                 } elsif ($currlim eq 'selfenrolled') {
 6477:                     $crslimit = ' ';
 6478:                     $selflimit = ' checked="checked" ';
 6479:                     $nolimit = ' '; 
 6480:                 } else {
 6481:                     $crslimit = ' ';
 6482:                     $selflimit = ' ';
 6483:                     $nolimit = ' checked="checked" ';
 6484:                 }
 6485:                 $output .= '<table><tr><td><label>'.
 6486:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6487:                            &mt('No limit').'</label></td><td><label>'.
 6488:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6489:                            &mt('Limit by total students').'</label></td><td><label>'.
 6490:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6491:                            &mt('Limit by total self-enrolled students').
 6492:                            '</td></tr><tr>'.
 6493:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6494:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6495:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6496:             }
 6497:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6498:         }
 6499:     }
 6500:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6501:     unless ($readonly) {
 6502:         $output .= '<input type="button" name="selfenrollconf" value="'
 6503:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6504:     }
 6505:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6506:               .'<input type="hidden" name="state" value="done" />'."\n"
 6507:               .$additional.'</form>';
 6508:     $r->print($output);
 6509:     return;
 6510: }
 6511: 
 6512: sub get_noedit_fields {
 6513:     my ($cdom,$cnum,$crstype,$row) = @_;
 6514:     my %noedit;
 6515:     if (ref($row) eq 'ARRAY') {
 6516:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6517:                                                            'internal.selfenrollmgrdc',
 6518:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6519:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6520:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6521:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6522:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6523:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6524:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6525: 
 6526:         foreach my $item (@{$row}) {
 6527:             next if ($specific_managebycc{$item});
 6528:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6529:                 $noedit{$item} = 1;
 6530:             }
 6531:         }
 6532:     }
 6533:     return %noedit;
 6534: } 
 6535: 
 6536: sub visible_in_stdcat {
 6537:     my ($cdom,$cnum,$domconf) = @_;
 6538:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6539:     unless (ref($domconf) eq 'HASH') {
 6540:         return ($visible,$cansetvis,\@vismsgs);
 6541:     }
 6542:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6543:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6544:             $settable{'togglecats'} = 1;
 6545:         }
 6546:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6547:             $settable{'categorize'} = 1;
 6548:         }
 6549:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6550:     }
 6551:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6552:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6553:     } elsif ($settable{'togglecats'}) {
 6554:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6555:     } elsif ($settable{'categorize'}) {
 6556:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6557:     } else {
 6558:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6559:     }
 6560:      
 6561:     my %currsettings =
 6562:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6563:                              $cdom,$cnum);
 6564:     $visible = 0;
 6565:     if ($currsettings{'internal.coursecode'} ne '') {
 6566:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6567:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6568:             if (ref($cathash) eq 'HASH') {
 6569:                 if ($cathash->{'instcode::0'} eq '') {
 6570:                     push(@vismsgs,'dc_addinst'); 
 6571:                 } else {
 6572:                     $visible = 1;
 6573:                 }
 6574:             } else {
 6575:                 $visible = 1;
 6576:             }
 6577:         } else {
 6578:             $visible = 1;
 6579:         }
 6580:     } else {
 6581:         if (ref($cathash) eq 'HASH') {
 6582:             if ($cathash->{'instcode::0'} ne '') {
 6583:                 push(@vismsgs,'dc_instcode');
 6584:             }
 6585:         } else {
 6586:             push(@vismsgs,'dc_instcode');
 6587:         }
 6588:     }
 6589:     if ($currsettings{'categories'} ne '') {
 6590:         my $cathash;
 6591:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6592:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6593:             if (ref($cathash) eq 'HASH') {
 6594:                 if (keys(%{$cathash}) == 0) {
 6595:                     push(@vismsgs,'dc_catalog');
 6596:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6597:                     push(@vismsgs,'dc_categories');
 6598:                 } else {
 6599:                     my @currcategories = split('&',$currsettings{'categories'});
 6600:                     my $matched = 0;
 6601:                     foreach my $cat (@currcategories) {
 6602:                         if ($cathash->{$cat} ne '') {
 6603:                             $visible = 1;
 6604:                             $matched = 1;
 6605:                             last;
 6606:                         }
 6607:                     }
 6608:                     if (!$matched) {
 6609:                         if ($settable{'categorize'}) { 
 6610:                             push(@vismsgs,'chgcat');
 6611:                         } else {
 6612:                             push(@vismsgs,'dc_chgcat');
 6613:                         }
 6614:                     }
 6615:                 }
 6616:             }
 6617:         }
 6618:     } else {
 6619:         if (ref($cathash) eq 'HASH') {
 6620:             if ((keys(%{$cathash}) > 1) || 
 6621:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6622:                 if ($settable{'categorize'}) {
 6623:                     push(@vismsgs,'addcat');
 6624:                 } else {
 6625:                     push(@vismsgs,'dc_addcat');
 6626:                 }
 6627:             }
 6628:         }
 6629:     }
 6630:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6631:         $visible = 0;
 6632:         if ($settable{'togglecats'}) {
 6633:             unshift(@vismsgs,'unhide');
 6634:         } else {
 6635:             unshift(@vismsgs,'dc_unhide')
 6636:         }
 6637:     }
 6638:     return ($visible,$cansetvis,\@vismsgs);
 6639: }
 6640: 
 6641: sub cat_visibility {
 6642:     my %visactions = &Apache::lonlocal::texthash(
 6643:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6644:                    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.',
 6645:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6646:                    none => 'Display of a course catalog is disabled for this domain.',
 6647:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6648:                    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.',
 6649:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6650:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6651:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6652:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6653:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6654:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6655:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6656:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6657:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6658:                    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',
 6659:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6660:     );
 6661:     $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>"');
 6662:     $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>"');
 6663:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6664:     return \%visactions;
 6665: }
 6666: 
 6667: sub new_selfenroll_dom_row {
 6668:     my ($newdom,$num) = @_;
 6669:     my $domdesc = &Apache::lonnet::domain($newdom);
 6670:     my $output;
 6671:     if ($domdesc ne '') {
 6672:         $output .= &Apache::loncommon::start_data_table_row()
 6673:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6674:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6675:                    .'" value="'.$newdom.'" /></span><br />'
 6676:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6677:                    .'name="selfenroll_activate" value="'.$num.'" '
 6678:                    .'onchange="javascript:update_types('
 6679:                    ."'selfenroll_activate','$num'".');" />'
 6680:                    .&mt('Activate').'</label></span></td>';
 6681:         my @currinsttypes;
 6682:         $output .= '<td>'.&mt('User types:').'<br />'
 6683:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6684:                    .&Apache::loncommon::end_data_table_row();
 6685:     }
 6686:     return $output;
 6687: }
 6688: 
 6689: sub selfenroll_inst_types {
 6690:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6691:     my $output;
 6692:     my $numinrow = 4;
 6693:     my $count = 0;
 6694:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6695:     my $othervalue = 'any';
 6696:     my $disabled;
 6697:     if ($readonly) {
 6698:         $disabled = ' disabled="disabled"';
 6699:     }
 6700:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6701:         if (keys(%{$usertypes}) > 0) {
 6702:             $othervalue = 'other';
 6703:         }
 6704:         $output .= '<table><tr>';
 6705:         foreach my $type (@{$types}) {
 6706:             if (($count > 0) && ($count%$numinrow == 0)) {
 6707:                 $output .= '</tr><tr>';
 6708:             }
 6709:             if (defined($usertypes->{$type})) {
 6710:                 my $esc_type = &escape($type);
 6711:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6712:                            $esc_type.'" ';
 6713:                 if (ref($currinsttypes) eq 'ARRAY') {
 6714:                     if (@{$currinsttypes} > 0) {
 6715:                         if (grep(/^any$/,@{$currinsttypes})) {
 6716:                             $output .= 'checked="checked"';
 6717:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6718:                             $output .= 'checked="checked"';
 6719:                         }
 6720:                     } else {
 6721:                         $output .= 'checked="checked"';
 6722:                     }
 6723:                 }
 6724:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6725:             }
 6726:             $count ++;
 6727:         }
 6728:         if (($count > 0) && ($count%$numinrow == 0)) {
 6729:             $output .= '</tr><tr>';
 6730:         }
 6731:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6732:         if (ref($currinsttypes) eq 'ARRAY') {
 6733:             if (@{$currinsttypes} > 0) {
 6734:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6735:                     $output .= ' checked="checked"';
 6736:                 } elsif ($othervalue eq 'other') {
 6737:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6738:                         $output .= ' checked="checked"';
 6739:                     }
 6740:                 }
 6741:             } else {
 6742:                 $output .= ' checked="checked"';
 6743:             }
 6744:         } else {
 6745:             $output .= ' checked="checked"';
 6746:         }
 6747:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6748:     }
 6749:     return $output;
 6750: }
 6751: 
 6752: sub selfenroll_date_forms {
 6753:     my ($startform,$endform) = @_;
 6754:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6755:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6756:                                                     'LC_oddrow_value')."\n".
 6757:                   $startform."\n".
 6758:                   &Apache::lonhtmlcommon::row_closure(1).
 6759:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6760:                                                    'LC_oddrow_value')."\n".
 6761:                   $endform."\n".
 6762:                   &Apache::lonhtmlcommon::row_closure(1).
 6763:                   &Apache::lonhtmlcommon::end_pick_box();
 6764:     return $output;
 6765: }
 6766: 
 6767: sub print_userchangelogs_display {
 6768:     my ($r,$context,$permission,$brcrum) = @_;
 6769:     my $formname = 'rolelog';
 6770:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6771:     if ($context eq 'domain') {
 6772:         $domain = $env{'request.role.domain'};
 6773:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6774:     } else {
 6775:         if ($context eq 'course') { 
 6776:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6777:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6778:             $crstype = &Apache::loncommon::course_type();
 6779:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6780:             my %saveable_parameters = ('show' => 'scalar',);
 6781:             &Apache::loncommon::store_course_settings('roles_log',
 6782:                                                       \%saveable_parameters);
 6783:             &Apache::loncommon::restore_course_settings('roles_log',
 6784:                                                         \%saveable_parameters);
 6785:         } elsif ($context eq 'author') {
 6786:             $domain = $env{'user.domain'}; 
 6787:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6788:                 $username = $env{'user.name'};
 6789:             } else {
 6790:                 undef($domain);
 6791:             }
 6792:         }
 6793:         if ($domain ne '' && $username ne '') { 
 6794:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6795:         }
 6796:     }
 6797:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6798: 
 6799:     my $helpitem;
 6800:     if ($context eq 'course') {
 6801:         $helpitem = 'Course_User_Logs';
 6802:     } elsif ($context eq 'domain') {
 6803:         $helpitem = 'Domain_Role_Logs';
 6804:     } elsif ($context eq 'author') {
 6805:         $helpitem = 'Author_User_Logs';
 6806:     }
 6807:     push (@{$brcrum},
 6808:              {href => '/adm/createuser?action=changelogs',
 6809:               text => 'User Management Logs',
 6810:               help => $helpitem});
 6811:     my $bread_crumbs_component = 'User Changes';
 6812:     my $args = { bread_crumbs           => $brcrum,
 6813:                  bread_crumbs_component => $bread_crumbs_component};
 6814: 
 6815:     # Create navigation javascript
 6816:     my $jsnav = &userlogdisplay_js($formname);
 6817: 
 6818:     my $jscript = (<<ENDSCRIPT);
 6819: <script type="text/javascript">
 6820: // <![CDATA[
 6821: $jsnav
 6822: // ]]>
 6823: </script>
 6824: ENDSCRIPT
 6825: 
 6826:     # print page header
 6827:     $r->print(&header($jscript,$args));
 6828: 
 6829:     # set defaults
 6830:     my $now = time();
 6831:     my $defstart = $now - (7*24*3600); #7 days ago 
 6832:     my %defaults = (
 6833:                      page               => '1',
 6834:                      show               => '10',
 6835:                      role               => 'any',
 6836:                      chgcontext         => 'any',
 6837:                      rolelog_start_date => $defstart,
 6838:                      rolelog_end_date   => $now,
 6839:                    );
 6840:     my $more_records = 0;
 6841: 
 6842:     # set current
 6843:     my %curr;
 6844:     foreach my $item ('show','page','role','chgcontext') {
 6845:         $curr{$item} = $env{'form.'.$item};
 6846:     }
 6847:     my ($startdate,$enddate) = 
 6848:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6849:     $curr{'rolelog_start_date'} = $startdate;
 6850:     $curr{'rolelog_end_date'} = $enddate;
 6851:     foreach my $key (keys(%defaults)) {
 6852:         if ($curr{$key} eq '') {
 6853:             $curr{$key} = $defaults{$key};
 6854:         }
 6855:     }
 6856:     my (%whodunit,%changed,$version);
 6857:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6858:     my ($minshown,$maxshown);
 6859:     $minshown = 1;
 6860:     my $count = 0;
 6861:     if ($curr{'show'} =~ /\D/) {
 6862:         $curr{'page'} = 1;
 6863:     } else {
 6864:         $maxshown = $curr{'page'} * $curr{'show'};
 6865:         if ($curr{'page'} > 1) {
 6866:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6867:         }
 6868:     }
 6869: 
 6870:     # Form Header
 6871:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6872:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6873:                                    $version,$crstype));
 6874: 
 6875:     my $showntableheader = 0;
 6876: 
 6877:     # Table Header
 6878:     my $tableheader = 
 6879:         &Apache::loncommon::start_data_table_header_row()
 6880:        .'<th>&nbsp;</th>'
 6881:        .'<th>'.&mt('When').'</th>'
 6882:        .'<th>'.&mt('Who made the change').'</th>'
 6883:        .'<th>'.&mt('Changed User').'</th>'
 6884:        .'<th>'.&mt('Role').'</th>';
 6885: 
 6886:     if ($context eq 'course') {
 6887:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6888:     }
 6889:     $tableheader .=
 6890:         '<th>'.&mt('Context').'</th>'
 6891:        .'<th>'.&mt('Start').'</th>'
 6892:        .'<th>'.&mt('End').'</th>'
 6893:        .&Apache::loncommon::end_data_table_header_row();
 6894: 
 6895:     # Display user change log data
 6896:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6897:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6898:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6899:         if ($curr{'show'} !~ /\D/) {
 6900:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6901:                 $more_records = 1;
 6902:                 last;
 6903:             }
 6904:         }
 6905:         if ($curr{'role'} ne 'any') {
 6906:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6907:         }
 6908:         if ($curr{'chgcontext'} ne 'any') {
 6909:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6910:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6911:             } else {
 6912:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6913:             }
 6914:         }
 6915:         if (($context eq 'course') && ($viewablesec ne '')) {
 6916:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6917:         }
 6918:         $count ++;
 6919:         next if ($count < $minshown);
 6920:         unless ($showntableheader) {
 6921:             $r->print(&Apache::loncommon::start_data_table()
 6922:                      .$tableheader);
 6923:             $r->rflush();
 6924:             $showntableheader = 1;
 6925:         }
 6926:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6927:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6928:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6929:         }
 6930:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6931:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6932:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6933:         }
 6934:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6935:         if ($sec eq '') {
 6936:             $sec = &mt('None');
 6937:         }
 6938:         my ($rolestart,$roleend);
 6939:         if ($roleslog{$id}{'delflag'}) {
 6940:             $rolestart = &mt('deleted');
 6941:             $roleend = &mt('deleted');
 6942:         } else {
 6943:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6944:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6945:             if ($rolestart eq '' || $rolestart == 0) {
 6946:                 $rolestart = &mt('No start date'); 
 6947:             } else {
 6948:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6949:             }
 6950:             if ($roleend eq '' || $roleend == 0) { 
 6951:                 $roleend = &mt('No end date');
 6952:             } else {
 6953:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6954:             }
 6955:         }
 6956:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6957:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6958:             $chgcontext = 'selfenroll';
 6959:         }
 6960:         my %lt = &rolechg_contexts($context,$crstype);
 6961:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6962:             $chgcontext = $lt{$chgcontext};
 6963:         }
 6964:         $r->print(
 6965:             &Apache::loncommon::start_data_table_row()
 6966:            .'<td>'.$count.'</td>'
 6967:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6968:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6969:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6970:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6971:         if ($context eq 'course') { 
 6972:             $r->print('<td>'.$sec.'</td>');
 6973:         }
 6974:         $r->print(
 6975:             '<td>'.$chgcontext.'</td>'
 6976:            .'<td>'.$rolestart.'</td>'
 6977:            .'<td>'.$roleend.'</td>'
 6978:            .&Apache::loncommon::end_data_table_row()."\n");
 6979:     }
 6980: 
 6981:     if ($showntableheader) { # Table footer, if content displayed above
 6982:         $r->print(&Apache::loncommon::end_data_table().
 6983:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6984:     } else { # No content displayed above
 6985:         $r->print('<p class="LC_info">'
 6986:                  .&mt('There are no records to display.')
 6987:                  .'</p>'
 6988:         );
 6989:     }
 6990: 
 6991:     # Form Footer
 6992:     $r->print( 
 6993:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6994:        .'<input type="hidden" name="action" value="changelogs" />'
 6995:        .'</form>');
 6996:     return;
 6997: }
 6998: 
 6999: sub print_useraccesslogs_display {
 7000:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 7001:     my $formname = 'accesslog';
 7002:     my $form = 'document.accesslog';
 7003: 
 7004: # set breadcrumbs
 7005:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 7006:     my $prevphasestr;
 7007:     if ($env{'form.popup'}) {
 7008:         $brcrum = [];
 7009:     } else {
 7010:         push (@{$brcrum},
 7011:             {href => "javascript:backPage($form)",
 7012:              text => $breadcrumb_text{'search'}});
 7013:         my @prevphases;
 7014:         if ($env{'form.prevphases'}) {
 7015:             @prevphases = split(/,/,$env{'form.prevphases'});
 7016:             $prevphasestr = $env{'form.prevphases'};
 7017:         }
 7018:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 7019:             push(@{$brcrum},
 7020:                   {href => "javascript:backPage($form,'get_user_info','select')",
 7021:                    text => $breadcrumb_text{'userpicked'}});
 7022:             if ($env{'form.phase'} eq 'userpicked') {
 7023:                 $prevphasestr = 'userpicked';
 7024:             }
 7025:         }
 7026:     }
 7027:     push(@{$brcrum},
 7028:              {href => '/adm/createuser?action=accesslogs',
 7029:               text => 'User access logs',
 7030:               help => 'Domain_User_Access_Logs'});
 7031:     my $bread_crumbs_component = 'User Access Logs';
 7032:     my $args = { bread_crumbs           => $brcrum,
 7033:                  bread_crumbs_component => 'User Management'};
 7034:     if ($env{'form.popup'}) {
 7035:         $args->{'no_nav_bar'} = 1;
 7036:         $args->{'bread_crumbs_nomenu'} = 1;
 7037:     }
 7038: 
 7039: # set javascript
 7040:     my ($jsback,$elements) = &crumb_utilities();
 7041:     my $jsnav = &userlogdisplay_js($formname);
 7042: 
 7043:     my $jscript = (<<ENDSCRIPT);
 7044: <script type="text/javascript">
 7045: // <![CDATA[
 7046: 
 7047: $jsback
 7048: $jsnav
 7049: 
 7050: // ]]>
 7051: </script>
 7052: 
 7053: ENDSCRIPT
 7054: 
 7055: # print page header
 7056:     $r->print(&header($jscript,$args));
 7057: 
 7058: # early out unless log data can be displayed.
 7059:     unless ($permission->{'activity'}) {
 7060:         $r->print('<p class="LC_warning">'
 7061:                  .&mt('You do not have rights to display user access logs.')
 7062:                  .'</p>');
 7063:         if ($env{'form.popup'}) {
 7064:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7065:         } else {
 7066:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7067:         }
 7068:         return;
 7069:     }
 7070: 
 7071:     unless ($udom eq $env{'request.role.domain'}) {
 7072:         $r->print('<p class="LC_warning">'
 7073:                  .&mt("User's domain must match role's domain")
 7074:                  .'</p>'
 7075:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7076:         return;
 7077:     }
 7078: 
 7079:     if (($uname eq '') || ($udom eq '')) {
 7080:         $r->print('<p class="LC_warning">'
 7081:                  .&mt('Invalid username or domain')
 7082:                  .'</p>'
 7083:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7084:         return;
 7085:     }
 7086: 
 7087:     if (&Apache::lonnet::privileged($uname,$udom,
 7088:                                     [$env{'request.role.domain'}],['dc','su'])) {
 7089:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 7090:                                             [$env{'request.role.domain'}],['dc','su'])) {
 7091:             $r->print('<p class="LC_warning">'
 7092:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 7093:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 7094:                                                          $uname,$udom))
 7095:                  .'</p>');
 7096:             if ($env{'form.popup'}) {
 7097:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7098:             } else {
 7099:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7100:             }
 7101:             return;
 7102:         }
 7103:     }
 7104: 
 7105: # set defaults
 7106:     my $now = time();
 7107:     my $defstart = $now - (7*24*3600);
 7108:     my %defaults = (
 7109:                      page                 => '1',
 7110:                      show                 => '10',
 7111:                      activity             => 'any',
 7112:                      accesslog_start_date => $defstart,
 7113:                      accesslog_end_date   => $now,
 7114:                    );
 7115:     my $more_records = 0;
 7116: 
 7117: # set current
 7118:     my %curr;
 7119:     foreach my $item ('show','page','activity') {
 7120:         $curr{$item} = $env{'form.'.$item};
 7121:     }
 7122:     my ($startdate,$enddate) =
 7123:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 7124:     $curr{'accesslog_start_date'} = $startdate;
 7125:     $curr{'accesslog_end_date'} = $enddate;
 7126:     foreach my $key (keys(%defaults)) {
 7127:         if ($curr{$key} eq '') {
 7128:             $curr{$key} = $defaults{$key};
 7129:         }
 7130:     }
 7131:     my ($minshown,$maxshown);
 7132:     $minshown = 1;
 7133:     my $count = 0;
 7134:     if ($curr{'show'} =~ /\D/) {
 7135:         $curr{'page'} = 1;
 7136:     } else {
 7137:         $maxshown = $curr{'page'} * $curr{'show'};
 7138:         if ($curr{'page'} > 1) {
 7139:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 7140:         }
 7141:     }
 7142: 
 7143: # form header
 7144:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 7145:               &activity_display_filter($formname,\%curr));
 7146: 
 7147:     my $showntableheader = 0;
 7148:     my ($nav_script,$nav_links);
 7149: 
 7150: # table header
 7151:     my $heading = '<h3>'.
 7152:         &mt('User access logs for: [_1]',
 7153:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>';
 7154:     my $tableheader = $heading
 7155:        .&Apache::loncommon::start_data_table_header_row()
 7156:        .'<th>&nbsp;</th>'
 7157:        .'<th>'.&mt('When').'</th>'
 7158:        .'<th>'.&mt('HostID').'</th>'
 7159:        .'<th>'.&mt('Event').'</th>'
 7160:        .'<th>'.&mt('Other data').'</th>'
 7161:        .&Apache::loncommon::end_data_table_header_row();
 7162: 
 7163:     my %filters=(
 7164:         start  => $curr{'accesslog_start_date'},
 7165:         end    => $curr{'accesslog_end_date'},
 7166:         action => $curr{'activity'},
 7167:     );
 7168: 
 7169:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 7170:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7171:         my (%courses,%missing);
 7172:         my @results = split(/\&/,$reply);
 7173:         foreach my $item (reverse(@results)) {
 7174:             my ($timestamp,$host,$event) = split(/:/,$item);
 7175:             next unless ($event =~ /^(Log|Role)/);
 7176:             if ($curr{'show'} !~ /\D/) {
 7177:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 7178:                     $more_records = 1;
 7179:                     last;
 7180:                 }
 7181:             }
 7182:             $count ++;
 7183:             next if ($count < $minshown);
 7184:             unless ($showntableheader) {
 7185:                 $r->print($nav_script
 7186:                          .&Apache::loncommon::start_data_table()
 7187:                          .$tableheader);
 7188:                 $r->rflush();
 7189:                 $showntableheader = 1;
 7190:             }
 7191:             my ($shown,$extra);
 7192:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 7193:             if ($event eq 'Role') {
 7194:                 my ($rolecode,$extent) = split(/\./,$data,2);
 7195:                 next if ($extent eq '');
 7196:                 my ($crstype,$desc,$info);
 7197:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 7198:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 7199:                     my $cid = $cdom.'_'.$cnum;
 7200:                     if (exists($courses{$cid})) {
 7201:                         $crstype = $courses{$cid}{'type'};
 7202:                         $desc = $courses{$cid}{'description'};
 7203:                     } elsif ($missing{$cid}) {
 7204:                         $crstype = 'Course';
 7205:                         $desc = 'Course/Community';
 7206:                     } else {
 7207:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7208:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 7209:                             $courses{$cid} = $crsinfo{$cid};
 7210:                             $crstype = $crsinfo{$cid}{'type'};
 7211:                             $desc = $crsinfo{$cid}{'description'};
 7212:                         } else {
 7213:                             $missing{$cid} = 1;
 7214:                         }
 7215:                     }
 7216:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 7217:                     if ($sec ne '') {
 7218:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 7219:                     }
 7220:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 7221:                     my ($dom,$name) = ($1,$2);
 7222:                     if ($rolecode eq 'au') {
 7223:                         $extra = '';
 7224:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 7225:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 7226:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 7227:                         $extra = &mt('Domain: [_1]',$dom);
 7228:                     }
 7229:                 }
 7230:                 my $rolename;
 7231:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 7232:                     my $role = $3;
 7233:                     my $owner = "($2:$1)";
 7234:                     if ($2 eq $1.'-domainconfig') {
 7235:                         $owner = '(ad hoc)';
 7236:                     }
 7237:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7238:                 } else {
 7239:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7240:                 }
 7241:                 $shown = &mt('Role selection: [_1]',$rolename);
 7242:             } else {
 7243:                 $shown = &mt($event);
 7244:                 if ($data =~ /^webdav/) {
 7245:                     my ($path,$clientip) = split(/\s+/,$data,2);
 7246:                     $path =~ s/^webdav//;
 7247:                     if ($clientip ne '') {
 7248:                         $extra = &mt('Client IP address: [_1]',$clientip);
 7249:                     }
 7250:                     if ($path ne '') {
 7251:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 7252:                     }
 7253:                 } elsif ($data ne '') {
 7254:                     $extra = &mt('Client IP address: [_1]',$data);
 7255:                 }
 7256:             }
 7257:             $r->print(
 7258:             &Apache::loncommon::start_data_table_row()
 7259:            .'<td>'.$count.'</td>'
 7260:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7261:            .'<td>'.$host.'</td>'
 7262:            .'<td>'.$shown.'</td>'
 7263:            .'<td>'.$extra.'</td>'
 7264:            .&Apache::loncommon::end_data_table_row()."\n");
 7265:         }
 7266:     }
 7267: 
 7268:     if ($showntableheader) { # Table footer, if content displayed above
 7269:         $r->print(&Apache::loncommon::end_data_table().
 7270:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7271:     } else { # No content displayed above
 7272:         $r->print($heading.'<p class="LC_info">'
 7273:                  .&mt('There are no records to display.')
 7274:                  .'</p>');
 7275:     }
 7276: 
 7277:     if ($env{'form.popup'} == 1) {
 7278:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 7279:     }
 7280: 
 7281:     # Form Footer
 7282:     $r->print(
 7283:         '<input type="hidden" name="currstate" value="" />'
 7284:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7285:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7286:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7287:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7288:        .'<input type="hidden" name="phase" value="activity" />'
 7289:        .'<input type="hidden" name="action" value="accesslogs" />'
 7290:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7291:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7292:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7293:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7294:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7295:        .'</form>');
 7296:     return;
 7297: }
 7298: 
 7299: sub earlyout_accesslog_form {
 7300:     my ($formname,$prevphasestr,$udom) = @_;
 7301:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7302:    return <<"END";
 7303: <form action="/adm/createuser" method="post" name="$formname">
 7304: <input type="hidden" name="currstate" value="" />
 7305: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7306: <input type="hidden" name="phase" value="activity" />
 7307: <input type="hidden" name="action" value="accesslogs" />
 7308: <input type="hidden" name="srchdomain" value="$udom" />
 7309: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7310: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7311: <input type="hidden" name="srchterm" value="$srchterm" />
 7312: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7313: </form>
 7314: END
 7315: }
 7316: 
 7317: sub activity_display_filter {
 7318:     my ($formname,$curr) = @_;
 7319:     my $nolink = 1;
 7320:     my $output = '<table><tr><td valign="top">'.
 7321:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7322:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7323:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7324:                  '</td><td>&nbsp;&nbsp;</td>';
 7325:     my $startform =
 7326:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7327:                                             $curr->{'accesslog_start_date'},undef,
 7328:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7329:     my $endform =
 7330:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7331:                                             $curr->{'accesslog_end_date'},undef,
 7332:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7333:     my %lt = &Apache::lonlocal::texthash (
 7334:                                           activity => 'Activity',
 7335:                                           Role     => 'Role selection',
 7336:                                           log      => 'Log-in or Logout',
 7337:     );
 7338:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7339:                '<table><tr><td>'.&mt('After:').
 7340:                '</td><td>'.$startform.'</td></tr>'.
 7341:                '<tr><td>'.&mt('Before:').'</td>'.
 7342:                '<td>'.$endform.'</td></tr></table>'.
 7343:                '</td>'.
 7344:                '<td>&nbsp;&nbsp;</td>'.
 7345:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7346:                '<select name="activity"><option value="any"';
 7347:     if ($curr->{'activity'} eq 'any') {
 7348:         $output .= ' selected="selected"';
 7349:     }
 7350:     $output .= '>'.&mt('Any').'</option>'."\n";
 7351:     foreach my $activity ('Role','log') {
 7352:         my $selstr = '';
 7353:         if ($activity eq $curr->{'activity'}) {
 7354:             $selstr = ' selected="selected"';
 7355:         }
 7356:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7357:     }
 7358:     $output .= '</select></td>'.
 7359:                '</tr></table>';
 7360:     # Update Display button
 7361:     $output .= '<p>'
 7362:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7363:               .'</p><hr />';
 7364:     return $output;
 7365: }
 7366: 
 7367: sub userlogdisplay_js {
 7368:     my ($formname) = @_;
 7369:     return <<"ENDSCRIPT";
 7370: 
 7371: function chgPage(caller) {
 7372:     if (caller == 'previous') {
 7373:         document.$formname.page.value --;
 7374:     }
 7375:     if (caller == 'next') {
 7376:         document.$formname.page.value ++;
 7377:     }
 7378:     document.$formname.submit();
 7379:     return;
 7380: }
 7381: ENDSCRIPT
 7382: }
 7383: 
 7384: sub userlogdisplay_navlinks {
 7385:     my ($curr,$more_records) = @_;
 7386:     return unless(ref($curr) eq 'HASH');
 7387:     # Navigation Buttons
 7388:     my $nav_links = '<p>';
 7389:     if (($curr->{'page'} > 1) || ($more_records)) {
 7390:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7391:             $nav_links .= '<input type="button"'
 7392:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7393:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7394:                          .'" /> ';
 7395:         }
 7396:         if ($more_records) {
 7397:             $nav_links .= '<input type="button"'
 7398:                          .' onclick="javascript:chgPage('."'next'".');"'
 7399:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7400:                          .'" />';
 7401:         }
 7402:     }
 7403:     $nav_links .= '</p>';
 7404:     return $nav_links;
 7405: }
 7406: 
 7407: sub role_display_filter {
 7408:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7409:     my $lctype;
 7410:     if ($context eq 'course') {
 7411:         $lctype = lc($crstype);
 7412:     }
 7413:     my $nolink = 1;
 7414:     my $output = '<table><tr><td valign="top">'.
 7415:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7416:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7417:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7418:                  '</td><td>&nbsp;&nbsp;</td>';
 7419:     my $startform =
 7420:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7421:                                             $curr->{'rolelog_start_date'},undef,
 7422:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7423:     my $endform =
 7424:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7425:                                             $curr->{'rolelog_end_date'},undef,
 7426:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7427:     my %lt = &rolechg_contexts($context,$crstype);
 7428:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7429:                '<table><tr><td>'.&mt('After:').
 7430:                '</td><td>'.$startform.'</td></tr>'.
 7431:                '<tr><td>'.&mt('Before:').'</td>'.
 7432:                '<td>'.$endform.'</td></tr></table>'.
 7433:                '</td>'.
 7434:                '<td>&nbsp;&nbsp;</td>'.
 7435:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7436:                '<select name="role"><option value="any"';
 7437:     if ($curr->{'role'} eq 'any') {
 7438:         $output .= ' selected="selected"';
 7439:     }
 7440:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7441:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7442:     foreach my $role (@roles) {
 7443:         my $plrole;
 7444:         if ($role eq 'cr') {
 7445:             $plrole = &mt('Custom Role');
 7446:         } else {
 7447:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7448:         }
 7449:         my $selstr = '';
 7450:         if ($role eq $curr->{'role'}) {
 7451:             $selstr = ' selected="selected"';
 7452:         }
 7453:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7454:     }
 7455:     $output .= '</select></td>'.
 7456:                '<td>&nbsp;&nbsp;</td>'.
 7457:                '<td valign="top"><b>'.
 7458:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7459:     my @posscontexts;
 7460:     if ($context eq 'course') {
 7461:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 7462:     } elsif ($context eq 'domain') {
 7463:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7464:     } else {
 7465:         @posscontexts = ('any','author','domain');
 7466:     } 
 7467:     foreach my $chgtype (@posscontexts) {
 7468:         my $selstr = '';
 7469:         if ($curr->{'chgcontext'} eq $chgtype) {
 7470:             $selstr = ' selected="selected"';
 7471:         }
 7472:         if ($context eq 'course') {
 7473:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7474:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7475:             }
 7476:         }
 7477:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7478:     }
 7479:     $output .= '</select></td>'
 7480:               .'</tr></table>';
 7481: 
 7482:     # Update Display button
 7483:     $output .= '<p>'
 7484:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7485:               .'</p>';
 7486: 
 7487:     # Server version info
 7488:     my $needsrev = '2.11.0';
 7489:     if ($context eq 'course') {
 7490:         $needsrev = '2.7.0';
 7491:     }
 7492:     
 7493:     $output .= '<p class="LC_info">'
 7494:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7495:                   ,$needsrev);
 7496:     if ($version) {
 7497:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7498:     }
 7499:     $output .= '</p><hr />';
 7500:     return $output;
 7501: }
 7502: 
 7503: sub rolechg_contexts {
 7504:     my ($context,$crstype) = @_;
 7505:     my %lt;
 7506:     if ($context eq 'course') {
 7507:         %lt = &Apache::lonlocal::texthash (
 7508:                                              any          => 'Any',
 7509:                                              automated    => 'Automated Enrollment',
 7510:                                              updatenow    => 'Roster Update',
 7511:                                              createcourse => 'Course Creation',
 7512:                                              course       => 'User Management in course',
 7513:                                              domain       => 'User Management in domain',
 7514:                                              selfenroll   => 'Self-enrolled',
 7515:                                              requestcourses => 'Course Request',
 7516:                                          );
 7517:         if ($crstype eq 'Community') {
 7518:             $lt{'createcourse'} = &mt('Community Creation');
 7519:             $lt{'course'} = &mt('User Management in community');
 7520:             $lt{'requestcourses'} = &mt('Community Request');
 7521:         }
 7522:     } elsif ($context eq 'domain') {
 7523:         %lt = &Apache::lonlocal::texthash (
 7524:                                              any           => 'Any',
 7525:                                              domain        => 'User Management in domain',
 7526:                                              requestauthor => 'Authoring Request',
 7527:                                              server        => 'Command line script (DC role)',
 7528:                                              domconfig     => 'Self-enrolled',
 7529:                                          );
 7530:     } else {
 7531:         %lt = &Apache::lonlocal::texthash (
 7532:                                              any    => 'Any',
 7533:                                              domain => 'User Management in domain',
 7534:                                              author => 'User Management by author',
 7535:                                          );
 7536:     } 
 7537:     return %lt;
 7538: }
 7539: 
 7540: sub print_helpdeskaccess_display {
 7541:     my ($r,$permission,$brcrum) = @_;
 7542:     my $formname = 'helpdeskaccess';
 7543:     my $helpitem = 'Course_Helpdesk_Access';
 7544:     push (@{$brcrum},
 7545:              {href => '/adm/createuser?action=helpdesk',
 7546:               text => 'Helpdesk Access',
 7547:               help => $helpitem});
 7548:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7549:     my $args = { bread_crumbs           => $brcrum,
 7550:                  bread_crumbs_component => $bread_crumbs_component};
 7551: 
 7552:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7553:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7554:     my $confname = $cdom.'-domainconfig';
 7555:     my $crstype = &Apache::loncommon::course_type();
 7556: 
 7557:     my @accesstypes = ('all','dh','da','none');
 7558:     my ($numstatustypes,@jsarray);
 7559:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7560:     if (ref($types) eq 'ARRAY') {
 7561:         if (@{$types} > 0) {
 7562:             $numstatustypes = scalar(@{$types});
 7563:             push(@accesstypes,'status');
 7564:             @jsarray = ('bystatus');
 7565:         }
 7566:     }
 7567:     my %customroles = &get_domain_customroles($cdom,$confname);
 7568:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7569:     if (keys(%domhelpdesk)) {
 7570:        push(@accesstypes,('inc','exc'));
 7571:        push(@jsarray,('notinc','notexc'));
 7572:     }
 7573:     push(@jsarray,'privs');
 7574:     my $hiddenstr = join("','",@jsarray);
 7575:     my $rolestr = join("','",sort(keys(%customroles)));
 7576: 
 7577:     my $jscript;
 7578:     my (%settings,%overridden);
 7579:     if (keys(%customroles)) {
 7580:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7581:                                 $types,\%customroles,\%settings,\%overridden);
 7582:         my %jsfull=();
 7583:         my %jslevels= (
 7584:                      course => {},
 7585:                      domain => {},
 7586:                      system => {},
 7587:                     );
 7588:         my %jslevelscurrent=(
 7589:                            course => {},
 7590:                            domain => {},
 7591:                            system => {},
 7592:                           );
 7593:         my (%privs,%jsprivs);
 7594:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7595:         foreach my $priv (keys(%jsfull)) {
 7596:             if ($jslevels{'course'}{$priv}) {
 7597:                 $jsprivs{$priv} = 1;
 7598:             }
 7599:         }
 7600:         my (%elements,%stored);
 7601:         foreach my $role (keys(%customroles)) {
 7602:             $elements{$role.'_access'} = 'radio';
 7603:             $elements{$role.'_incrs'} = 'radio';
 7604:             if ($numstatustypes) {
 7605:                 $elements{$role.'_status'} = 'checkbox';
 7606:             }
 7607:             if (keys(%domhelpdesk) > 0) {
 7608:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7609:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7610:             }
 7611:             $elements{$role.'_override'} = 'checkbox';
 7612:             if (ref($settings{$role}) eq 'HASH') {
 7613:                 if ($settings{$role}{'access'} ne '') {
 7614:                     my $curraccess = $settings{$role}{'access'};
 7615:                     $stored{$role.'_access'} = $curraccess;
 7616:                     $stored{$role.'_incrs'} = 1;
 7617:                     if ($curraccess eq 'status') {
 7618:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7619:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7620:                         }
 7621:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7622:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7623:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7624:                         }
 7625:                     }
 7626:                 } else {
 7627:                     $stored{$role.'_incrs'} = 0;
 7628:                 }
 7629:                 $stored{$role.'_override'} = [];
 7630:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7631:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7632:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7633:                             push(@{$stored{$role.'_override'}},$priv);
 7634:                         }
 7635:                     }
 7636:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7637:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7638:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7639:                                 push(@{$stored{$role.'_override'}},$priv);
 7640:                             }
 7641:                         }
 7642:                     }
 7643:                 }
 7644:             } else {
 7645:                 $stored{$role.'_incrs'} = 0;
 7646:             }
 7647:         }
 7648:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7649:     }
 7650: 
 7651:     my $js = <<"ENDJS";
 7652: <script type="text/javascript">
 7653: // <![CDATA[
 7654: $jscript;
 7655: 
 7656: function switchRoleTab(caller,role) {
 7657:     if (document.getElementById(role+'_maindiv')) {
 7658:         if (caller.id != 'LC_current_minitab') {
 7659:             if (document.getElementById('LC_current_minitab')) {
 7660:                 document.getElementById('LC_current_minitab').id=null;
 7661:             }
 7662:             var roledivs = Array('$rolestr');
 7663:             if (roledivs.length > 0) {
 7664:                 for (var i=0; i<roledivs.length; i++) {
 7665:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7666:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7667:                     }
 7668:                 }
 7669:             }
 7670:             caller.id = 'LC_current_minitab';
 7671:             document.getElementById(role+'_maindiv').style.display='block';
 7672:         }
 7673:     }
 7674:     return false;
 7675: }
 7676: 
 7677: function helpdeskAccess(role) {
 7678:     var curraccess = null;
 7679:     if (document.$formname.elements[role+'_access'].length) {
 7680:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7681:             if (document.$formname.elements[role+'_access'][i].checked) {
 7682:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7683:             }
 7684:         }
 7685:     }
 7686:     var shown = Array();
 7687:     var hidden = Array();
 7688:     if (curraccess == 'none') {
 7689:         hidden = Array ('$hiddenstr');
 7690:     } else {
 7691:         if (curraccess == 'status') {
 7692:             shown = Array ('bystatus','privs');
 7693:             hidden = Array ('notinc','notexc');
 7694:         } else {
 7695:             if (curraccess == 'exc') {
 7696:                 shown = Array ('notexc','privs');
 7697:                 hidden = Array ('notinc','bystatus');
 7698:             }
 7699:             if (curraccess == 'inc') {
 7700:                 shown = Array ('notinc','privs');
 7701:                 hidden = Array ('notexc','bystatus');
 7702:             }
 7703:             if (curraccess == 'all') {
 7704:                 shown = Array ('privs');
 7705:                 hidden = Array ('notinc','notexc','bystatus');
 7706:             }
 7707:         }
 7708:     }
 7709:     if (hidden.length > 0) {
 7710:         for (var i=0; i<hidden.length; i++) {
 7711:             if (document.getElementById(role+'_'+hidden[i])) {
 7712:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 7713:             }
 7714:         }
 7715:     }
 7716:     if (shown.length > 0) {
 7717:         for (var i=0; i<shown.length; i++) {
 7718:             if (document.getElementById(role+'_'+shown[i])) {
 7719:                 if (shown[i] == 'privs') {
 7720:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7721:                 } else {
 7722:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7723:                 }
 7724:             }
 7725:         }
 7726:     }
 7727:     return;
 7728: }
 7729: 
 7730: function toggleAccess(role) {
 7731:     if ((document.getElementById(role+'_setincrs')) &&
 7732:         (document.getElementById(role+'_setindom'))) {
 7733:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7734:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7735:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7736:                     document.getElementById(role+'_setindom').style.display = 'none';
 7737:                     document.getElementById(role+'_setincrs').style.display = 'block';
 7738:                 } else {
 7739:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7740:                     document.getElementById(role+'_setindom').style.display = 'block';
 7741:                 }
 7742:                 break;
 7743:             }
 7744:         }
 7745:     }
 7746:     return;
 7747: }
 7748: 
 7749: // ]]>
 7750: </script>
 7751: ENDJS
 7752: 
 7753:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7754: 
 7755:     # print page header
 7756:     $r->print(&header($js,$args));
 7757:     # print form header
 7758:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7759: 
 7760:     if (keys(%customroles)) {
 7761:         my %lt = &Apache::lonlocal::texthash(
 7762:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7763:                     'rou'    => 'Role usage',
 7764:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7765:                     'udd'    => 'Use domain default',
 7766:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 7767:                     'dh'     => 'All with domain helpdesk role',
 7768:                     'da'     => 'All with domain helpdesk assistant role',
 7769:                     'none'   => 'None',
 7770:                     'status' => 'Determined based on institutional status',
 7771:                     'inc'    => 'Include all, but exclude specific personnel',
 7772:                     'exc'    => 'Exclude all, but include specific personnel',
 7773:                     'hel'    => 'Helpdesk',
 7774:                     'rpr'    => 'Role privileges',
 7775:                  );
 7776:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7777:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7778:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7779:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7780:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7781:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7782:             }
 7783:         }
 7784:         my $count = 0;
 7785:         foreach my $role (sort(keys(%customroles))) {
 7786:             my ($order,$desc,$access_in_dom);
 7787:             if (ref($domcurrent{$role}) eq 'HASH') {
 7788:                 $order = $domcurrent{$role}{'order'};
 7789:                 $desc = $domcurrent{$role}{'desc'};
 7790:                 $access_in_dom = $domcurrent{$role}{'access'};
 7791:             }
 7792:             if ($order eq '') {
 7793:                 $order = $count;
 7794:             }
 7795:             $ordered{$order} = $role;
 7796:             if ($desc ne '') {
 7797:                 $description{$role} = $desc;
 7798:             } else {
 7799:                 $description{$role}= $role;
 7800:             }
 7801:             $count++;
 7802:         }
 7803:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7804:         my @roles_by_num = ();
 7805:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7806:             push(@roles_by_num,$ordered{$item});
 7807:         }
 7808:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7809:         if ($permission->{'owner'}) {
 7810:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7811:             $r->print('<input type="hidden" name="state" value="process" />'.
 7812:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7813:         } else {
 7814:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7815:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7816:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7817:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7818:             }
 7819:             $disabled = ' disabled="disabled"';
 7820:         }
 7821:         $r->print('</p>');
 7822: 
 7823:         $r->print('<div id="LC_minitab_header"><ul>');
 7824:         my $count = 0;
 7825:         my %visibility;
 7826:         foreach my $role (@roles_by_num) {
 7827:             my $id;
 7828:             if ($count == 0) {
 7829:                 $id=' id="LC_current_minitab"';
 7830:                 $visibility{$role} = ' style="display:block"';
 7831:             } else {
 7832:                 $visibility{$role} = ' style="display:none"';
 7833:             }
 7834:             $count ++;
 7835:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7836:         }
 7837:         $r->print('</ul></div>');
 7838: 
 7839:         foreach my $role (@roles_by_num) {
 7840:             my %usecheck = (
 7841:                              all => ' checked="checked"',
 7842:                            );
 7843:             my %displaydiv = (
 7844:                                 status => 'none',
 7845:                                 inc    => 'none',
 7846:                                 exc    => 'none',
 7847:                                 priv   => 'block',
 7848:                              );
 7849:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7850:             if (ref($settings{$role}) eq 'HASH') {
 7851:                 if ($settings{$role}{'access'} ne '') {
 7852:                     $indomvis = ' style="display:none"';
 7853:                     $incrsvis = ' style="display:block"';
 7854:                     $incrscheck = ' checked="checked"';
 7855:                     if ($settings{$role}{'access'} ne 'all') {
 7856:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7857:                         delete($usecheck{'all'});
 7858:                         if ($settings{$role}{'access'} eq 'status') {
 7859:                             my $access = 'status';
 7860:                             $displaydiv{$access} = 'inline';
 7861:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7862:                                 $selected{$access} = $settings{$role}{$access};
 7863:                             }
 7864:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7865:                             my $access = $1;
 7866:                             $displaydiv{$access} = 'inline';
 7867:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7868:                                 $selected{$access} = $settings{$role}{$access};
 7869:                             }
 7870:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7871:                             $displaydiv{'priv'} = 'none';
 7872:                         }
 7873:                     }
 7874:                 } else {
 7875:                     $indomcheck = ' checked="checked"';
 7876:                     $indomvis = ' style="display:block"';
 7877:                     $incrsvis = ' style="display:none"';
 7878:                 }
 7879:             } else {
 7880:                 $indomcheck = ' checked="checked"';
 7881:                 $indomvis = ' style="display:block"';
 7882:                 $incrsvis = ' style="display:none"';
 7883:             }
 7884:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7885:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7886:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7887:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7888:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7889:                       '<span>'.('&nbsp;'x2).
 7890:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7891:                       $lt{'udd'}.'</label><span></p>'.
 7892:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7893:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7894:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7895:             foreach my $access (@accesstypes) {
 7896:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7897:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7898:                 if ($access eq 'status') {
 7899:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7900:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7901:                                                                         $othertitle,$usertypes,$types,$disabled).
 7902:                               '</div>');
 7903:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7904:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7905:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7906:                                                                  \%domhelpdesk,$disabled).
 7907:                               '</div>');
 7908:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7909:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7910:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7911:                                                                  \%domhelpdesk,$disabled).
 7912:                               '</div>');
 7913:                 }
 7914:                 $r->print('</p>');
 7915:             }
 7916:             $r->print('</div></fieldset>');
 7917:             my %full=();
 7918:             my %levels= (
 7919:                          course => {},
 7920:                          domain => {},
 7921:                          system => {},
 7922:                         );
 7923:             my %levelscurrent=(
 7924:                                course => {},
 7925:                                domain => {},
 7926:                                system => {},
 7927:                               );
 7928:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7929:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7930:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7931:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7932:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7933:         }
 7934:         if ($permission->{'owner'}) {
 7935:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7936:         }
 7937:     } else {
 7938:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7939:     }
 7940:     # Form Footer
 7941:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7942:              .'</form>');
 7943:     return;
 7944: }
 7945: 
 7946: sub domain_adhoc_access {
 7947:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7948:     my %domusage;
 7949:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7950:     foreach my $role (keys(%{$roles})) {
 7951:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7952:             my $access = $domcurrent->{$role}{'access'};
 7953:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7954:                 $access = 'all';
 7955:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 7956:                                                                                           &Apache::lonnet::plaintext('da'));
 7957:             } elsif ($access eq 'status') {
 7958:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7959:                     my @shown;
 7960:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7961:                         unless ($type eq 'default') {
 7962:                             if ($usertypes->{$type}) {
 7963:                                 push(@shown,$usertypes->{$type});
 7964:                             }
 7965:                         }
 7966:                     }
 7967:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7968:                         push(@shown,$othertitle);
 7969:                     }
 7970:                     if (@shown) {
 7971:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7972:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 7973:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 7974:                     } else {
 7975:                         $domusage{$role} = &mt('No one in the domain');
 7976:                     }
 7977:                 }
 7978:             } elsif ($access eq 'inc') {
 7979:                 my @dominc = ();
 7980:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7981:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7982:                         my ($uname,$udom) = split(/:/,$user);
 7983:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7984:                     }
 7985:                     my $showninc = join(', ',@dominc);
 7986:                     if ($showninc ne '') {
 7987:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 7988:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 7989:                     } else {
 7990:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7991:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7992:                     }
 7993:                 }
 7994:             } elsif ($access eq 'exc') {
 7995:                 my @domexc = ();
 7996:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 7997:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 7998:                         my ($uname,$udom) = split(/:/,$user);
 7999:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 8000:                     }
 8001:                 }
 8002:                 my $shownexc = join(', ',@domexc);
 8003:                 if ($shownexc ne '') {
 8004:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 8005:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 8006:                 } else {
 8007:                     $domusage{$role} = &mt('No one in the domain');
 8008:                 }
 8009:             } elsif ($access eq 'none') {
 8010:                 $domusage{$role} = &mt('No one in the domain');
 8011:             } elsif ($access eq 'dh') {
 8012:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 8013:             } elsif ($access eq 'da') {
 8014:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 8015:             } elsif ($access eq 'all') {
 8016:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 8017:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 8018:             }
 8019:         } else {
 8020:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 8021:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 8022:         }
 8023:     }
 8024:     return %domusage;
 8025: }
 8026: 
 8027: sub get_domain_customroles {
 8028:     my ($cdom,$confname) = @_;
 8029:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 8030:     my %customroles;
 8031:     foreach my $key (keys(%existing)) {
 8032:         if ($key=~/^rolesdef\_(\w+)$/) {
 8033:             my $rolename = $1;
 8034:             my %privs;
 8035:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 8036:             $customroles{$rolename} = \%privs;
 8037:         }
 8038:     }
 8039:     return %customroles;
 8040: }
 8041: 
 8042: sub role_priv_table {
 8043:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 8044:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 8045:                    (ref($levelscurrent) eq 'HASH'));
 8046:     my %lt=&Apache::lonlocal::texthash (
 8047:                     'crl'  => 'Course Level Privilege',
 8048:                     'def'  => 'Domain Defaults',
 8049:                     'ove'  => 'Override in Course',
 8050:                     'ine'  => 'In effect',
 8051:                     'dis'  => 'Disabled',
 8052:                     'ena'  => 'Enabled',
 8053:                    );
 8054:     if ($crstype eq 'Community') {
 8055:         $lt{'ove'} = 'Override in Community',
 8056:     }
 8057:     my @status = ('Disabled','Enabled');
 8058:     my (%on,%off);
 8059:     if (ref($overridden) eq 'HASH') {
 8060:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 8061:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 8062:         }
 8063:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 8064:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 8065:         }
 8066:     }
 8067:     my $output=&Apache::loncommon::start_data_table().
 8068:                &Apache::loncommon::start_data_table_header_row().
 8069:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 8070:                '</th><th>'.$lt{'ine'}.'</th>'.
 8071:                &Apache::loncommon::end_data_table_header_row();
 8072:     foreach my $priv (sort(keys(%{$full}))) {
 8073:         next unless ($levels->{'course'}{$priv});
 8074:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 8075:         my ($default,$ineffect);
 8076:         if ($levelscurrent->{'course'}{$priv}) {
 8077:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8078:             $ineffect = $default;
 8079:         }
 8080:         my ($customstatus,$checked);
 8081:         $output .= &Apache::loncommon::start_data_table_row().
 8082:                    '<td>'.$privtext.'</td>'.
 8083:                    '<td>'.$default.'</td><td>';
 8084:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 8085:             if ($permission->{'owner'}) {
 8086:                 $checked = ' checked="checked"';
 8087:             }
 8088:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 8089:             $ineffect = $customstatus;
 8090:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 8091:             if ($permission->{'owner'}) {
 8092:                 $checked = ' checked="checked"';
 8093:             }
 8094:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8095:             $ineffect = $customstatus;
 8096:         }
 8097:         if ($permission->{'owner'}) {
 8098:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 8099:         } else {
 8100:             $output .= $customstatus;
 8101:         }
 8102:         $output .= '</td><td>'.$ineffect.'</td>'.
 8103:                    &Apache::loncommon::end_data_table_row();
 8104:     }
 8105:     $output .= &Apache::loncommon::end_data_table();
 8106:     return $output;
 8107: }
 8108: 
 8109: sub get_adhocrole_settings {
 8110:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 8111:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 8112:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 8113:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 8114:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 8115:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 8116:             $settings->{$role}{'access'} = $curraccess;
 8117:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 8118:                 my @status = split(/,/,$rest);
 8119:                 my @currstatus;
 8120:                 foreach my $type (@status) {
 8121:                     if ($type eq 'default') {
 8122:                         push(@currstatus,$type);
 8123:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8124:                         push(@currstatus,$type);
 8125:                     }
 8126:                 }
 8127:                 if (@currstatus) {
 8128:                     $settings->{$role}{$curraccess} = \@currstatus;
 8129:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8130:                     my @personnel = split(/,/,$rest);
 8131:                     $settings->{$role}{$curraccess} = \@personnel;
 8132:                 }
 8133:             }
 8134:         }
 8135:     }
 8136:     foreach my $role (keys(%{$customroles})) {
 8137:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 8138:             my %currentprivs;
 8139:             if (ref($customroles->{$role}) eq 'HASH') {
 8140:                 if (exists($customroles->{$role}{'course'})) {
 8141:                     my %full=();
 8142:                     my %levels= (
 8143:                                   course => {},
 8144:                                   domain => {},
 8145:                                   system => {},
 8146:                                 );
 8147:                     my %levelscurrent=(
 8148:                                         course => {},
 8149:                                         domain => {},
 8150:                                         system => {},
 8151:                                       );
 8152:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 8153:                     %currentprivs = %{$levelscurrent{'course'}};
 8154:                 }
 8155:             }
 8156:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 8157:                 next if ($item eq '');
 8158:                 my ($rule,$rest) = split(/=/,$item);
 8159:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 8160:                 foreach my $priv (split(/:/,$rest)) {
 8161:                     if ($priv ne '') {
 8162:                         if ($rule eq 'off') {
 8163:                             push(@{$overridden->{$role}{'off'}},$priv);
 8164:                             if ($currentprivs{$priv}) {
 8165:                                 push(@{$settings->{$role}{'off'}},$priv);
 8166:                             }
 8167:                         } else {
 8168:                             push(@{$overridden->{$role}{'on'}},$priv);
 8169:                             unless ($currentprivs{$priv}) {
 8170:                                 push(@{$settings->{$role}{'on'}},$priv);
 8171:                             }
 8172:                         }
 8173:                     }
 8174:                 }
 8175:             }
 8176:         }
 8177:     }
 8178:     return;
 8179: }
 8180: 
 8181: sub update_helpdeskaccess {
 8182:     my ($r,$permission,$brcrum) = @_;
 8183:     my $helpitem = 'Course_Helpdesk_Access';
 8184:     push (@{$brcrum},
 8185:              {href => '/adm/createuser?action=helpdesk',
 8186:               text => 'Helpdesk Access',
 8187:               help => $helpitem},
 8188:              {href => '/adm/createuser?action=helpdesk',
 8189:               text => 'Result',
 8190:               help => $helpitem}
 8191:          );
 8192:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8193:     my $args = { bread_crumbs           => $brcrum,
 8194:                  bread_crumbs_component => $bread_crumbs_component};
 8195: 
 8196:     # print page header
 8197:     $r->print(&header('',$args));
 8198:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 8199:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 8200:         return;
 8201:     }
 8202:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 8203:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8204:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8205:     my $confname = $cdom.'-domainconfig';
 8206:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8207:     my $crstype = &Apache::loncommon::course_type();
 8208:     my %customroles = &get_domain_customroles($cdom,$confname);
 8209:     my (%settings,%overridden);
 8210:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8211:                             $types,\%customroles,\%settings,\%overridden);
 8212:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8213:     my (%changed,%storehash,@todelete);
 8214: 
 8215:     if (keys(%customroles)) {
 8216:         my (%newsettings,@incrs);
 8217:         foreach my $role (keys(%customroles)) {
 8218:             $newsettings{$role} = {
 8219:                                     access => '',
 8220:                                     status => '',
 8221:                                     exc    => '',
 8222:                                     inc    => '',
 8223:                                     on     => '',
 8224:                                     off    => '',
 8225:                                   };
 8226:             my %current;
 8227:             if (ref($settings{$role}) eq 'HASH') {
 8228:                 %current = %{$settings{$role}};
 8229:             }
 8230:             if (ref($overridden{$role}) eq 'HASH') {
 8231:                 $current{'overridden'} = $overridden{$role};
 8232:             }
 8233:             if ($env{'form.'.$role.'_incrs'}) {
 8234:                 my $access = $env{'form.'.$role.'_access'};
 8235:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 8236:                     push(@incrs,$role);
 8237:                     unless ($current{'access'} eq $access) {
 8238:                         $changed{$role}{'access'} = 1;
 8239:                         $storehash{'internal.adhoc.'.$role} = $access;
 8240:                     }
 8241:                     if ($access eq 'status') {
 8242:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 8243:                         my @stored;
 8244:                         my @shownstatus;
 8245:                         if (ref($types) eq 'ARRAY') {
 8246:                             foreach my $type (sort(@statuses)) {
 8247:                                 if ($type eq 'default') {
 8248:                                     push(@stored,$type);
 8249:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8250:                                     push(@stored,$type);
 8251:                                     push(@shownstatus,$usertypes->{$type});
 8252:                                 }
 8253:                             }
 8254:                             if (grep(/^default$/,@statuses)) {
 8255:                                 push(@shownstatus,$othertitle);
 8256:                             }
 8257:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8258:                         }
 8259:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 8260:                         if (ref($current{'status'}) eq 'ARRAY') {
 8261:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 8262:                             if (@diffs) {
 8263:                                 $changed{$role}{'status'} = 1;
 8264:                             }
 8265:                         } elsif (@stored) {
 8266:                             $changed{$role}{'status'} = 1;
 8267:                         }
 8268:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 8269:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 8270:                         my @newspecstaff;
 8271:                         my @stored;
 8272:                         my @currstaff;
 8273:                         foreach my $person (sort(@personnel)) {
 8274:                             if ($domhelpdesk{$person}) {
 8275:                                 push(@stored,$person);
 8276:                             }
 8277:                         }
 8278:                         if (ref($current{$access}) eq 'ARRAY') {
 8279:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 8280:                             if (@diffs) {
 8281:                                 $changed{$role}{$access} = 1;
 8282:                             }
 8283:                         } elsif (@stored) {
 8284:                             $changed{$role}{$access} = 1;
 8285:                         }
 8286:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8287:                         foreach my $person (@stored) {
 8288:                             my ($uname,$udom) = split(/:/,$person);
 8289:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 8290:                         }
 8291:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 8292:                     }
 8293:                     $newsettings{$role}{'access'} = $access;
 8294:                 }
 8295:             } else {
 8296:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 8297:                     $changed{$role}{'access'} = 1;
 8298:                     $newsettings{$role} = {};
 8299:                     push(@todelete,'internal.adhoc.'.$role);
 8300:                 }
 8301:             }
 8302:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 8303:                 if (ref($current{'overridden'}) eq 'HASH') {
 8304:                     push(@todelete,'internal.adhocpriv.'.$role);
 8305:                 }
 8306:             } else {
 8307:                 my %full=();
 8308:                 my %levels= (
 8309:                              course => {},
 8310:                              domain => {},
 8311:                              system => {},
 8312:                             );
 8313:                 my %levelscurrent=(
 8314:                                    course => {},
 8315:                                    domain => {},
 8316:                                    system => {},
 8317:                                   );
 8318:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 8319:                 my (@updatedon,@updatedoff,@override);
 8320:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 8321:                 if (@override) {
 8322:                     foreach my $priv (sort(keys(%full))) {
 8323:                         next unless ($levels{'course'}{$priv});
 8324:                         if (grep(/^\Q$priv\E$/,@override)) {
 8325:                             if ($levelscurrent{'course'}{$priv}) {
 8326:                                 push(@updatedoff,$priv);
 8327:                             } else {
 8328:                                 push(@updatedon,$priv);
 8329:                             }
 8330:                         }
 8331:                     }
 8332:                 }
 8333:                 if (@updatedon) {
 8334:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 8335:                 }
 8336:                 if (@updatedoff) {
 8337:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 8338:                 }
 8339:                 if (ref($current{'overridden'}) eq 'HASH') {
 8340:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 8341:                         if (@updatedon) {
 8342:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 8343:                             if (@diffs) {
 8344:                                 $changed{$role}{'on'} = 1;
 8345:                             }
 8346:                         } else {
 8347:                             $changed{$role}{'on'} = 1;
 8348:                         }
 8349:                     } elsif (@updatedon) {
 8350:                         $changed{$role}{'on'} = 1;
 8351:                     }
 8352:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 8353:                         if (@updatedoff) {
 8354:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 8355:                             if (@diffs) {
 8356:                                 $changed{$role}{'off'} = 1;
 8357:                             }
 8358:                         } else {
 8359:                             $changed{$role}{'off'} = 1;
 8360:                         }
 8361:                     } elsif (@updatedoff) {
 8362:                         $changed{$role}{'off'} = 1;
 8363:                     }
 8364:                 } else {
 8365:                     if (@updatedon) {
 8366:                         $changed{$role}{'on'} = 1;
 8367:                     }
 8368:                     if (@updatedoff) {
 8369:                         $changed{$role}{'off'} = 1;
 8370:                     }
 8371:                 }
 8372:                 if (ref($changed{$role}) eq 'HASH') {
 8373:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8374:                         my $newpriv;
 8375:                         if (@updatedon) {
 8376:                             $newpriv = 'on='.join(':',@updatedon);
 8377:                         }
 8378:                         if (@updatedoff) {
 8379:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8380:                         }
 8381:                         if ($newpriv eq '') {
 8382:                             push(@todelete,'internal.adhocpriv.'.$role);
 8383:                         } else {
 8384:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8385:                         }
 8386:                     }
 8387:                 }
 8388:             }
 8389:         }
 8390:         if (@incrs) {
 8391:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8392:         } elsif (@todelete) {
 8393:             push(@todelete,'internal.adhocaccess');
 8394:         }
 8395:         if (keys(%changed)) {
 8396:             my ($putres,$delres);
 8397:             if (keys(%storehash)) {
 8398:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8399:                 my %newenvhash;
 8400:                 foreach my $key (keys(%storehash)) {
 8401:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8402:                 }
 8403:                 &Apache::lonnet::appenv(\%newenvhash);
 8404:             }
 8405:             if (@todelete) {
 8406:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8407:                 foreach my $key (@todelete) {
 8408:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8409:                 }
 8410:             }
 8411:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8412:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8413:                 my (%domcurrent,%ordered,%description,%domusage);
 8414:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8415:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8416:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8417:                     }
 8418:                 }
 8419:                 my $count = 0;
 8420:                 foreach my $role (sort(keys(%customroles))) {
 8421:                     my ($order,$desc);
 8422:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8423:                         $order = $domcurrent{$role}{'order'};
 8424:                         $desc = $domcurrent{$role}{'desc'};
 8425:                     }
 8426:                     if ($order eq '') {
 8427:                         $order = $count;
 8428:                     }
 8429:                     $ordered{$order} = $role;
 8430:                     if ($desc ne '') {
 8431:                         $description{$role} = $desc;
 8432:                     } else {
 8433:                         $description{$role}= $role;
 8434:                     }
 8435:                     $count++;
 8436:                 }
 8437:                 my @roles_by_num = ();
 8438:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8439:                     push(@roles_by_num,$ordered{$item});
 8440:                 }
 8441:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8442:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8443:                 $r->print('<ul>');
 8444:                 foreach my $role (@roles_by_num) {
 8445:                     next unless (ref($changed{$role}) eq 'HASH');
 8446:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8447:                               '<ul>');
 8448:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8449:                         $r->print('<li>');
 8450:                         if ($env{'form.'.$role.'_incrs'}) {
 8451:                             if ($newsettings{$role}{'access'} eq 'all') {
 8452:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8453:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 8454:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8455:                                               &Apache::lonnet::plaintext('dh')));
 8456:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 8457:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8458:                                               &Apache::lonnet::plaintext('da')));
 8459:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8460:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8461:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8462:                                 if ($newsettings{$role}{'status'}) {
 8463:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8464:                                     if (split(/,/,$rest) > 1) {
 8465:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8466:                                                       $newsettings{$role}{'status'}));
 8467:                                     } else {
 8468:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8469:                                                       $newsettings{$role}{'status'}));
 8470:                                     }
 8471:                                 } else {
 8472:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8473:                                 }
 8474:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8475:                                 if ($newsettings{$role}{'exc'}) {
 8476:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8477:                                 } else {
 8478:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8479:                                 }
 8480:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8481:                                 if ($newsettings{$role}{'inc'}) {
 8482:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8483:                                 } else {
 8484:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8485:                                 }
 8486:                             }
 8487:                         } else {
 8488:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8489:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8490:                         }
 8491:                         $r->print('</li>');
 8492:                     }
 8493:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8494:                         if ($changed{$role}{'off'}) {
 8495:                             if ($newsettings{$role}{'off'}) {
 8496:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8497:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8498:                             } else {
 8499:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8500:                             }
 8501:                         }
 8502:                         if ($changed{$role}{'on'}) {
 8503:                             if ($newsettings{$role}{'on'}) {
 8504:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8505:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8506:                             } else {
 8507:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8508:                             }
 8509:                         }
 8510:                     }
 8511:                     $r->print('</ul></li>');
 8512:                 }
 8513:                 $r->print('</ul>');
 8514:             }
 8515:         } else {
 8516:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8517:         }
 8518:     }
 8519:     return;
 8520: }
 8521: 
 8522: #-------------------------------------------------- functions for &phase_two
 8523: sub user_search_result {
 8524:     my ($context,$srch) = @_;
 8525:     my %allhomes;
 8526:     my %inst_matches;
 8527:     my %srch_results;
 8528:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8529:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8530:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8531:         $response = &mt('Invalid search.');
 8532:     }
 8533:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8534:         $response = &mt('Invalid search.');
 8535:     }
 8536:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8537:         $response = &mt('Invalid search.');
 8538:     }
 8539:     if ($srch->{'srchterm'} eq '') {
 8540:         $response = &mt('You must enter a search term.');
 8541:     }
 8542:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8543:         $response = &mt('Your search term must contain more than just spaces.');
 8544:     }
 8545:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8546:         if (($srch->{'srchdomain'} eq '') || 
 8547: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8548:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8549:         }
 8550:     }
 8551:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8552:         ($srch->{'srchin'} eq 'alc')) {
 8553:         if ($srch->{'srchby'} eq 'uname') {
 8554:             my $unamecheck = $srch->{'srchterm'};
 8555:             if ($srch->{'srchtype'} eq 'contains') {
 8556:                 if ($unamecheck !~ /^\w/) {
 8557:                     $unamecheck = 'a'.$unamecheck; 
 8558:                 }
 8559:             }
 8560:             if ($unamecheck !~ /^$match_username$/) {
 8561:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8562:             }
 8563:         }
 8564:     }
 8565:     if ($response ne '') {
 8566:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8567:     }
 8568:     if ($srch->{'srchin'} eq 'instd') {
 8569:         my $instd_chk = &instdirectorysrch_check($srch);
 8570:         if ($instd_chk ne 'ok') {
 8571:             my $domd_chk = &domdirectorysrch_check($srch);
 8572:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8573:             if ($domd_chk eq 'ok') {
 8574:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 8575:             }
 8576:             $response .= '<br />';
 8577:         }
 8578:     } else {
 8579:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8580:             my $domd_chk = &domdirectorysrch_check($srch);
 8581:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 8582:                 my $instd_chk = &instdirectorysrch_check($srch);
 8583:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8584:                 if ($instd_chk eq 'ok') {
 8585:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 8586:                 }
 8587:                 $response .= '<br />';
 8588:             }
 8589:         }
 8590:     }
 8591:     if ($response ne '') {
 8592:         return ($currstate,$response);
 8593:     }
 8594:     if ($srch->{'srchby'} eq 'uname') {
 8595:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8596:             if ($env{'form.forcenew'}) {
 8597:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8598:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8599:                     if ($uhome eq 'no_host') {
 8600:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8601:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8602:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8603:                     } else {
 8604:                         $currstate = 'modify';
 8605:                     }
 8606:                 } else {
 8607:                     $currstate = 'modify';
 8608:                 }
 8609:             } else {
 8610:                 if ($srch->{'srchin'} eq 'dom') {
 8611:                     if ($srch->{'srchtype'} eq 'exact') {
 8612:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8613:                         if ($uhome eq 'no_host') {
 8614:                             ($currstate,$response,$forcenewuser) =
 8615:                                 &build_search_response($context,$srch,%srch_results);
 8616:                         } else {
 8617:                             $currstate = 'modify';
 8618:                             if ($env{'form.action'} eq 'accesslogs') {
 8619:                                 $currstate = 'activity';
 8620:                             }
 8621:                             my $uname = $srch->{'srchterm'};
 8622:                             my $udom = $srch->{'srchdomain'};
 8623:                             $srch_results{$uname.':'.$udom} =
 8624:                                 { &Apache::lonnet::get('environment',
 8625:                                                        ['firstname',
 8626:                                                         'lastname',
 8627:                                                         'permanentemail'],
 8628:                                                          $udom,$uname)
 8629:                                 };
 8630:                         }
 8631:                     } else {
 8632:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8633:                         ($currstate,$response,$forcenewuser) =
 8634:                             &build_search_response($context,$srch,%srch_results);
 8635:                     }
 8636:                 } else {
 8637:                     my $courseusers = &get_courseusers();
 8638:                     if ($srch->{'srchtype'} eq 'exact') {
 8639:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8640:                             $currstate = 'modify';
 8641:                         } else {
 8642:                             ($currstate,$response,$forcenewuser) =
 8643:                                 &build_search_response($context,$srch,%srch_results);
 8644:                         }
 8645:                     } else {
 8646:                         foreach my $user (keys(%$courseusers)) {
 8647:                             my ($cuname,$cudomain) = split(/:/,$user);
 8648:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8649:                                 my $matched = 0;
 8650:                                 if ($srch->{'srchtype'} eq 'begins') {
 8651:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8652:                                         $matched = 1;
 8653:                                     }
 8654:                                 } else {
 8655:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8656:                                         $matched = 1;
 8657:                                     }
 8658:                                 }
 8659:                                 if ($matched) {
 8660:                                     $srch_results{$user} = 
 8661: 					{&Apache::lonnet::get('environment',
 8662: 							     ['firstname',
 8663: 							      'lastname',
 8664: 							      'permanentemail'],
 8665: 							      $cudomain,$cuname)};
 8666:                                 }
 8667:                             }
 8668:                         }
 8669:                         ($currstate,$response,$forcenewuser) =
 8670:                             &build_search_response($context,$srch,%srch_results);
 8671:                     }
 8672:                 }
 8673:             }
 8674:         } elsif ($srch->{'srchin'} eq 'alc') {
 8675:             $currstate = 'query';
 8676:         } elsif ($srch->{'srchin'} eq 'instd') {
 8677:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8678:             if ($dirsrchres eq 'ok') {
 8679:                 ($currstate,$response,$forcenewuser) = 
 8680:                     &build_search_response($context,$srch,%srch_results);
 8681:             } else {
 8682:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8683:                 $response = '<span class="LC_warning">'.
 8684:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8685:                     '</span><br />'.
 8686:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8687:                     '<br />'; 
 8688:             }
 8689:         }
 8690:     } else {
 8691:         if ($srch->{'srchin'} eq 'dom') {
 8692:             %srch_results = &Apache::lonnet::usersearch($srch);
 8693:             ($currstate,$response,$forcenewuser) = 
 8694:                 &build_search_response($context,$srch,%srch_results); 
 8695:         } elsif ($srch->{'srchin'} eq 'crs') {
 8696:             my $courseusers = &get_courseusers(); 
 8697:             foreach my $user (keys(%$courseusers)) {
 8698:                 my ($uname,$udom) = split(/:/,$user);
 8699:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8700:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8701:                 if ($srch->{'srchby'} eq 'lastname') {
 8702:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8703:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8704:                         (($srch->{'srchtype'} eq 'begins') &&
 8705:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8706:                         (($srch->{'srchtype'} eq 'contains') &&
 8707:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8708:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8709:                                             lastname => $names{'lastname'},
 8710:                                             permanentemail => $emails{'permanentemail'},
 8711:                                            };
 8712:                     }
 8713:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8714:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8715:                     $srchlast =~ s/\s+$//;
 8716:                     $srchfirst =~ s/^\s+//;
 8717:                     if ($srch->{'srchtype'} eq 'exact') {
 8718:                         if (($names{'lastname'} eq $srchlast) &&
 8719:                             ($names{'firstname'} eq $srchfirst)) {
 8720:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8721:                                                 lastname => $names{'lastname'},
 8722:                                                 permanentemail => $emails{'permanentemail'},
 8723: 
 8724:                                            };
 8725:                         }
 8726:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8727:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8728:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8729:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8730:                                                 lastname => $names{'lastname'},
 8731:                                                 permanentemail => $emails{'permanentemail'},
 8732:                                                };
 8733:                         }
 8734:                     } else {
 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:                     }
 8743:                 }
 8744:             }
 8745:             ($currstate,$response,$forcenewuser) = 
 8746:                 &build_search_response($context,$srch,%srch_results); 
 8747:         } elsif ($srch->{'srchin'} eq 'alc') {
 8748:             $currstate = 'query';
 8749:         } elsif ($srch->{'srchin'} eq 'instd') {
 8750:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8751:             if ($dirsrchres eq 'ok') {
 8752:                 ($currstate,$response,$forcenewuser) = 
 8753:                     &build_search_response($context,$srch,%srch_results);
 8754:             } else {
 8755:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8756:                 $response = '<span class="LC_warning">'.
 8757:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8758:                     '</span><br />'.
 8759:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8760:                     '<br />';
 8761:             }
 8762:         }
 8763:     }
 8764:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8765: }
 8766: 
 8767: sub domdirectorysrch_check {
 8768:     my ($srch) = @_;
 8769:     my $response;
 8770:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8771:                                              ['directorysrch'],$srch->{'srchdomain'});
 8772:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8773:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8774:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8775:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8776:         }
 8777:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8778:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8779:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8780:             }
 8781:         }
 8782:     }
 8783:     return 'ok';
 8784: }
 8785: 
 8786: sub instdirectorysrch_check {
 8787:     my ($srch) = @_;
 8788:     my $can_search = 0;
 8789:     my $response;
 8790:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8791:                                              ['directorysrch'],$srch->{'srchdomain'});
 8792:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8793:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8794:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8795:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8796:         }
 8797:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8798:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8799:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8800:             }
 8801:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8802:             if (!@usertypes) {
 8803:                 push(@usertypes,'default');
 8804:             }
 8805:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8806:                 foreach my $type (@usertypes) {
 8807:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8808:                         $can_search = 1;
 8809:                         last;
 8810:                     }
 8811:                 }
 8812:             }
 8813:             if (!$can_search) {
 8814:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8815:                 my @longtypes; 
 8816:                 foreach my $item (@usertypes) {
 8817:                     if (defined($insttypes->{$item})) { 
 8818:                         push (@longtypes,$insttypes->{$item});
 8819:                     } elsif ($item eq 'default') {
 8820:                         push (@longtypes,&mt('other')); 
 8821:                     }
 8822:                 }
 8823:                 my $insttype_str = join(', ',@longtypes); 
 8824:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8825:             }
 8826:         } else {
 8827:             $can_search = 1;
 8828:         }
 8829:     } else {
 8830:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8831:     }
 8832:     my %longtext = &Apache::lonlocal::texthash (
 8833:                        uname     => 'username',
 8834:                        lastfirst => 'last name, first name',
 8835:                        lastname  => 'last name',
 8836:                        contains  => 'contains',
 8837:                        exact     => 'as exact match to',
 8838:                        begins    => 'begins with',
 8839:                    );
 8840:     if ($can_search) {
 8841:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8842:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8843:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8844:             }
 8845:         } else {
 8846:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8847:         }
 8848:     }
 8849:     if ($can_search) {
 8850:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8851:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8852:                 return 'ok';
 8853:             } else {
 8854:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8855:             }
 8856:         } else {
 8857:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8858:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8859:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 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:         }
 8865:     }
 8866: }
 8867: 
 8868: sub get_courseusers {
 8869:     my %advhash;
 8870:     my $classlist = &Apache::loncoursedata::get_classlist();
 8871:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8872:     foreach my $role (sort(keys(%coursepersonnel))) {
 8873:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8874: 	    if (!exists($classlist->{$user})) {
 8875: 		$classlist->{$user} = [];
 8876: 	    }
 8877:         }
 8878:     }
 8879:     return $classlist;
 8880: }
 8881: 
 8882: sub build_search_response {
 8883:     my ($context,$srch,%srch_results) = @_;
 8884:     my ($currstate,$response,$forcenewuser);
 8885:     my %names = (
 8886:           'uname'     => 'username',
 8887:           'lastname'  => 'last name',
 8888:           'lastfirst' => 'last name, first name',
 8889:           'crs'       => 'this course',
 8890:           'dom'       => 'LON-CAPA domain',
 8891:           'instd'     => 'the institutional directory for domain',
 8892:     );
 8893: 
 8894:     my %single = (
 8895:                    begins   => 'A match',
 8896:                    contains => 'A match',
 8897:                    exact    => 'An exact match',
 8898:                  );
 8899:     my %nomatch = (
 8900:                    begins   => 'No match',
 8901:                    contains => 'No match',
 8902:                    exact    => 'No exact match',
 8903:                   );
 8904:     if (keys(%srch_results) > 1) {
 8905:         $currstate = 'select';
 8906:     } else {
 8907:         if (keys(%srch_results) == 1) {
 8908:             if ($env{'form.action'} eq 'accesslogs') {
 8909:                 $currstate = 'activity';
 8910:             } else {
 8911:                 $currstate = 'modify';
 8912:             }
 8913:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8914:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8915:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8916:             }
 8917:         } else { # Search has nothing found. Prepare message to user.
 8918:             $response = '<span class="LC_warning">';
 8919:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8920:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8921:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8922:                                  &display_domain_info($srch->{'srchdomain'}));
 8923:             } else {
 8924:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8925:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8926:             }
 8927:             $response .= '</span>';
 8928: 
 8929:             if ($srch->{'srchin'} ne 'alc') {
 8930:                 $forcenewuser = 1;
 8931:                 my $cansrchinst = 0; 
 8932:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
 8933:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8934:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8935:                         if ($domconfig{'directorysrch'}{'available'}) {
 8936:                             $cansrchinst = 1;
 8937:                         } 
 8938:                     }
 8939:                 }
 8940:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8941:                      ($srch->{'srchby'} eq 'lastname')) &&
 8942:                     ($srch->{'srchin'} eq 'dom')) {
 8943:                     if ($cansrchinst) {
 8944:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8945:                     }
 8946:                 }
 8947:                 if ($srch->{'srchin'} eq 'crs') {
 8948:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8949:                 }
 8950:             }
 8951:             my $createdom = $env{'request.role.domain'};
 8952:             if ($context eq 'requestcrs') {
 8953:                 if ($env{'form.coursedom'} ne '') {
 8954:                     $createdom = $env{'form.coursedom'};
 8955:                 }
 8956:             }
 8957:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8958:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8959:                 my $cancreate =
 8960:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8961:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8962:                 if ($cancreate) {
 8963:                     my $showdom = &display_domain_info($createdom); 
 8964:                     $response .= '<br /><br />'
 8965:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8966:                                 .'<br />';
 8967:                     if ($context eq 'requestcrs') {
 8968:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8969:                     } else {
 8970:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8971:                     }
 8972:                     $response .='<ul><li>'
 8973:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8974:                                 .'</li><li>'
 8975:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8976:                                 .'</li><li>'
 8977:                                 .&mt('Provide the proposed username')
 8978:                                 .'</li><li>'
 8979:                                 .&mt("Click 'Search'")
 8980:                                 .'</li></ul><br />';
 8981:                 } else {
 8982:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8983:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8984:                         $response .= '<br /><br />';
 8985:                         if ($context eq 'requestcrs') {
 8986:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8987:                         } else {
 8988:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 8989:                         }
 8990:                         $response .= '<br />'
 8991:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 8992:                                         ,' <a'.$helplink.'>'
 8993:                                         ,'</a>')
 8994:                                      .'<br />';
 8995:                     }
 8996:                 }
 8997:             }
 8998:         }
 8999:     }
 9000:     return ($currstate,$response,$forcenewuser);
 9001: }
 9002: 
 9003: sub display_domain_info {
 9004:     my ($dom) = @_;
 9005:     my $output = $dom;
 9006:     if ($dom ne '') { 
 9007:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 9008:         if ($domdesc ne '') {
 9009:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 9010:         }
 9011:     }
 9012:     return $output;
 9013: }
 9014: 
 9015: sub crumb_utilities {
 9016:     my %elements = (
 9017:        crtuser => {
 9018:            srchterm => 'text',
 9019:            srchin => 'selectbox',
 9020:            srchby => 'selectbox',
 9021:            srchtype => 'selectbox',
 9022:            srchdomain => 'selectbox',
 9023:        },
 9024:        crtusername => {
 9025:            srchterm => 'text',
 9026:            srchdomain => 'selectbox',
 9027:        },
 9028:        docustom => {
 9029:            rolename => 'selectbox',
 9030:            newrolename => 'textbox',
 9031:        },
 9032:        studentform => {
 9033:            srchterm => 'text',
 9034:            srchin => 'selectbox',
 9035:            srchby => 'selectbox',
 9036:            srchtype => 'selectbox',
 9037:            srchdomain => 'selectbox',
 9038:        },
 9039:     );
 9040: 
 9041:     my $jsback .= qq|
 9042: function backPage(formname,prevphase,prevstate) {
 9043:     if (typeof prevphase == 'undefined') {
 9044:         formname.phase.value = '';
 9045:     }
 9046:     else {  
 9047:         formname.phase.value = prevphase;
 9048:     }
 9049:     if (typeof prevstate == 'undefined') {
 9050:         formname.currstate.value = '';
 9051:     }
 9052:     else {
 9053:         formname.currstate.value = prevstate;
 9054:     }
 9055:     formname.submit();
 9056: }
 9057: |;
 9058:     return ($jsback,\%elements);
 9059: }
 9060: 
 9061: sub course_level_table {
 9062:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 9063:     return unless (ref($inccourses) eq 'HASH');
 9064:     my $table = '';
 9065: # Custom Roles?
 9066: 
 9067:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9068:     my %lt=&Apache::lonlocal::texthash(
 9069:             'exs'  => "Existing sections",
 9070:             'new'  => "Define new section",
 9071:             'ssd'  => "Set Start Date",
 9072:             'sed'  => "Set End Date",
 9073:             'crl'  => "Course Level",
 9074:             'act'  => "Activate",
 9075:             'rol'  => "Role",
 9076:             'ext'  => "Extent",
 9077:             'grs'  => "Section",
 9078:             'crd'  => "Credits",
 9079:             'sta'  => "Start",
 9080:             'end'  => "End"
 9081:     );
 9082: 
 9083:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 9084: 	my $thiscourse=$protectedcourse;
 9085: 	$thiscourse=~s:_:/:g;
 9086: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 9087:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 9088: 	my $area=$coursedata{'description'};
 9089:         my $crstype=$coursedata{'type'};
 9090: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 9091: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 9092:         my %sections_count;
 9093:         if (defined($env{'request.course.id'})) {
 9094:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 9095:                 %sections_count = 
 9096: 		    &Apache::loncommon::get_sections($domain,$cnum);
 9097:             }
 9098:         }
 9099:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 9100: 	foreach my $role (@roles) {
 9101:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 9102: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 9103:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 9104:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9105:                                             $plrole,\%sections_count,\%lt,
 9106:                                             $showcredits,$defaultcredits,$crstype);
 9107:             } elsif ($env{'request.course.sec'} ne '') {
 9108:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 9109:                                              $env{'request.course.sec'})) {
 9110:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9111:                                                 $plrole,\%sections_count,\%lt,
 9112:                                                 $showcredits,$defaultcredits,$crstype);
 9113:                 }
 9114:             }
 9115:         }
 9116:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 9117:             foreach my $cust (sort(keys(%customroles))) {
 9118:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 9119:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 9120:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9121:                                             $cust,\%sections_count,\%lt,
 9122:                                             $showcredits,$defaultcredits,$crstype);
 9123:             }
 9124: 	}
 9125:     }
 9126:     return '' if ($table eq ''); # return nothing if there is nothing 
 9127:                                  # in the table
 9128:     my $result;
 9129:     if (!$env{'request.course.id'}) {
 9130:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 9131:     }
 9132:     $result .= 
 9133: &Apache::loncommon::start_data_table().
 9134: &Apache::loncommon::start_data_table_header_row().
 9135: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9136: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 9137:     if ($showcredits) {
 9138:         $result .= $lt{'crd'}.'</th>';
 9139:     }
 9140:     $result .=
 9141: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 9142: '<th>'.$lt{'end'}.'</th>'.
 9143: &Apache::loncommon::end_data_table_header_row().
 9144: $table.
 9145: &Apache::loncommon::end_data_table();
 9146:     return $result;
 9147: }
 9148: 
 9149: sub course_level_row {
 9150:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 9151:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 9152:     my $creditem;
 9153:     my $row = &Apache::loncommon::start_data_table_row().
 9154:               ' <td><input type="checkbox" name="act_'.
 9155:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 9156:               ' <td>'.$plrole.'</td>'."\n".
 9157:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 9158:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 9159:         $row .= 
 9160:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 9161:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 9162:     } else {
 9163:         $row .= '<td>&nbsp;</td>';
 9164:     }
 9165:     if (($role eq 'cc') || ($role eq 'co')) {
 9166:         $row .= '<td>&nbsp;</td>';
 9167:     } elsif ($env{'request.course.sec'} ne '') {
 9168:         $row .= ' <td><input type="hidden" value="'.
 9169:                 $env{'request.course.sec'}.'" '.
 9170:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 9171:                 $env{'request.course.sec'}.'</td>';
 9172:     } else {
 9173:         if (ref($sections_count) eq 'HASH') {
 9174:             my $currsec = 
 9175:                 &Apache::lonuserutils::course_sections($sections_count,
 9176:                                                        $protectedcourse.'_'.$role);
 9177:             $row .= '<td><table class="LC_createuser">'."\n".
 9178:                     '<tr class="LC_section_row">'."\n".
 9179:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 9180:                        $currsec.'</td>'."\n".
 9181:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 9182:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 9183:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 9184:                      '" value="" />'.
 9185:                      '<input type="hidden" '.
 9186:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 9187:                      '</tr></table></td>'."\n";
 9188:         } else {
 9189:             $row .= '<td><input type="text" size="10" '.
 9190:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 9191:         }
 9192:     }
 9193:     $row .= <<ENDTIMEENTRY;
 9194: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 9195: <a href=
 9196: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 9197: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 9198: <a href=
 9199: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 9200: ENDTIMEENTRY
 9201:     $row .= &Apache::loncommon::end_data_table_row();
 9202:     return $row;
 9203: }
 9204: 
 9205: sub course_level_dc {
 9206:     my ($dcdom,$showcredits) = @_;
 9207:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9208:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 9209:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 9210:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 9211:                       '<input type="hidden" name="dccourse" value="" />';
 9212:     my $courseform=&Apache::loncommon::selectcourse_link
 9213:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 9214:     my $credit_elem;
 9215:     if ($showcredits) {
 9216:         $credit_elem = 'credits';
 9217:     }
 9218:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 9219:     my %lt=&Apache::lonlocal::texthash(
 9220:                     'rol'  => "Role",
 9221:                     'grs'  => "Section",
 9222:                     'exs'  => "Existing sections",
 9223:                     'new'  => "Define new section", 
 9224:                     'sta'  => "Start",
 9225:                     'end'  => "End",
 9226:                     'ssd'  => "Set Start Date",
 9227:                     'sed'  => "Set End Date",
 9228:                     'scc'  => "Course/Community",
 9229:                     'crd'  => "Credits",
 9230:                   );
 9231:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 9232:                  &Apache::loncommon::start_data_table().
 9233:                  &Apache::loncommon::start_data_table_header_row().
 9234:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9235:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 9236:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 9237:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 9238:                  &Apache::loncommon::end_data_table_header_row();
 9239:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 9240:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 9241:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 9242:                      '<td valign="top"><br /><select name="role">'."\n";
 9243:     foreach my $role (@roles) {
 9244:         my $plrole=&Apache::lonnet::plaintext($role);
 9245:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 9246:     }
 9247:     if ( keys(%customroles) > 0) {
 9248:         foreach my $cust (sort(keys(%customroles))) {
 9249:             my $custrole='cr_cr_'.$env{'user.domain'}.
 9250:                     '_'.$env{'user.name'}.'_'.$cust;
 9251:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 9252:         }
 9253:     }
 9254:     $otheritems .= '</select></td><td>'.
 9255:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 9256:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 9257:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 9258:                      '<td>&nbsp;&nbsp;</td>'.
 9259:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 9260:                      '<input type="text" name="newsec" value="" />'.
 9261:                      '<input type="hidden" name="section" value="" />'.
 9262:                      '<input type="hidden" name="groups" value="" />'.
 9263:                      '<input type="hidden" name="crstype" value="" /></td>'.
 9264:                      '</tr></table></td>'."\n";
 9265:     if ($showcredits) {
 9266:         $otheritems .= '<td><br />'."\n".
 9267:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 9268:     }
 9269:     $otheritems .= <<ENDTIMEENTRY;
 9270: <td><br /><input type="hidden" name="start" value='' />
 9271: <a href=
 9272: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 9273: <td><br /><input type="hidden" name="end" value='' />
 9274: <a href=
 9275: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 9276: ENDTIMEENTRY
 9277:     $otheritems .= &Apache::loncommon::end_data_table_row().
 9278:                    &Apache::loncommon::end_data_table()."\n";
 9279:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 9280: }
 9281: 
 9282: sub update_selfenroll_config {
 9283:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 9284:     return unless (ref($currsettings) eq 'HASH');
 9285:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 9286:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9287:     my (%changes,%warning);
 9288:     my $curr_types;
 9289:     my %noedit;
 9290:     unless ($context eq 'domain') {
 9291:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 9292:     }
 9293:     if (ref($row) eq 'ARRAY') {
 9294:         foreach my $item (@{$row}) {
 9295:             next if ($noedit{$item});
 9296:             if ($item eq 'enroll_dates') {
 9297:                 my (%currenrolldate,%newenrolldate);
 9298:                 foreach my $type ('start','end') {
 9299:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 9300:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 9301:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 9302:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 9303:                     }
 9304:                 }
 9305:             } elsif ($item eq 'access_dates') {
 9306:                 my (%currdate,%newdate);
 9307:                 foreach my $type ('start','end') {
 9308:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 9309:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 9310:                     if ($newdate{$type} ne $currdate{$type}) {
 9311:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 9312:                     }
 9313:                 }
 9314:             } elsif ($item eq 'types') {
 9315:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 9316:                 if ($env{'form.selfenroll_all'}) {
 9317:                     if ($curr_types ne '*') {
 9318:                         $changes{'internal.selfenroll_types'} = '*';
 9319:                     } else {
 9320:                         next;
 9321:                     }
 9322:                 } else {
 9323:                     my %currdoms;
 9324:                     my @entries = split(/;/,$curr_types);
 9325:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 9326:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 9327:                     my $newnum = 0;
 9328:                     my @latesttypes;
 9329:                     foreach my $num (@activations) {
 9330:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 9331:                         if (@types > 0) {
 9332:                             @types = sort(@types);
 9333:                             my $typestr = join(',',@types);
 9334:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 9335:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9336:                             $currdoms{$typedom} = 1;
 9337:                             $newnum ++;
 9338:                         }
 9339:                     }
 9340:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 9341:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 9342:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 9343:                             if (@types > 0) {
 9344:                                 @types = sort(@types);
 9345:                                 my $typestr = join(',',@types);
 9346:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 9347:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 9348:                                 $currdoms{$typedom} = 1;
 9349:                                 $newnum ++;
 9350:                             }
 9351:                         }
 9352:                     }
 9353:                     if ($env{'form.selfenroll_newdom'} ne '') {
 9354:                         my $typedom = $env{'form.selfenroll_newdom'};
 9355:                         if ((!defined($currdoms{$typedom})) && 
 9356:                             (&Apache::lonnet::domain($typedom) ne '')) {
 9357:                             my $typestr;
 9358:                             my ($othertitle,$usertypes,$types) = 
 9359:                                 &Apache::loncommon::sorted_inst_types($typedom);
 9360:                             my $othervalue = 'any';
 9361:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 9362:                                 if (@{$types} > 0) {
 9363:                                     my @esc_types = map { &escape($_); } @{$types};
 9364:                                     $othervalue = 'other';
 9365:                                     $typestr = join(',',(@esc_types,$othervalue));
 9366:                                 }
 9367:                                 $typestr = $othervalue;
 9368:                             } else {
 9369:                                 $typestr = $othervalue;
 9370:                             } 
 9371:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9372:                             $newnum ++ ;
 9373:                         }
 9374:                     }
 9375:                     my $selfenroll_types = join(';',@latesttypes);
 9376:                     if ($selfenroll_types ne $curr_types) {
 9377:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9378:                     }
 9379:                 }
 9380:             } elsif ($item eq 'limit') {
 9381:                 my $newlimit = $env{'form.selfenroll_limit'};
 9382:                 my $newcap = $env{'form.selfenroll_cap'};
 9383:                 $newcap =~s/\s+//g;
 9384:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9385:                 $currlimit = 'none' if ($currlimit eq '');
 9386:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9387:                 if ($newlimit ne $currlimit) {
 9388:                     if ($newlimit ne 'none') {
 9389:                         if ($newcap =~ /^\d+$/) {
 9390:                             if ($newcap ne $currcap) {
 9391:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9392:                             }
 9393:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9394:                         } else {
 9395:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9396:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9397:                         }
 9398:                     } elsif ($currcap ne '') {
 9399:                         $changes{'internal.selfenroll_cap'} = '';
 9400:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9401:                     }
 9402:                 } elsif ($currlimit ne 'none') {
 9403:                     if ($newcap =~ /^\d+$/) {
 9404:                         if ($newcap ne $currcap) {
 9405:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9406:                         }
 9407:                     } else {
 9408:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9409:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9410:                     }
 9411:                 }
 9412:             } elsif ($item eq 'approval') {
 9413:                 my (@currnotified,@newnotified);
 9414:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9415:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9416:                 if ($currnotifylist ne '') {
 9417:                     @currnotified = split(/,/,$currnotifylist);
 9418:                     @currnotified = sort(@currnotified);
 9419:                 }
 9420:                 my $newapproval = $env{'form.selfenroll_approval'};
 9421:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9422:                 @newnotified = sort(@newnotified);
 9423:                 if ($newapproval ne $currapproval) {
 9424:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9425:                     if (!$newapproval) {
 9426:                         if ($currnotifylist ne '') {
 9427:                             $changes{'internal.selfenroll_notifylist'} = '';
 9428:                         }
 9429:                     } else {
 9430:                         my @differences =  
 9431:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9432:                         if (@differences > 0) {
 9433:                             if (@newnotified > 0) {
 9434:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9435:                             } else {
 9436:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9437:                             }
 9438:                         }
 9439:                     }
 9440:                 } else {
 9441:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9442:                     if (@differences > 0) {
 9443:                         if (@newnotified > 0) {
 9444:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9445:                         } else {
 9446:                             $changes{'internal.selfenroll_notifylist'} = '';
 9447:                         }
 9448:                     }
 9449:                 }
 9450:             } else {
 9451:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9452:                 my $newval = $env{'form.selfenroll_'.$item};
 9453:                 if ($item eq 'section') {
 9454:                     $newval = $env{'form.sections'};
 9455:                     if (defined($curr_groups{$newval})) {
 9456:                         $newval = $curr_val;
 9457:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9458:                                           &mt('Group names and section names must be distinct');
 9459:                     } elsif ($newval eq 'all') {
 9460:                         $newval = $curr_val;
 9461:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9462:                     }
 9463:                     if ($newval eq '') {
 9464:                         $newval = 'none';
 9465:                     }
 9466:                 }
 9467:                 if ($newval ne $curr_val) {
 9468:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9469:                 }
 9470:             }
 9471:         }
 9472:         if (keys(%warning) > 0) {
 9473:             foreach my $item (@{$row}) {
 9474:                 if (exists($warning{$item})) {
 9475:                     $r->print($warning{$item}.'<br />');
 9476:                 }
 9477:             } 
 9478:         }
 9479:         if (keys(%changes) > 0) {
 9480:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9481:             if ($putresult eq 'ok') {
 9482:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9483:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9484:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9485:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9486:                                                                 $cnum,undef,undef,'Course');
 9487:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9488:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9489:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9490:                             if (exists($changes{'internal.'.$item})) {
 9491:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9492:                             }
 9493:                         }
 9494:                         my $crsputresult =
 9495:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9496:                                                          $chome,'notime');
 9497:                     }
 9498:                 }
 9499:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9500:                 foreach my $item (@{$row}) {
 9501:                     my $title = $item;
 9502:                     if (ref($lt) eq 'HASH') {
 9503:                         $title = $lt->{$item};
 9504:                     }
 9505:                     if ($item eq 'enroll_dates') {
 9506:                         foreach my $type ('start','end') {
 9507:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9508:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9509:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9510:                                           $title,$type,$newdate).'</li>');
 9511:                             }
 9512:                         }
 9513:                     } elsif ($item eq 'access_dates') {
 9514:                         foreach my $type ('start','end') {
 9515:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9516:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9517:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9518:                                           $title,$type,$newdate).'</li>');
 9519:                             }
 9520:                         }
 9521:                     } elsif ($item eq 'limit') {
 9522:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9523:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9524:                             my ($newval,$newcap);
 9525:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9526:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9527:                             } else {
 9528:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9529:                             }
 9530:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9531:                                 $newval = &mt('No limit');
 9532:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9533:                                      'allstudents') {
 9534:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9535:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9536:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9537:                             } else {
 9538:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9539:                                 if ($currlimit eq 'allstudents') {
 9540:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9541:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9542:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9543:                                 }
 9544:                             }
 9545:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9546:                         }
 9547:                     } elsif ($item eq 'approval') {
 9548:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9549:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9550:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9551:                             my ($newval,$newnotify);
 9552:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9553:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9554:                             } else {   
 9555:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9556:                             }
 9557:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9558:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9559:                                     $changes{'internal.selfenroll_approval'} = '0';
 9560:                                 }
 9561:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9562:                             } else {
 9563:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9564:                                 if ($currapproval !~ /^[012]$/) {
 9565:                                     $currapproval = 0;
 9566:                                 }
 9567:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9568:                             }
 9569:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9570:                             if ($newnotify) {
 9571:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9572:                             } else {
 9573:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9574:                             }
 9575:                             $r->print('</li>'."\n");
 9576:                         }
 9577:                     } else {
 9578:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9579:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9580:                             if ($item eq 'types') {
 9581:                                 if ($newval eq '') {
 9582:                                     $newval = &mt('None');
 9583:                                 } elsif ($newval eq '*') {
 9584:                                     $newval = &mt('Any user in any domain');
 9585:                                 }
 9586:                             } elsif ($item eq 'registered') {
 9587:                                 if ($newval eq '1') {
 9588:                                     $newval = &mt('Yes');
 9589:                                 } elsif ($newval eq '0') {
 9590:                                     $newval = &mt('No');
 9591:                                 }
 9592:                             }
 9593:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9594:                         }
 9595:                     }
 9596:                 }
 9597:                 $r->print('</ul>');
 9598:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9599:                     my %newenvhash;
 9600:                     foreach my $key (keys(%changes)) {
 9601:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9602:                     }
 9603:                     &Apache::lonnet::appenv(\%newenvhash);
 9604:                 }
 9605:             } else {
 9606:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9607:                           &mt('The error was: [_1].',$putresult));
 9608:             }
 9609:         } else {
 9610:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9611:         }
 9612:     } else {
 9613:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9614:     }
 9615:     my $visactions = &cat_visibility();
 9616:     my ($cathash,%cattype);
 9617:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9618:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9619:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9620:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9621:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9622:     } else {
 9623:         $cathash = {};
 9624:         $cattype{'auth'} = 'std';
 9625:         $cattype{'unauth'} = 'std';
 9626:     }
 9627:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9628:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9629:                   '<br />'.
 9630:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9631:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9632:                   '</ul>');
 9633:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9634:         if ($currsettings->{'uniquecode'}) {
 9635:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9636:         } else {
 9637:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9638:                   '<br />'.
 9639:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9640:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9641:                   '</ul><br />');
 9642:         }
 9643:     } else {
 9644:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9645:         if (ref($visactions) eq 'HASH') {
 9646:             if (!$visible) {
 9647:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9648:                           '<br />');
 9649:                 if (ref($vismsgs) eq 'ARRAY') {
 9650:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9651:                     foreach my $item (@{$vismsgs}) {
 9652:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9653:                     }
 9654:                     $r->print('</ul>');
 9655:                 }
 9656:                 $r->print($cansetvis);
 9657:             }
 9658:         }
 9659:     } 
 9660:     return;
 9661: }
 9662: 
 9663: #---------------------------------------------- end functions for &phase_two
 9664: 
 9665: #--------------------------------- functions for &phase_two and &phase_three
 9666: 
 9667: #--------------------------end of functions for &phase_two and &phase_three
 9668: 
 9669: 1;
 9670: __END__
 9671: 
 9672: 

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