File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.450: download - view: text, annotated - select for diffs
Sat Dec 8 18:30:15 2018 UTC (5 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Trust settings.

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.450 2018/12/08 18:30:15 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);
 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) = @_;
 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 (&Apache::lonnet::allowed('udp',$ccdomain)) {
 2275:                 # Current user has rights to view domain preferences for user's domain
 2276:                 my $result;
 2277:                 if ($currentauth =~ /^krb(4|5):([^:]*)$/) {
 2278:                     my ($krbver,$krbrealm) = ($1,$2);
 2279:                     if ($krbrealm eq '') {
 2280:                         $result = &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2281:                     } else {
 2282:                         $result = &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2283:                                       $krbrealm,$krbver);
 2284:                     }
 2285:                 } elsif ($currentauth =~ /^internal:/) {
 2286:                     $result = &mt('Currently internally authenticated.');
 2287:                 } elsif ($currentauth =~ /^localauth:/) {
 2288:                     $result = &mt('Currently using local (institutional) authentication.');
 2289:                 } elsif ($currentauth =~ /^unix:/) {
 2290:                     $result = &mt('Currently Filesystem Authenticated.');
 2291:                 } elsif ($currentauth =~ /^lti:/) {
 2292:                     $result = &mt('Currently LTi authenticated.');
 2293:                 }
 2294:                 $outcome = '<h3>'.$lt{'ld'}.'</h3>'.
 2295:                            &Apache::loncommon::start_data_table().
 2296:                            &Apache::loncommon::start_data_table_row().
 2297:                            '<td>'.$result.'</td>'.
 2298:                            &Apache::loncommon::end_data_table_row()."\n".
 2299:                            &Apache::loncommon::end_data_table();
 2300:             } elsif (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 2301:                 my %lt=&Apache::lonlocal::texthash(
 2302:                            'ccld'  => "Change Current Login Data",
 2303:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 2304:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 2305:                 );
 2306:                 $outcome .= <<ENDNOPRIV;
 2307: <h3>$lt{'ccld'}</h3>
 2308: $lt{'yodo'} $lt{'ifch'}: $ccdomain
 2309: <input type="hidden" name="login" value="nochange" />
 2310: ENDNOPRIV
 2311:             }
 2312:         }
 2313:     }  ## End of "check for bad authentication type" logic
 2314:     return $outcome;
 2315: }
 2316: 
 2317: sub modify_login_block {
 2318:     my ($dom,$currentauth) = @_;
 2319:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2320:     my ($authnum,%can_assign) =
 2321:         &Apache::loncommon::get_assignable_auth($dom);
 2322:     my ($authformcurrent,@authform_others,$show_override_msg);
 2323:     if ($currentauth=~/^krb(4|5):/) {
 2324:         $authformcurrent=$authformkrb;
 2325:         if ($can_assign{'int'}) {
 2326:             push(@authform_others,$authformint);
 2327:         }
 2328:         if ($can_assign{'loc'}) {
 2329:             push(@authform_others,$authformloc);
 2330:         }
 2331:         if ($can_assign{'lti'}) {
 2332:             push(@authform_others,$authformlti);
 2333:         }
 2334:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2335:             $show_override_msg = 1;
 2336:         }
 2337:     } elsif ($currentauth=~/^internal:/) {
 2338:         $authformcurrent=$authformint;
 2339:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2340:             push(@authform_others,$authformkrb);
 2341:         }
 2342:         if ($can_assign{'loc'}) {
 2343:             push(@authform_others,$authformloc);
 2344:         }
 2345:         if ($can_assign{'lti'}) {
 2346:             push(@authform_others,$authformlti);
 2347:         }
 2348:         if ($can_assign{'int'}) {
 2349:             $show_override_msg = 1;
 2350:         }
 2351:     } elsif ($currentauth=~/^unix:/) {
 2352:         $authformcurrent=$authformfsys;
 2353:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2354:             push(@authform_others,$authformkrb);
 2355:         }
 2356:         if ($can_assign{'int'}) {
 2357:             push(@authform_others,$authformint);
 2358:         }
 2359:         if ($can_assign{'loc'}) {
 2360:             push(@authform_others,$authformloc);
 2361:         }
 2362:         if ($can_assign{'lti'}) {
 2363:             push(@authform_others,$authformlti);
 2364:         }
 2365:         if ($can_assign{'fsys'}) {
 2366:             $show_override_msg = 1;
 2367:         }
 2368:     } elsif ($currentauth=~/^localauth:/) {
 2369:         $authformcurrent=$authformloc;
 2370:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2371:             push(@authform_others,$authformkrb);
 2372:         }
 2373:         if ($can_assign{'int'}) {
 2374:             push(@authform_others,$authformint);
 2375:         }
 2376:         if ($can_assign{'lti'}) {
 2377:             push(@authform_others,$authformlti);
 2378:         }
 2379:         if ($can_assign{'loc'}) {
 2380:             $show_override_msg = 1;
 2381:         }
 2382:     } elsif ($currentauth=~/^lti:/) {
 2383:         $authformcurrent=$authformlti;
 2384:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
 2385:             push(@authform_others,$authformkrb);
 2386:         }
 2387:         if ($can_assign{'int'}) {
 2388:             push(@authform_others,$authformint);
 2389:         }
 2390:         if ($can_assign{'loc'}) {
 2391:             push(@authform_others,$authformloc);
 2392:         }
 2393:     }
 2394:     if ($show_override_msg) {
 2395:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
 2396:                            '</td></tr>'."\n".
 2397:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
 2398:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
 2399:                            '<td align="right"><span class="LC_cusr_emph">'.
 2400:                             &mt('will override current values').
 2401:                             '</span></td></tr></table>';
 2402:     }
 2403:     return ($authformcurrent,$show_override_msg,@authform_others); 
 2404: }
 2405: 
 2406: sub personal_data_display {
 2407:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray,
 2408:         $now,$captchaform,$emailusername,$usertype,$usernameset,$condition,$excluded) = @_;
 2409:     my ($output,%userenv,%canmodify,%canmodify_status);
 2410:     my @userinfo = ('firstname','middlename','lastname','generation',
 2411:                     'permanentemail','id');
 2412:     my $rowcount = 0;
 2413:     my $editable = 0;
 2414:     my %textboxsize = (
 2415:                        firstname      => '15',
 2416:                        middlename     => '15',
 2417:                        lastname       => '15',
 2418:                        generation     => '5',
 2419:                        permanentemail => '25',
 2420:                        id             => '15',
 2421:                       );
 2422: 
 2423:     my %lt=&Apache::lonlocal::texthash(
 2424:                 'pd'             => "Personal Data",
 2425:                 'firstname'      => "First Name",
 2426:                 'middlename'     => "Middle Name",
 2427:                 'lastname'       => "Last Name",
 2428:                 'generation'     => "Generation",
 2429:                 'permanentemail' => "Permanent e-mail address",
 2430:                 'id'             => "Student/Employee ID",
 2431:                 'lg'             => "Login Data",
 2432:                 'inststatus'     => "Affiliation",
 2433:                 'email'          => 'E-mail address',
 2434:                 'valid'          => 'Validation',
 2435:                 'username'       => 'Username',
 2436:     );
 2437: 
 2438:     %canmodify_status =
 2439:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2440:                                                    ['inststatus'],$rolesarray);
 2441:     if (!$newuser) {
 2442:         # Get the users information
 2443:         %userenv = &Apache::lonnet::get('environment',
 2444:                    ['firstname','middlename','lastname','generation',
 2445:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
 2446:         %canmodify =
 2447:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
 2448:                                                        \@userinfo,$rolesarray);
 2449:     } elsif ($context eq 'selfcreate') {
 2450:         if ($newuser eq 'email') {
 2451:             if (ref($emailusername) eq 'HASH') {
 2452:                 if (ref($emailusername->{$usertype}) eq 'HASH') {
 2453:                     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 2454:                     @userinfo = ();
 2455:                     if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 2456:                         foreach my $field (@{$infofields}) { 
 2457:                             if ($emailusername->{$usertype}->{$field}) {
 2458:                                 push(@userinfo,$field);
 2459:                                 $canmodify{$field} = 1;
 2460:                                 unless ($textboxsize{$field}) {
 2461:                                     $textboxsize{$field} = 25;
 2462:                                 }
 2463:                                 unless ($lt{$field}) {
 2464:                                     $lt{$field} = $infotitles->{$field};
 2465:                                 }
 2466:                                 if ($emailusername->{$usertype}->{$field} eq 'required') {
 2467:                                     $lt{$field} .= '<b>*</b>';
 2468:                                 }
 2469:                             }
 2470:                         }
 2471:                     }
 2472:                 }
 2473:             }
 2474:         } else {
 2475:             %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
 2476:                                                $inst_results,$rolesarray);
 2477:         }
 2478:     }
 2479: 
 2480:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
 2481:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
 2482:               &Apache::lonhtmlcommon::start_pick_box();
 2483:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2484:         my $size = 25;
 2485:         if ($condition) {
 2486:             if ($condition =~ /^\@[^\@]+$/) {
 2487:                 $size = 10;
 2488:             } else {
 2489:                 undef($condition);
 2490:             }
 2491:         } 
 2492:         if ($excluded) {
 2493:             unless ($excluded =~ /^\@[^\@]+$/) {
 2494:                 undef($condition);
 2495:             }
 2496:         }
 2497:         $output .= &Apache::lonhtmlcommon::row_title($lt{'email'}.'<b>*</b>',undef,
 2498:                                                      'LC_oddrow_value')."\n".
 2499:                    '<input type="text" name="uname" size="'.$size.'" value="" autocomplete="off" />';
 2500:         if ($condition) {
 2501:             $output .= $condition;
 2502:         } elsif ($excluded) {
 2503:             $output .= '<br /><span style="font-size: smaller">'.&mt('You must use an e-mail address that does not end with [_1]',
 2504:                                                                      $excluded).'</span>';
 2505:         }
 2506:         if ($usernameset eq 'first') {
 2507:             $output .= '<br /><span style="font-size: smaller">';
 2508:             if ($condition) {
 2509:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before [_1]',
 2510:                                       $condition);
 2511:             } else {
 2512:                 $output .= &mt('Your username in LON-CAPA will be the part of your e-mail address before the @');
 2513:             }
 2514:             $output .= '</span>';
 2515:         }
 2516:         $rowcount ++;
 2517:         $output .= &Apache::lonhtmlcommon::row_closure(1);
 2518:         my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
 2519:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
 2520:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
 2521:                                                     'LC_pick_box_title',
 2522:                                                     'LC_oddrow_value')."\n".
 2523:                    $upassone."\n".
 2524:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
 2525:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password').'<b>*</b>',
 2526:                                                      'LC_pick_box_title',
 2527:                                                      'LC_oddrow_value')."\n".
 2528:                    $upasstwo.
 2529:                    &Apache::lonhtmlcommon::row_closure()."\n";
 2530:         if ($usernameset eq 'free') {
 2531:             my $onclick = "toggleUsernameDisp(this,'selfcreateusername');"; 
 2532:             $output .= &Apache::lonhtmlcommon::row_title($lt{'username'},undef,'LC_oddrow_value')."\n".
 2533:                        &mt('Use e-mail address: ').
 2534:                        '<label><input type="radio" name="emailused" value="1" checked="checked" onclick="'.$onclick.'" />'.&mt('Yes').'</label>'."\n".
 2535:                        ('&nbsp;'x2).
 2536:                        '<label><input type="radio" name="emailused" value="0" onclick="'.$onclick.'" />'.&mt('No').'</label>'."\n".
 2537:                        '<div id="selfcreateusername" style="display: none; font-size: smaller">'.
 2538:                        '<br /><span class="LC_nobreak">'.&mt('Preferred username').
 2539:                        '&nbsp;<input type="text" name="username" value="" size="20" autocomplete="off"/>'.
 2540:                        '</span></div>'."\n".&Apache::lonhtmlcommon::row_closure(1);
 2541:             $rowcount ++;
 2542:         }
 2543:     }
 2544:     foreach my $item (@userinfo) {
 2545:         my $rowtitle = $lt{$item};
 2546:         my $hiderow = 0;
 2547:         if ($item eq 'generation') {
 2548:             $rowtitle = $genhelp.$rowtitle;
 2549:         }
 2550:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
 2551:         if ($newuser) {
 2552:             if (ref($inst_results) eq 'HASH') {
 2553:                 if ($inst_results->{$item} ne '') {
 2554:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
 2555:                 } else {
 2556:                     if ($context eq 'selfcreate') {
 2557:                         if ($canmodify{$item}) {
 2558:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2559:                             $editable ++;
 2560:                         } else {
 2561:                             $hiderow = 1;
 2562:                         }
 2563:                     } else {
 2564:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2565:                     }
 2566:                 }
 2567:             } else {
 2568:                 if ($context eq 'selfcreate') {
 2569:                     if ($canmodify{$item}) {
 2570:                         if ($newuser eq 'email') {
 2571:                             $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2572:                         } else {
 2573:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
 2574:                         }
 2575:                         $editable ++;
 2576:                     } else {
 2577:                         $hiderow = 1;
 2578:                     }
 2579:                 } else {
 2580:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
 2581:                 }
 2582:             }
 2583:         } else {
 2584:             if ($canmodify{$item}) {
 2585:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
 2586:                 if (($item eq 'id') && (!$newuser)) {
 2587:                     $row .= '<br />'.&Apache::lonuserutils::forceid_change($context);
 2588:                 }
 2589:             } else {
 2590:                 $row .= $userenv{$item};
 2591:             }
 2592:         }
 2593:         $row .= &Apache::lonhtmlcommon::row_closure(1);
 2594:         if (!$hiderow) {
 2595:             $output .= $row;
 2596:             $rowcount ++;
 2597:         }
 2598:     }
 2599:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
 2600:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
 2601:         if (ref($types) eq 'ARRAY') {
 2602:             if (@{$types} > 0) {
 2603:                 my ($hiderow,$shown);
 2604:                 if ($canmodify_status{'inststatus'}) {
 2605:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
 2606:                 } else {
 2607:                     if ($userenv{'inststatus'} eq '') {
 2608:                         $hiderow = 1;
 2609:                     } else {
 2610:                         my @showitems;
 2611:                         foreach my $item ( map { &unescape($_); } split(':',$userenv{'inststatus'})) {
 2612:                             if (exists($usertypes->{$item})) {
 2613:                                 push(@showitems,$usertypes->{$item});
 2614:                             } else {
 2615:                                 push(@showitems,$item);
 2616:                             }
 2617:                         }
 2618:                         if (@showitems) {
 2619:                             $shown = join(', ',@showitems);
 2620:                         } else {
 2621:                             $hiderow = 1;
 2622:                         }
 2623:                     }
 2624:                 }
 2625:                 if (!$hiderow) {
 2626:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affiliations'),undef,'LC_oddrow_value')."\n".
 2627:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
 2628:                     if ($context eq 'selfcreate') {
 2629:                         $rowcount ++;
 2630:                     }
 2631:                     $output .= $row;
 2632:                 }
 2633:             }
 2634:         }
 2635:     }
 2636:     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
 2637:         if ($captchaform) {
 2638:             $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
 2639:                                                          'LC_pick_box_title')."\n".
 2640:                        $captchaform."\n".'<br /><br />'.
 2641:                        &Apache::lonhtmlcommon::row_closure(1); 
 2642:             $rowcount ++;
 2643:         }
 2644:         my $submit_text = &mt('Create account');
 2645:         $output .= &Apache::lonhtmlcommon::row_title()."\n".
 2646:                    '<br /><input type="submit" name="createaccount" value="'.
 2647:                    $submit_text.'" />'.
 2648:                    '<input type="hidden" name="type" value="'.$usertype.'" />'.
 2649:                    &Apache::lonhtmlcommon::row_closure(1);
 2650:     }
 2651:     $output .= &Apache::lonhtmlcommon::end_pick_box();
 2652:     if (wantarray) {
 2653:         if ($context eq 'selfcreate') {
 2654:             return($output,$rowcount,$editable);
 2655:         } else {
 2656:             return $output;
 2657:         }
 2658:     } else {
 2659:         return $output;
 2660:     }
 2661: }
 2662: 
 2663: sub pick_inst_statuses {
 2664:     my ($curr,$usertypes,$types) = @_;
 2665:     my ($output,$rem,@currtypes);
 2666:     if ($curr ne '') {
 2667:         @currtypes = map { &unescape($_); } split(/:/,$curr);
 2668:     }
 2669:     my $numinrow = 2;
 2670:     if (ref($types) eq 'ARRAY') {
 2671:         $output = '<table>';
 2672:         my $lastcolspan; 
 2673:         for (my $i=0; $i<@{$types}; $i++) {
 2674:             if (defined($usertypes->{$types->[$i]})) {
 2675:                 my $rem = $i%($numinrow);
 2676:                 if ($rem == 0) {
 2677:                     if ($i<@{$types}-1) {
 2678:                         if ($i > 0) { 
 2679:                             $output .= '</tr>';
 2680:                         }
 2681:                         $output .= '<tr>';
 2682:                     }
 2683:                 } elsif ($i==@{$types}-1) {
 2684:                     my $colsleft = $numinrow - $rem;
 2685:                     if ($colsleft > 1) {
 2686:                         $lastcolspan = ' colspan="'.$colsleft.'"';
 2687:                     }
 2688:                 }
 2689:                 my $check = ' ';
 2690:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
 2691:                     $check = ' checked="checked" ';
 2692:                 }
 2693:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
 2694:                            '<span class="LC_nobreak"><label>'.
 2695:                            '<input type="checkbox" name="inststatus" '.
 2696:                            'value="'.$types->[$i].'"'.$check.'/>'.
 2697:                            $usertypes->{$types->[$i]}.'</label></span></td>';
 2698:             }
 2699:         }
 2700:         $output .= '</tr></table>';
 2701:     }
 2702:     return $output;
 2703: }
 2704: 
 2705: sub selfcreate_canmodify {
 2706:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
 2707:     if (ref($inst_results) eq 'HASH') {
 2708:         my @inststatuses = &get_inststatuses($inst_results);
 2709:         if (@inststatuses == 0) {
 2710:             @inststatuses = ('default');
 2711:         }
 2712:         $rolesarray = \@inststatuses;
 2713:     }
 2714:     my %canmodify =
 2715:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
 2716:                                                    $rolesarray);
 2717:     return %canmodify;
 2718: }
 2719: 
 2720: sub get_inststatuses {
 2721:     my ($insthashref) = @_;
 2722:     my @inststatuses = ();
 2723:     if (ref($insthashref) eq 'HASH') {
 2724:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
 2725:             @inststatuses = @{$insthashref->{'inststatus'}};
 2726:         }
 2727:     }
 2728:     return @inststatuses;
 2729: }
 2730: 
 2731: # ================================================================= Phase Three
 2732: sub update_user_data {
 2733:     my ($r,$context,$crstype,$brcrum,$showcredits) = @_; 
 2734:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 2735:                                           $env{'form.ccdomain'});
 2736:     # Error messages
 2737:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
 2738:     my $end       = '</span><br /><br />';
 2739:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
 2740:                     "'$env{'form.prevphase'}','modify')".'" />'.
 2741:                     &mt('Return to previous page').'</a>'.
 2742:                     &Apache::loncommon::end_page();
 2743:     my $now = time;
 2744:     my $title;
 2745:     if (exists($env{'form.makeuser'})) {
 2746: 	$title='Set Privileges for New User';
 2747:     } else {
 2748:         $title='Modify User Privileges';
 2749:     }
 2750:     my $newuser = 0;
 2751:     my ($jsback,$elements) = &crumb_utilities();
 2752:     my $jscript = '<script type="text/javascript">'."\n".
 2753:                   '// <![CDATA['."\n".
 2754:                   $jsback."\n".
 2755:                   '// ]]>'."\n".
 2756:                   '</script>'."\n";
 2757:     my %breadcrumb_text = &singleuser_breadcrumb($crstype,$context,$env{'form.ccdomain'});
 2758:     push (@{$brcrum},
 2759:              {href => "javascript:backPage(document.userupdate)",
 2760:               text => $breadcrumb_text{'search'},
 2761:               faq  => 282,
 2762:               bug  => 'Instructor Interface',}
 2763:              );
 2764:     if ($env{'form.prevphase'} eq 'userpicked') {
 2765:         push(@{$brcrum},
 2766:                {href => "javascript:backPage(document.userupdate,'get_user_info','select')",
 2767:                 text => $breadcrumb_text{'userpicked'},
 2768:                 faq  => 282,
 2769:                 bug  => 'Instructor Interface',});
 2770:     }
 2771:     my $helpitem = 'Course_Change_Privileges';
 2772:     if ($env{'form.action'} eq 'singlestudent') {
 2773:         $helpitem = 'Course_Add_Student';
 2774:     } elsif ($context eq 'author') {
 2775:         $helpitem = 'Author_Change_Privileges';
 2776:     } elsif ($context eq 'domain') {
 2777:         $helpitem = 'Domain_Change_Privileges';
 2778:     }
 2779:     push(@{$brcrum}, 
 2780:             {href => "javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 2781:              text => $breadcrumb_text{'modify'},
 2782:              faq  => 282,
 2783:              bug  => 'Instructor Interface',},
 2784:             {href => "/adm/createuser",
 2785:              text => "Result",
 2786:              faq  => 282,
 2787:              bug  => 'Instructor Interface',
 2788:              help => $helpitem});
 2789:     my $args = {bread_crumbs          => $brcrum,
 2790:                 bread_crumbs_component => 'User Management'};
 2791:     if ($env{'form.popup'}) {
 2792:         $args->{'no_nav_bar'} = 1;
 2793:     }
 2794:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
 2795:     $r->print(&update_result_form($uhome));
 2796:     # Check Inputs
 2797:     if (! $env{'form.ccuname'} ) {
 2798: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
 2799: 	return;
 2800:     }
 2801:     if (  $env{'form.ccuname'} ne 
 2802: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 2803: 	$r->print($error.&mt('Invalid login name.').'  '.
 2804: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
 2805: 		  $end.$rtnlink);
 2806: 	return;
 2807:     }
 2808:     if (! $env{'form.ccdomain'}       ) {
 2809: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
 2810: 	return;
 2811:     }
 2812:     if (  $env{'form.ccdomain'} ne
 2813: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 2814: 	$r->print($error.&mt('Invalid domain name.').'  '.
 2815: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
 2816: 		  $end.$rtnlink);
 2817: 	return;
 2818:     }
 2819:     if ($uhome eq 'no_host') {
 2820:         $newuser = 1;
 2821:     }
 2822:     if (! exists($env{'form.makeuser'})) {
 2823:         # Modifying an existing user, so check the validity of the name
 2824:         if ($uhome eq 'no_host') {
 2825:             $r->print(
 2826:                 $error
 2827:                .'<p class="LC_error">'
 2828:                .&mt('Unable to determine home server for [_1] in domain [_2].',
 2829:                         '"'.$env{'form.ccuname'}.'"','"'.$env{'form.ccdomain'}.'"')
 2830:                .'</p>');
 2831:             return;
 2832:         }
 2833:     }
 2834:     # Determine authentication method and password for the user being modified
 2835:     my $amode='';
 2836:     my $genpwd='';
 2837:     if ($env{'form.login'} eq 'krb') {
 2838: 	$amode='krb';
 2839: 	$amode.=$env{'form.krbver'};
 2840: 	$genpwd=$env{'form.krbarg'};
 2841:     } elsif ($env{'form.login'} eq 'int') {
 2842: 	$amode='internal';
 2843: 	$genpwd=$env{'form.intarg'};
 2844:     } elsif ($env{'form.login'} eq 'fsys') {
 2845: 	$amode='unix';
 2846: 	$genpwd=$env{'form.fsysarg'};
 2847:     } elsif ($env{'form.login'} eq 'loc') {
 2848: 	$amode='localauth';
 2849: 	$genpwd=$env{'form.locarg'};
 2850: 	$genpwd=" " if (!$genpwd);
 2851:     } elsif ($env{'form.login'} eq 'lti') {
 2852:         $amode='lti';
 2853:         $genpwd=" ";
 2854:     } elsif (($env{'form.login'} eq 'nochange') ||
 2855:              ($env{'form.login'} eq ''        )) { 
 2856:         # There is no need to tell the user we did not change what they
 2857:         # did not ask us to change.
 2858:         # If they are creating a new user but have not specified login
 2859:         # information this will be caught below.
 2860:     } else {
 2861:             $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);
 2862:             return;
 2863:     }
 2864: 
 2865:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
 2866:                         $env{'form.ccuname'}.' ('.&Apache::loncommon::plainname($env{'form.ccuname'},
 2867:                         $env{'form.ccdomain'}).')', $env{'form.ccdomain'}).'</h3>');
 2868:     my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,2);
 2869: 
 2870:     my (%alerts,%rulematch,%inst_results,%curr_rules);
 2871:     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 2872:     my @usertools = ('aboutme','blog','webdav','portfolio');
 2873:     my @requestcourses = ('official','unofficial','community','textbook','placement','lti');
 2874:     my @requestauthor = ('requestauthor');
 2875:     my ($othertitle,$usertypes,$types) = 
 2876:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
 2877:     my %canmodify_status =
 2878:         &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},
 2879:                                                    ['inststatus']);
 2880:     if ($env{'form.makeuser'}) {
 2881: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
 2882:         # Check for the authentication mode and password
 2883:         if (! $amode || ! $genpwd) {
 2884: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
 2885: 	    return;
 2886: 	}
 2887:         # Determine desired host
 2888:         my $desiredhost = $env{'form.hserver'};
 2889:         if (lc($desiredhost) eq 'default') {
 2890:             $desiredhost = undef;
 2891:         } else {
 2892:             my %home_servers = 
 2893: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 2894:             if (! exists($home_servers{$desiredhost})) {
 2895:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
 2896:                 return;
 2897:             }
 2898:         }
 2899:         # Check ID format
 2900:         my %checkhash;
 2901:         my %checks = ('id' => 1);
 2902:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
 2903:             'newuser' => $newuser, 
 2904:             'id' => $env{'form.cid'},
 2905:         );
 2906:         if ($env{'form.cid'} ne '') {
 2907:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 2908:                                           \%rulematch,\%inst_results,\%curr_rules);
 2909:             if (ref($alerts{'id'}) eq 'HASH') {
 2910:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 2911:                     my $domdesc =
 2912:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
 2913:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
 2914:                         my $userchkmsg;
 2915:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
 2916:                             $userchkmsg  = 
 2917:                                 &Apache::loncommon::instrule_disallow_msg('id',
 2918:                                                                     $domdesc,1).
 2919:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
 2920:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
 2921:                         }
 2922:                         $r->print($error.&mt('Invalid ID format').$end.
 2923:                                   $userchkmsg.$rtnlink);
 2924:                         return;
 2925:                     }
 2926:                 }
 2927:             }
 2928:         }
 2929:         &Apache::lonhtmlcommon::Increment_PrgWin($r, \%prog_state);
 2930: 	# Call modifyuser
 2931: 	my $result = &Apache::lonnet::modifyuser
 2932: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
 2933:              $amode,$genpwd,$env{'form.cfirstname'},
 2934:              $env{'form.cmiddlename'},$env{'form.clastname'},
 2935:              $env{'form.cgeneration'},undef,$desiredhost,
 2936:              $env{'form.cpermanentemail'});
 2937: 	$r->print(&mt('Generating user').': '.$result);
 2938:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
 2939:                                                $env{'form.ccdomain'});
 2940:         my (%changeHash,%newcustom,%changed,%changedinfo);
 2941:         if ($uhome ne 'no_host') {
 2942:             if ($context eq 'domain') {
 2943:                 foreach my $name ('portfolio','author') {
 2944:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 2945:                         if ($env{'form.'.$name.'quota'} eq '') {
 2946:                             $newcustom{$name.'quota'} = 0;
 2947:                         } else {
 2948:                             $newcustom{$name.'quota'} = $env{'form.'.$name.'quota'};
 2949:                             $newcustom{$name.'quota'} =~ s/[^\d\.]//g;
 2950:                         }
 2951:                         if (&quota_admin($newcustom{$name.'quota'},\%changeHash,$name)) {
 2952:                             $changed{$name.'quota'} = 1;
 2953:                         }
 2954:                     }
 2955:                 }
 2956:                 foreach my $item (@usertools) {
 2957:                     if ($env{'form.custom'.$item} == 1) {
 2958:                         $newcustom{$item} = $env{'form.tools_'.$item};
 2959:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2960:                                                      \%changeHash,'tools');
 2961:                     }
 2962:                 }
 2963:                 foreach my $item (@requestcourses) {
 2964:                     if ($env{'form.custom'.$item} == 1) {
 2965:                         $newcustom{$item} = $env{'form.crsreq_'.$item};
 2966:                         if ($env{'form.crsreq_'.$item} eq 'autolimit') {
 2967:                             $newcustom{$item} .= '=';
 2968:                             $env{'form.crsreq_'.$item.'_limit'} =~ s/\D+//g;
 2969:                             if ($env{'form.crsreq_'.$item.'_limit'}) {
 2970:                                 $newcustom{$item} .= $env{'form.crsreq_'.$item.'_limit'};
 2971:                             }
 2972:                         }
 2973:                         $changed{$item} = &tool_admin($item,$newcustom{$item},
 2974:                                                       \%changeHash,'requestcourses');
 2975:                     }
 2976:                 }
 2977:                 if ($env{'form.customrequestauthor'} == 1) {
 2978:                     $newcustom{'requestauthor'} = $env{'form.requestauthor'};
 2979:                     $changed{'requestauthor'} = &tool_admin('requestauthor',
 2980:                                                     $newcustom{'requestauthor'},
 2981:                                                     \%changeHash,'requestauthor');
 2982:                 }
 2983:             }
 2984:             if ($canmodify_status{'inststatus'}) {
 2985:                 if (exists($env{'form.inststatus'})) {
 2986:                     my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 2987:                     if (@inststatuses > 0) {
 2988:                         $changeHash{'inststatus'} = join(',',@inststatuses);
 2989:                         $changed{'inststatus'} = $changeHash{'inststatus'};
 2990:                     }
 2991:                 }
 2992:             }
 2993:             if (keys(%changed)) {
 2994:                 foreach my $item (@userinfo) {
 2995:                     $changeHash{$item}  = $env{'form.c'.$item};
 2996:                 }
 2997:                 my $chgresult =
 2998:                      &Apache::lonnet::put('environment',\%changeHash,
 2999:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
 3000:             } 
 3001:         }
 3002:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
 3003:                   &Apache::lonnet::hostname($uhome));
 3004:     } elsif (($env{'form.login'} ne 'nochange') &&
 3005:              ($env{'form.login'} ne ''        )) {
 3006: 	# Modify user privileges
 3007:         if (! $amode || ! $genpwd) {
 3008: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
 3009: 	    return;
 3010: 	}
 3011: 	# Only allow authentication modification if the person has authority
 3012: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3013: 	    $r->print('Modifying authentication: '.
 3014:                       &Apache::lonnet::modifyuserauth(
 3015: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 3016:                        $amode,$genpwd));
 3017:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 3018: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 3019: 	} else {
 3020: 	    # Okay, this is a non-fatal error.
 3021: 	    $r->print($error.&mt('You do not have the authority to modify this users authentication information.').$end);    
 3022: 	}
 3023:     }
 3024:     $r->rflush(); # Finish display of header before time consuming actions start
 3025:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state);
 3026:     ##
 3027:     my (@userroles,%userupdate,$cnum,$cdom,$defaultcredits,%namechanged);
 3028:     if ($context eq 'course') {
 3029:         ($cnum,$cdom) =
 3030:             &Apache::lonuserutils::get_course_identity();
 3031:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 3032:         if ($showcredits) {
 3033:            $defaultcredits = &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 3034:         }
 3035:     }
 3036:     if (! $env{'form.makeuser'} ) {
 3037:         # Check for need to change
 3038:         my %userenv = &Apache::lonnet::get
 3039:             ('environment',['firstname','middlename','lastname','generation',
 3040:              'id','permanentemail','portfolioquota','authorquota','inststatus',
 3041:              'tools.aboutme','tools.blog','tools.webdav','tools.portfolio',
 3042:              'requestcourses.official','requestcourses.unofficial',
 3043:              'requestcourses.community','requestcourses.textbook',
 3044:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
 3045:              'reqcrsotherdom.community','reqcrsotherdom.textbook',
 3046:              'reqcrsotherdom.placement','requestauthor'],
 3047:               $env{'form.ccdomain'},$env{'form.ccuname'});
 3048:         my ($tmp) = keys(%userenv);
 3049:         if ($tmp =~ /^(con_lost|error)/i) { 
 3050:             %userenv = ();
 3051:         }
 3052:         my $no_forceid_alert;
 3053:         # Check to see if user information can be changed
 3054:         my %domconfig =
 3055:             &Apache::lonnet::get_dom('configuration',['usermodification'],
 3056:                                      $env{'form.ccdomain'});
 3057:         my @statuses = ('active','future');
 3058:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
 3059:         my ($auname,$audom);
 3060:         if ($context eq 'author') {
 3061:             $auname = $env{'user.name'};
 3062:             $audom = $env{'user.domain'};     
 3063:         }
 3064:         foreach my $item (keys(%roles)) {
 3065:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
 3066:             if ($context eq 'course') {
 3067:                 if ($cnum ne '' && $cdom ne '') {
 3068:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
 3069:                         if (!grep(/^\Q$role\E$/,@userroles)) {
 3070:                             push(@userroles,$role);
 3071:                         }
 3072:                     }
 3073:                 }
 3074:             } elsif ($context eq 'author') {
 3075:                 if ($rolenum eq $auname && $roledom eq $audom) {
 3076:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
 3077:                         push(@userroles,$role);
 3078:                     }
 3079:                 }
 3080:             }
 3081:         }
 3082:         if ($env{'form.action'} eq 'singlestudent') {
 3083:             if (!grep(/^st$/,@userroles)) {
 3084:                 push(@userroles,'st');
 3085:             }
 3086:         } else {
 3087:             # Check for course or co-author roles being activated or re-enabled
 3088:             if ($context eq 'author' || $context eq 'course') {
 3089:                 foreach my $key (keys(%env)) {
 3090:                     if ($context eq 'author') {
 3091:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
 3092:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3093:                                 push(@userroles,$1);
 3094:                             }
 3095:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
 3096:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3097:                                 push(@userroles,$1);
 3098:                             }
 3099:                         }
 3100:                     } elsif ($context eq 'course') {
 3101:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
 3102:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3103:                                 push(@userroles,$1);
 3104:                             }
 3105:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
 3106:                             if (!grep(/^\Q$1\E$/,@userroles)) {
 3107:                                 push(@userroles,$1);
 3108:                             }
 3109:                         }
 3110:                     }
 3111:                 }
 3112:             }
 3113:         }
 3114:         #Check to see if we can change personal data for the user 
 3115:         my (@mod_disallowed,@longroles);
 3116:         foreach my $role (@userroles) {
 3117:             if ($role eq 'cr') {
 3118:                 push(@longroles,'Custom');
 3119:             } else {
 3120:                 push(@longroles,&Apache::lonnet::plaintext($role,$crstype)); 
 3121:             }
 3122:         }
 3123:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
 3124:         foreach my $item (@userinfo) {
 3125:             # Strip leading and trailing whitespace
 3126:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
 3127:             if (!$canmodify{$item}) {
 3128:                 if (defined($env{'form.c'.$item})) {
 3129:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
 3130:                         push(@mod_disallowed,$item);
 3131:                     }
 3132:                 }
 3133:                 $env{'form.c'.$item} = $userenv{$item};
 3134:             }
 3135:         }
 3136:         # Check to see if we can change the Student/Employee ID
 3137:         my $forceid = $env{'form.forceid'};
 3138:         my $recurseid = $env{'form.recurseid'};
 3139:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
 3140:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
 3141:                                             $env{'form.ccuname'});
 3142:         if (($uidhash{$env{'form.ccuname'}}) && 
 3143:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
 3144:             (!$forceid)) {
 3145:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
 3146:                 $env{'form.cid'} = $userenv{'id'};
 3147:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
 3148:                                    .'<br />'
 3149:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
 3150:                                    .'<br />'."\n";
 3151:             }
 3152:         }
 3153:         if ($env{'form.cid'} ne $userenv{'id'}) {
 3154:             my $checkhash;
 3155:             my $checks = { 'id' => 1 };
 3156:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
 3157:                    { 'newuser' => $newuser,
 3158:                      'id'  => $env{'form.cid'}, 
 3159:                    };
 3160:             &Apache::loncommon::user_rule_check($checkhash,$checks,
 3161:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
 3162:             if (ref($alerts{'id'}) eq 'HASH') {
 3163:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
 3164:                    $env{'form.cid'} = $userenv{'id'};
 3165:                 }
 3166:             }
 3167:         }
 3168:         my (%quotachanged,%oldquota,%newquota,%olddefquota,%newdefquota, 
 3169:             $oldinststatus,$newinststatus,%oldisdefault,%newisdefault,%oldsettings,
 3170:             %oldsettingstext,%newsettings,%newsettingstext,@disporder,
 3171:             %oldsettingstatus,%newsettingstatus);
 3172:         @disporder = ('inststatus');
 3173:         if ($env{'request.role.domain'} eq $env{'form.ccdomain'}) {
 3174:             push(@disporder,'requestcourses','requestauthor');
 3175:         } else {
 3176:             push(@disporder,'reqcrsotherdom');
 3177:         }
 3178:         push(@disporder,('quota','tools'));
 3179:         $oldinststatus = $userenv{'inststatus'};
 3180:         foreach my $name ('portfolio','author') {
 3181:             ($olddefquota{$name},$oldsettingstatus{$name}) = 
 3182:                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
 3183:             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
 3184:         }
 3185:         my %canshow;
 3186:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 3187:             $canshow{'quota'} = 1;
 3188:         }
 3189:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 3190:             $canshow{'tools'} = 1;
 3191:         }
 3192:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 3193:             $canshow{'requestcourses'} = 1;
 3194:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 3195:             $canshow{'reqcrsotherdom'} = 1;
 3196:         }
 3197:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 3198:             $canshow{'inststatus'} = 1;
 3199:         }
 3200:         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
 3201:             $canshow{'requestauthor'} = 1;
 3202:         }
 3203:         my (%changeHash,%changed);
 3204:         if ($oldinststatus eq '') {
 3205:             $oldsettings{'inststatus'} = $othertitle; 
 3206:         } else {
 3207:             if (ref($usertypes) eq 'HASH') {
 3208:                 $oldsettings{'inststatus'} = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
 3209:             } else {
 3210:                 $oldsettings{'inststatus'} = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
 3211:             }
 3212:         }
 3213:         $changeHash{'inststatus'} = $userenv{'inststatus'};
 3214:         if ($canmodify_status{'inststatus'}) {
 3215:             $canshow{'inststatus'} = 1;
 3216:             if (exists($env{'form.inststatus'})) {
 3217:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
 3218:                 if (@inststatuses > 0) {
 3219:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
 3220:                     $changeHash{'inststatus'} = $newinststatus;
 3221:                     if ($newinststatus ne $oldinststatus) {
 3222:                         $changed{'inststatus'} = $newinststatus;
 3223:                         foreach my $name ('portfolio','author') {
 3224:                             ($newdefquota{$name},$newsettingstatus{$name}) =
 3225:                                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3226:                         }
 3227:                     }
 3228:                     if (ref($usertypes) eq 'HASH') {
 3229:                         $newsettings{'inststatus'} = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
 3230:                     } else {
 3231:                         $newsettings{'inststatus'} = join(', ',@inststatuses);
 3232:                     }
 3233:                 }
 3234:             } else {
 3235:                 $newinststatus = '';
 3236:                 $changeHash{'inststatus'} = $newinststatus;
 3237:                 $newsettings{'inststatus'} = $othertitle;
 3238:                 if ($newinststatus ne $oldinststatus) {
 3239:                     $changed{'inststatus'} = $changeHash{'inststatus'};
 3240:                     foreach my $name ('portfolio','author') {
 3241:                         ($newdefquota{$name},$newsettingstatus{$name}) =
 3242:                             &Apache::loncommon::default_quota($env{'form.ccdomain'},$newinststatus,$name);
 3243:                     }
 3244:                 }
 3245:             }
 3246:         } elsif ($context ne 'selfcreate') {
 3247:             $canshow{'inststatus'} = 1;
 3248:             $newsettings{'inststatus'} = $oldsettings{'inststatus'};
 3249:         }
 3250:         foreach my $name ('portfolio','author') {
 3251:             $changeHash{$name.'quota'} = $userenv{$name.'quota'};
 3252:         }
 3253:         if ($context eq 'domain') {
 3254:             foreach my $name ('portfolio','author') {
 3255:                 if ($userenv{$name.'quota'} ne '') {
 3256:                     $oldquota{$name} = $userenv{$name.'quota'};
 3257:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3258:                         if ($env{'form.'.$name.'quota'} eq '') {
 3259:                             $newquota{$name} = 0;
 3260:                         } else {
 3261:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3262:                             $newquota{$name} =~ s/[^\d\.]//g;
 3263:                         }
 3264:                         if ($newquota{$name} != $oldquota{$name}) {
 3265:                             if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3266:                                 $changed{$name.'quota'} = 1;
 3267:                             }
 3268:                         }
 3269:                     } else {
 3270:                         if (&quota_admin('',\%changeHash,$name)) {
 3271:                             $changed{$name.'quota'} = 1;
 3272:                             $newquota{$name} = $newdefquota{$name};
 3273:                             $newisdefault{$name} = 1;
 3274:                         }
 3275:                     }
 3276:                 } else {
 3277:                     $oldisdefault{$name} = 1;
 3278:                     $oldquota{$name} = $olddefquota{$name};
 3279:                     if ($env{'form.custom_'.$name.'quota'} == 1) {
 3280:                         if ($env{'form.'.$name.'quota'} eq '') {
 3281:                             $newquota{$name} = 0;
 3282:                         } else {
 3283:                             $newquota{$name} = $env{'form.'.$name.'quota'};
 3284:                             $newquota{$name} =~ s/[^\d\.]//g;
 3285:                         }
 3286:                         if (&quota_admin($newquota{$name},\%changeHash,$name)) {
 3287:                             $changed{$name.'quota'} = 1;
 3288:                         }
 3289:                     } else {
 3290:                         $newquota{$name} = $newdefquota{$name};
 3291:                         $newisdefault{$name} = 1;
 3292:                     }
 3293:                 }
 3294:                 if ($oldisdefault{$name}) {
 3295:                     $oldsettingstext{'quota'}{$name} = &get_defaultquota_text($oldsettingstatus{$name});
 3296:                 }  else {
 3297:                     $oldsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$oldquota{$name});
 3298:                 }
 3299:                 if ($newisdefault{$name}) {
 3300:                     $newsettingstext{'quota'}{$name} = &get_defaultquota_text($newsettingstatus{$name});
 3301:                 } else {
 3302:                     $newsettingstext{'quota'}{$name} = &mt('custom quota: [_1] MB',$newquota{$name});
 3303:                 }
 3304:             }
 3305:             &tool_changes('tools',\@usertools,\%oldsettings,\%oldsettingstext,\%userenv,
 3306:                           \%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3307:             if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
 3308:                 &tool_changes('requestcourses',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3309:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3310:                 &tool_changes('requestauthor',\@requestauthor,\%oldsettings,\%oldsettingstext,
 3311:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3312:             } else {
 3313:                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
 3314:                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
 3315:             }
 3316:         }
 3317:         foreach my $item (@userinfo) {
 3318:             if ($env{'form.c'.$item} ne $userenv{$item}) {
 3319:                 $namechanged{$item} = 1;
 3320:             }
 3321:         }
 3322:         foreach my $name ('portfolio','author') {
 3323:             $oldsettings{'quota'}{$name} = &mt('[_1] MB',$oldquota{$name});
 3324:             $newsettings{'quota'}{$name} = &mt('[_1] MB',$newquota{$name});
 3325:         }
 3326:         if ((keys(%namechanged) > 0) || (keys(%changed) > 0)) {
 3327:             my ($chgresult,$namechgresult);
 3328:             if (keys(%changed) > 0) {
 3329:                 $chgresult = 
 3330:                     &Apache::lonnet::put('environment',\%changeHash,
 3331:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 3332:                 if ($chgresult eq 'ok') {
 3333:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
 3334:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
 3335:                         my %newenvhash;
 3336:                         foreach my $key (keys(%changed)) {
 3337:                             if (($key eq 'official') || ($key eq 'unofficial') ||
 3338:                                 ($key eq 'community') || ($key eq 'textbook') ||
 3339:                                 ($key eq 'placement') || ($key eq 'lti')) {
 3340:                                 $newenvhash{'environment.requestcourses.'.$key} =
 3341:                                     $changeHash{'requestcourses.'.$key};
 3342:                                 if ($changeHash{'requestcourses.'.$key}) {
 3343:                                     $newenvhash{'environment.canrequest.'.$key} = 1;
 3344:                                 } else {
 3345:                                     $newenvhash{'environment.canrequest.'.$key} =
 3346:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3347:                                             $key,'reload','requestcourses');
 3348:                                 }
 3349:                             } elsif ($key eq 'requestauthor') {
 3350:                                 $newenvhash{'environment.'.$key} = $changeHash{$key};
 3351:                                 if ($changeHash{$key}) {
 3352:                                     $newenvhash{'environment.canrequest.author'} = 1;
 3353:                                 } else {
 3354:                                     $newenvhash{'environment.canrequest.author'} =
 3355:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3356:                                             $key,'reload','requestauthor');
 3357:                                 }
 3358:                             } elsif ($key ne 'quota') {
 3359:                                 $newenvhash{'environment.tools.'.$key} = 
 3360:                                     $changeHash{'tools.'.$key};
 3361:                                 if ($changeHash{'tools.'.$key} ne '') {
 3362:                                     $newenvhash{'environment.availabletools.'.$key} =
 3363:                                         $changeHash{'tools.'.$key};
 3364:                                 } else {
 3365:                                     $newenvhash{'environment.availabletools.'.$key} =
 3366:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
 3367:           $key,'reload','tools');
 3368:                                 }
 3369:                             }
 3370:                         }
 3371:                         if (keys(%newenvhash)) {
 3372:                             &Apache::lonnet::appenv(\%newenvhash);
 3373:                         }
 3374:                     }
 3375:                 }
 3376:             }
 3377:             if (keys(%namechanged) > 0) {
 3378:                 foreach my $field (@userinfo) {
 3379:                     $changeHash{$field}  = $env{'form.c'.$field};
 3380:                 }
 3381: # Make the change
 3382:                 $namechgresult =
 3383:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
 3384:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
 3385:                         $changeHash{'firstname'},$changeHash{'middlename'},
 3386:                         $changeHash{'lastname'},$changeHash{'generation'},
 3387:                         $changeHash{'id'},undef,$changeHash{'permanentemail'},undef,\@userinfo);
 3388:                 %userupdate = (
 3389:                                lastname   => $env{'form.clastname'},
 3390:                                middlename => $env{'form.cmiddlename'},
 3391:                                firstname  => $env{'form.cfirstname'},
 3392:                                generation => $env{'form.cgeneration'},
 3393:                                id         => $env{'form.cid'},
 3394:                              );
 3395:             }
 3396:             if (((keys(%namechanged) > 0) && $namechgresult eq 'ok') || 
 3397:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
 3398:             # Tell the user we changed the name
 3399:                 &display_userinfo($r,1,\@disporder,\%canshow,\@requestcourses,
 3400:                                   \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,
 3401:                                   \%oldsettings, \%oldsettingstext,\%newsettings,
 3402:                                   \%newsettingstext);
 3403:                 if ($env{'form.cid'} ne $userenv{'id'}) {
 3404:                     &Apache::lonnet::idput($env{'form.ccdomain'},
 3405:                          {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
 3406:                     if (($recurseid) &&
 3407:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
 3408:                         my $idresult = 
 3409:                             &Apache::lonuserutils::propagate_id_change(
 3410:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
 3411:                                 \%userupdate);
 3412:                         $r->print('<br />'.$idresult.'<br />');
 3413:                     }
 3414:                 }
 3415:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 3416:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 3417:                     my %newenvhash;
 3418:                     foreach my $key (keys(%changeHash)) {
 3419:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 3420:                     }
 3421:                     &Apache::lonnet::appenv(\%newenvhash);
 3422:                 }
 3423:             } else { # error occurred
 3424:                 $r->print(
 3425:                     '<p class="LC_error">'
 3426:                    .&mt('Unable to successfully change environment for [_1] in domain [_2].',
 3427:                             '"'.$env{'form.ccuname'}.'"',
 3428:                             '"'.$env{'form.ccdomain'}.'"')
 3429:                    .'</p>');
 3430:             }
 3431:         } else { # End of if ($env ... ) logic
 3432:             # They did not want to change the users name, quota, tool availability,
 3433:             # or ability to request creation of courses, 
 3434:             # but we can still tell them what the name and quota and availabilities are  
 3435:             &display_userinfo($r,undef,\@disporder,\%canshow,\@requestcourses,
 3436:                               \@usertools,\@requestauthor,\%userenv,\%changed,\%namechanged,\%oldsettings,
 3437:                               \%oldsettingstext,\%newsettings,\%newsettingstext);
 3438:         }
 3439:         if (@mod_disallowed) {
 3440:             my ($rolestr,$contextname);
 3441:             if (@longroles > 0) {
 3442:                 $rolestr = join(', ',@longroles);
 3443:             } else {
 3444:                 $rolestr = &mt('No roles');
 3445:             }
 3446:             if ($context eq 'course') {
 3447:                 $contextname = 'course';
 3448:             } elsif ($context eq 'author') {
 3449:                 $contextname = 'co-author';
 3450:             }
 3451:             $r->print(&mt('The following fields were not updated: ').'<ul>');
 3452:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3453:             foreach my $field (@mod_disallowed) {
 3454:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
 3455:             }
 3456:             $r->print('</ul>');
 3457:             if (@mod_disallowed == 1) {
 3458:                 $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
 3459:             } else {
 3460:                 $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
 3461:             }
 3462:             my $helplink = 'javascript:helpMenu('."'display'".')';
 3463:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
 3464:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
 3465:                          ,'<a href="'.$helplink.'">','</a>')
 3466:                       .'<br />');
 3467:         }
 3468:         $r->print('<span class="LC_warning">'
 3469:                   .$no_forceid_alert
 3470:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
 3471:                   .'</span>');
 3472:     }
 3473:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3474:     if ($env{'form.action'} eq 'singlestudent') {
 3475:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context,
 3476:                                $crstype,$showcredits,$defaultcredits);
 3477:         my $linktext = ($crstype eq 'Community' ?
 3478:             &mt('Enroll Another Member') : &mt('Enroll Another Student'));
 3479:         $r->print(
 3480:             &Apache::lonhtmlcommon::actionbox([
 3481:                 '<a href="javascript:backPage(document.userupdate)">'
 3482:                .($crstype eq 'Community' ? 
 3483:                     &mt('Enroll Another Member') : &mt('Enroll Another Student'))
 3484:                .'</a>']));
 3485:     } else {
 3486:         my @rolechanges = &update_roles($r,$context,$showcredits);
 3487:         if (keys(%namechanged) > 0) {
 3488:             if ($context eq 'course') {
 3489:                 if (@userroles > 0) {
 3490:                     if ((@rolechanges == 0) || 
 3491:                         (!(grep(/^st$/,@rolechanges)))) {
 3492:                         if (grep(/^st$/,@userroles)) {
 3493:                             my $classlistupdated =
 3494:                                 &Apache::lonuserutils::update_classlist($cdom,
 3495:                                               $cnum,$env{'form.ccdomain'},
 3496:                                        $env{'form.ccuname'},\%userupdate);
 3497:                         }
 3498:                     }
 3499:                 }
 3500:             }
 3501:         }
 3502:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
 3503:                                                      $env{'form.ccdomain'});
 3504:         if ($env{'form.popup'}) {
 3505:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 3506:         } else {
 3507:             $r->print('<br />'.&Apache::lonhtmlcommon::actionbox(['<a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
 3508:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>',
 3509:                      '<a href="javascript:backPage(document.userupdate)">'.&mt('Create/Modify Another User').'</a>']));
 3510:         }
 3511:     }
 3512: }
 3513: 
 3514: sub display_userinfo {
 3515:     my ($r,$changed,$order,$canshow,$requestcourses,$usertools,$requestauthor,
 3516:         $userenv,$changedhash,$namechangedhash,$oldsetting,$oldsettingtext,
 3517:         $newsetting,$newsettingtext) = @_;
 3518:     return unless (ref($order) eq 'ARRAY' &&
 3519:                    ref($canshow) eq 'HASH' && 
 3520:                    ref($requestcourses) eq 'ARRAY' && 
 3521:                    ref($requestauthor) eq 'ARRAY' &&
 3522:                    ref($usertools) eq 'ARRAY' && 
 3523:                    ref($userenv) eq 'HASH' &&
 3524:                    ref($changedhash) eq 'HASH' &&
 3525:                    ref($oldsetting) eq 'HASH' &&
 3526:                    ref($oldsettingtext) eq 'HASH' &&
 3527:                    ref($newsetting) eq 'HASH' &&
 3528:                    ref($newsettingtext) eq 'HASH');
 3529:     my %lt=&Apache::lonlocal::texthash(
 3530:          'ui'             => 'User Information',
 3531:          'uic'            => 'User Information Changed',
 3532:          'firstname'      => 'First Name',
 3533:          'middlename'     => 'Middle Name',
 3534:          'lastname'       => 'Last Name',
 3535:          'generation'     => 'Generation',
 3536:          'id'             => 'Student/Employee ID',
 3537:          'permanentemail' => 'Permanent e-mail address',
 3538:          'portfolioquota' => 'Disk space allocated to portfolio files',
 3539:          'authorquota'    => 'Disk space allocated to Authoring Space',
 3540:          'blog'           => 'Blog Availability',
 3541:          'webdav'         => 'WebDAV Availability',
 3542:          'aboutme'        => 'Personal Information Page Availability',
 3543:          'portfolio'      => 'Portfolio Availability',
 3544:          'official'       => 'Can Request Official Courses',
 3545:          'unofficial'     => 'Can Request Unofficial Courses',
 3546:          'community'      => 'Can Request Communities',
 3547:          'textbook'       => 'Can Request Textbook Courses',
 3548:          'placement'      => 'Can Request Placement Tests',
 3549:          'lti'            => 'Can Request LTI Courses',
 3550:          'requestauthor'  => 'Can Request Author Role',
 3551:          'inststatus'     => "Affiliation",
 3552:          'prvs'           => 'Previous Value:',
 3553:          'chto'           => 'Changed To:'
 3554:     );
 3555:     if ($changed) {
 3556:         $r->print('<h3>'.$lt{'uic'}.'</h3>'.
 3557:                 &Apache::loncommon::start_data_table().
 3558:                 &Apache::loncommon::start_data_table_header_row());
 3559:         $r->print("<th>&nbsp;</th>\n");
 3560:         $r->print('<th><b>'.$lt{'prvs'}.'</b></th>');
 3561:         $r->print('<th><span class="LC_nobreak"><b>'.$lt{'chto'}.'</b></span></th>');
 3562:         $r->print(&Apache::loncommon::end_data_table_header_row());
 3563:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
 3564: 
 3565:         foreach my $item (@userinfo) {
 3566:             my $value = $env{'form.c'.$item};
 3567:             #show changes only:
 3568:             unless ($value eq $userenv->{$item}){
 3569:                 $r->print(&Apache::loncommon::start_data_table_row());
 3570:                 $r->print("<td>$lt{$item}</td>\n");
 3571:                 $r->print("<td>".$userenv->{$item}."</td>\n");
 3572:                 $r->print("<td>$value </td>\n");
 3573:                 $r->print(&Apache::loncommon::end_data_table_row());
 3574:             }
 3575:         }
 3576:         foreach my $entry (@{$order}) {
 3577:             if ($canshow->{$entry}) {
 3578:                 if (($entry eq 'requestcourses') || ($entry eq 'reqcrsotherdom') || ($entry eq 'requestauthor')) {
 3579:                     my @items;
 3580:                     if ($entry eq 'requestauthor') {
 3581:                         @items = ($entry);
 3582:                     } else {
 3583:                         @items = @{$requestcourses};
 3584:                     }
 3585:                     foreach my $item (@items) {
 3586:                         if (($newsetting->{$item} ne $oldsetting->{$item}) || 
 3587:                             ($newsettingtext->{$item} ne $oldsettingtext->{$item})) {
 3588:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");  
 3589:                             $r->print("<td>$lt{$item}</td>\n");
 3590:                             $r->print("<td>".$oldsetting->{$item});
 3591:                             if ($oldsettingtext->{$item}) {
 3592:                                 if ($oldsetting->{$item}) {
 3593:                                     $r->print(' -- ');
 3594:                                 }
 3595:                                 $r->print($oldsettingtext->{$item});
 3596:                             }
 3597:                             $r->print("</td>\n");
 3598:                             $r->print("<td>".$newsetting->{$item});
 3599:                             if ($newsettingtext->{$item}) {
 3600:                                 if ($newsetting->{$item}) {
 3601:                                     $r->print(' -- ');
 3602:                                 }
 3603:                                 $r->print($newsettingtext->{$item});
 3604:                             }
 3605:                             $r->print("</td>\n");
 3606:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3607:                         }
 3608:                     }
 3609:                 } elsif ($entry eq 'tools') {
 3610:                     foreach my $item (@{$usertools}) {
 3611:                         if ($newsetting->{$item} ne $oldsetting->{$item}) {
 3612:                             $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3613:                             $r->print("<td>$lt{$item}</td>\n");
 3614:                             $r->print("<td>".$oldsetting->{$item}.' '.$oldsettingtext->{$item}."</td>\n");
 3615:                             $r->print("<td>".$newsetting->{$item}.' '.$newsettingtext->{$item}."</td>\n");
 3616:                             $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3617:                         }
 3618:                     }
 3619:                 } elsif ($entry eq 'quota') {
 3620:                     if ((ref($oldsetting->{$entry}) eq 'HASH') && (ref($oldsettingtext->{$entry}) eq 'HASH') &&
 3621:                         (ref($newsetting->{$entry}) eq 'HASH') && (ref($newsettingtext->{$entry}) eq 'HASH')) {
 3622:                         foreach my $name ('portfolio','author') {
 3623:                             if ($newsetting->{$entry}->{$name} ne $oldsetting->{$entry}->{$name}) {
 3624:                                 $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3625:                                 $r->print("<td>$lt{$name.$entry}</td>\n");
 3626:                                 $r->print("<td>".$oldsettingtext->{$entry}->{$name}."</td>\n");
 3627:                                 $r->print("<td>".$newsettingtext->{$entry}->{$name}."</td>\n");
 3628:                                 $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3629:                             }
 3630:                         }
 3631:                     }
 3632:                 } else {
 3633:                     if ($newsetting->{$entry} ne $oldsetting->{$entry}) {
 3634:                         $r->print(&Apache::loncommon::start_data_table_row()."\n");
 3635:                         $r->print("<td>$lt{$entry}</td>\n");
 3636:                         $r->print("<td>".$oldsetting->{$entry}.' '.$oldsettingtext->{$entry}."</td>\n");
 3637:                         $r->print("<td>".$newsetting->{$entry}.' '.$newsettingtext->{$entry}."</td>\n");
 3638:                         $r->print(&Apache::loncommon::end_data_table_row()."\n");
 3639:                     }
 3640:                 }
 3641:             }
 3642:         }
 3643:         $r->print(&Apache::loncommon::end_data_table().'<br />');
 3644:     } else {
 3645:         $r->print('<h3>'.$lt{'ui'}.'</h3>'.
 3646:                   '<p>'.&mt('No changes made to user information').'</p>');
 3647:     }
 3648:     return;
 3649: }
 3650: 
 3651: sub tool_changes {
 3652:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
 3653:         $changed,$newaccess,$newaccesstext) = @_;
 3654:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
 3655:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
 3656:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
 3657:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
 3658:         return;
 3659:     }
 3660:     my %reqdisplay = &requestchange_display();
 3661:     if ($context eq 'reqcrsotherdom') {
 3662:         my @options = ('approval','validate','autolimit');
 3663:         my $optregex = join('|',@options);
 3664:         my $cdom = $env{'request.role.domain'};
 3665:         foreach my $tool (@{$usertools}) {
 3666:             $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3667:             $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3668:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
 3669:             my ($newop,$limit);
 3670:             if ($env{'form.'.$context.'_'.$tool}) {
 3671:                 $newop = $env{'form.'.$context.'_'.$tool};
 3672:                 if ($newop eq 'autolimit') {
 3673:                     $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3674:                     $limit =~ s/\D+//g;
 3675:                     $newop .= '='.$limit;
 3676:                 }
 3677:             }
 3678:             if ($userenv->{$context.'.'.$tool} eq '') {
 3679:                 if ($newop) {
 3680:                     $changed->{$tool}=&tool_admin($tool,$cdom.':'.$newop,
 3681:                                                   $changeHash,$context);
 3682:                     if ($changed->{$tool}) {
 3683:                         if ($newop =~ /^autolimit/) {
 3684:                             if ($limit) {
 3685:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3686:                             } else {
 3687:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3688:                             }
 3689:                         } else {
 3690:                             $newaccesstext->{$tool} = $reqdisplay{$newop};
 3691:                         }
 3692:                     } else {
 3693:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3694:                     }
 3695:                 }
 3696:             } else {
 3697:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
 3698:                 my @new;
 3699:                 my $changedoms;
 3700:                 foreach my $req (@curr) {
 3701:                     if ($req =~ /^\Q$cdom\E\:($optregex\=?\d*)$/) {
 3702:                         my $oldop = $1;
 3703:                         if ($oldop =~ /^autolimit=(\d*)/) {
 3704:                             my $limit = $1;
 3705:                             if ($limit) {
 3706:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3707:                             } else {
 3708:                                 $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3709:                             }
 3710:                         } else {
 3711:                             $oldaccesstext->{$tool} = $reqdisplay{$oldop};
 3712:                         }
 3713:                         if ($oldop ne $newop) {
 3714:                             $changedoms = 1;
 3715:                             foreach my $item (@curr) {
 3716:                                 my ($reqdom,$option) = split(':',$item);
 3717:                                 unless ($reqdom eq $cdom) {
 3718:                                     push(@new,$item);
 3719:                                 }
 3720:                             }
 3721:                             if ($newop) {
 3722:                                 push(@new,$cdom.':'.$newop);
 3723:                             }
 3724:                             @new = sort(@new);
 3725:                         }
 3726:                         last;
 3727:                     }
 3728:                 }
 3729:                 if ((!$changedoms) && ($newop)) {
 3730:                     $changedoms = 1;
 3731:                     @new = sort(@curr,$cdom.':'.$newop);
 3732:                 }
 3733:                 if ($changedoms) {
 3734:                     my $newdomstr;
 3735:                     if (@new) {
 3736:                         $newdomstr = join(',',@new);
 3737:                     }
 3738:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
 3739:                                                   $context);
 3740:                     if ($changed->{$tool}) {
 3741:                         if ($env{'form.'.$context.'_'.$tool}) {
 3742:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
 3743:                                 my $limit = $env{'form.'.$context.'_'.$tool.'_limit'};
 3744:                                 $limit =~ s/\D+//g;
 3745:                                 if ($limit) {
 3746:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3747:                                 } else {
 3748:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3749:                                 }
 3750:                             } else {
 3751:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
 3752:                             }
 3753:                         } else {
 3754:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3755:                         }
 3756:                     }
 3757:                 }
 3758:             }
 3759:         }
 3760:         return;
 3761:     }
 3762:     foreach my $tool (@{$usertools}) {
 3763:         my ($newval,$limit,$envkey);
 3764:         $envkey = $context.'.'.$tool;
 3765:         if ($context eq 'requestcourses') {
 3766:             $newval = $env{'form.crsreq_'.$tool};
 3767:             if ($newval eq 'autolimit') {
 3768:                 $limit = $env{'form.crsreq_'.$tool.'_limit'};
 3769:                 $limit =~ s/\D+//g;
 3770:                 $newval .= '='.$limit;
 3771:             }
 3772:         } elsif ($context eq 'requestauthor') {
 3773:             $newval = $env{'form.'.$context};
 3774:             $envkey = $context;
 3775:         } else {
 3776:             $newval = $env{'form.'.$context.'_'.$tool};
 3777:         }
 3778:         if ($userenv->{$envkey} ne '') {
 3779:             $oldaccess->{$tool} = &mt('custom');
 3780:             if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3781:                 if ($userenv->{$envkey} =~ /^autolimit=(\d*)$/) {
 3782:                     my $currlimit = $1;
 3783:                     if ($currlimit eq '') {
 3784:                         $oldaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3785:                     } else {
 3786:                         $oldaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$currlimit);
 3787:                     }
 3788:                 } elsif ($userenv->{$envkey}) {
 3789:                     $oldaccesstext->{$tool} = $reqdisplay{$userenv->{$envkey}};
 3790:                 } else {
 3791:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3792:                 }
 3793:             } else {
 3794:                 if ($userenv->{$envkey}) {
 3795:                     $oldaccesstext->{$tool} = &mt("availability set to 'on'");
 3796:                 } else {
 3797:                     $oldaccesstext->{$tool} = &mt("availability set to 'off'");
 3798:                 }
 3799:             }
 3800:             $changeHash->{$envkey} = $userenv->{$envkey};
 3801:             if ($env{'form.custom'.$tool} == 1) {
 3802:                 if ($newval ne $userenv->{$envkey}) {
 3803:                     $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3804:                                                     $context);
 3805:                     if ($changed->{$tool}) {
 3806:                         $newaccess->{$tool} = &mt('custom');
 3807:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3808:                             if ($newval =~ /^autolimit/) {
 3809:                                 if ($limit) {
 3810:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3811:                                 } else {
 3812:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3813:                                 }
 3814:                             } elsif ($newval) {
 3815:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3816:                             } else {
 3817:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3818:                             }
 3819:                         } else {
 3820:                             if ($newval) {
 3821:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3822:                             } else {
 3823:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3824:                             }
 3825:                         }
 3826:                     } else {
 3827:                         $newaccess->{$tool} = $oldaccess->{$tool};
 3828:                         if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3829:                             if ($newval =~ /^autolimit/) {
 3830:                                 if ($limit) {
 3831:                                     $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3832:                                 } else {
 3833:                                     $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3834:                                 }
 3835:                             } elsif ($newval) {
 3836:                                 $newaccesstext->{$tool} = $reqdisplay{$newval};
 3837:                             } else {
 3838:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3839:                             }
 3840:                         } else {
 3841:                             if ($userenv->{$context.'.'.$tool}) {
 3842:                                 $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3843:                             } else {
 3844:                                 $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3845:                             }
 3846:                         }
 3847:                     }
 3848:                 } else {
 3849:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3850:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
 3851:                 }
 3852:             } else {
 3853:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
 3854:                 if ($changed->{$tool}) {
 3855:                     $newaccess->{$tool} = &mt('default');
 3856:                 } else {
 3857:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3858:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3859:                         if ($newval =~ /^autolimit/) {
 3860:                             if ($limit) {
 3861:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3862:                             } else {
 3863:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3864:                             }
 3865:                         } elsif ($newval) {
 3866:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3867:                         } else {
 3868:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3869:                         }
 3870:                     } else {
 3871:                         if ($userenv->{$context.'.'.$tool}) {
 3872:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3873:                         } else {
 3874:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3875:                         }
 3876:                     }
 3877:                 }
 3878:             }
 3879:         } else {
 3880:             $oldaccess->{$tool} = &mt('default');
 3881:             if ($env{'form.custom'.$tool} == 1) {
 3882:                 $changed->{$tool} = &tool_admin($tool,$newval,$changeHash,
 3883:                                                 $context);
 3884:                 if ($changed->{$tool}) {
 3885:                     $newaccess->{$tool} = &mt('custom');
 3886:                     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 3887:                         if ($newval =~ /^autolimit/) {
 3888:                             if ($limit) {
 3889:                                 $newaccesstext->{$tool} = &mt('available with automatic approval, up to limit of [quant,_1,request] per user',$limit);
 3890:                             } else {
 3891:                                 $newaccesstext->{$tool} = &mt('available with automatic approval (unlimited)');
 3892:                             }
 3893:                         } elsif ($newval) {
 3894:                             $newaccesstext->{$tool} = $reqdisplay{$newval};
 3895:                         } else {
 3896:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3897:                         }
 3898:                     } else {
 3899:                         if ($newval) {
 3900:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
 3901:                         } else {
 3902:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
 3903:                         }
 3904:                     }
 3905:                 } else {
 3906:                     $newaccess->{$tool} = $oldaccess->{$tool};
 3907:                 }
 3908:             } else {
 3909:                 $newaccess->{$tool} = $oldaccess->{$tool};
 3910:             }
 3911:         }
 3912:     }
 3913:     return;
 3914: }
 3915: 
 3916: sub update_roles {
 3917:     my ($r,$context,$showcredits) = @_;
 3918:     my $now=time;
 3919:     my @rolechanges;
 3920:     my %disallowed;
 3921:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 3922:     foreach my $key (keys(%env)) {
 3923: 	next if (! $env{$key});
 3924:         next if ($key eq 'form.action');
 3925: 	# Revoke roles
 3926: 	if ($key=~/^form\.rev/) {
 3927: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 3928: # Revoke standard role
 3929: 		my ($scope,$role) = ($1,$2);
 3930: 		my $result =
 3931: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
 3932: 						$env{'form.ccuname'},
 3933: 						$scope,$role,'','',$context);
 3934:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3935:                             &mt('Revoking [_1] in [_2]',
 3936:                                 &Apache::lonnet::plaintext($role),
 3937:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3938:                                 $result ne "ok").'<br />');
 3939:                 if ($result ne "ok") {
 3940:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3941:                 }
 3942: 		if ($role eq 'st') {
 3943: 		    my $result = 
 3944:                         &Apache::lonuserutils::classlist_drop($scope,
 3945:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3946: 			    $now);
 3947:                     $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3948: 		}
 3949:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3950:                     push(@rolechanges,$role);
 3951:                 }
 3952: 	    }
 3953: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
 3954: # Revoke custom role
 3955:                 my $result = &Apache::lonnet::revokecustomrole(
 3956:                     $env{'form.ccdomain'},$env{'form.ccuname'},$1,$2,$3,$4,'','',$context);
 3957:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3958:                             &mt('Revoking custom role [_1] by [_2] in [_3]',
 3959:                                 $4,$3.':'.$2,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 3960:                             $result ne 'ok').'<br />');
 3961:                 if ($result ne "ok") {
 3962:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3963:                 }
 3964:                 if (!grep(/^cr$/,@rolechanges)) {
 3965:                     push(@rolechanges,'cr');
 3966:                 }
 3967: 	    }
 3968: 	} elsif ($key=~/^form\.del/) {
 3969: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 3970: # Delete standard role
 3971: 		my ($scope,$role) = ($1,$2);
 3972: 		my $result =
 3973: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
 3974: 						$env{'form.ccuname'},
 3975: 						$scope,$role,$now,0,1,'',
 3976:                                                 $context);
 3977:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 3978:                             &mt('Deleting [_1] in [_2]',
 3979:                                 &Apache::lonnet::plaintext($role),
 3980:                                 &Apache::loncommon::show_role_extent($scope,$context,$role)),
 3981:                             $result ne 'ok').'<br />');
 3982:                 if ($result ne "ok") {
 3983:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 3984:                 }
 3985: 
 3986: 		if ($role eq 'st') {
 3987: 		    my $result = 
 3988:                         &Apache::lonuserutils::classlist_drop($scope,
 3989:                             $env{'form.ccuname'},$env{'form.ccdomain'},
 3990: 			    $now);
 3991: 		    $r->print(&Apache::lonhtmlcommon::confirm_success($result));
 3992: 		}
 3993:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 3994:                     push(@rolechanges,$role);
 3995:                 }
 3996:             }
 3997: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 3998:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 3999: # Delete custom role
 4000:                 my $result =
 4001:                     &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 4002:                         $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 4003:                         0,1,$context);
 4004:                 $r->print(&Apache::lonhtmlcommon::confirm_success(&mt('Deleting custom role [_1] by [_2] in [_3]',
 4005:                       $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4006:                       $result ne "ok").'<br />');
 4007:                 if ($result ne "ok") {
 4008:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4009:                 }
 4010: 
 4011:                 if (!grep(/^cr$/,@rolechanges)) {
 4012:                     push(@rolechanges,'cr');
 4013:                 }
 4014:             }
 4015: 	} elsif ($key=~/^form\.ren/) {
 4016:             my $udom = $env{'form.ccdomain'};
 4017:             my $uname = $env{'form.ccuname'};
 4018: # Re-enable standard role
 4019: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 4020:                 my $url = $1;
 4021:                 my $role = $2;
 4022:                 my $logmsg;
 4023:                 my $output;
 4024:                 if ($role eq 'st') {
 4025:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 4026:                         my ($cdom,$cnum,$csec) = ($1,$2,$3);
 4027:                         my $credits;
 4028:                         if ($showcredits) {
 4029:                             my $defaultcredits = 
 4030:                                 &Apache::lonuserutils::get_defaultcredits($cdom,$cnum);
 4031:                             $credits = &get_user_credits($defaultcredits,$cdom,$cnum);
 4032:                         }
 4033:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$cdom,$cnum,$csec,$context,$credits);
 4034:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
 4035:                             if ($result eq 'refused' && $logmsg) {
 4036:                                 $output = $logmsg;
 4037:                             } else { 
 4038:                                 $output = &mt('Error: [_1]',$result)."\n";
 4039:                             }
 4040:                         } else {
 4041:                             $output = &Apache::lonhtmlcommon::confirm_success(&mt('Assigning [_1] in [_2] starting [_3]',
 4042:                                         &Apache::lonnet::plaintext($role),
 4043:                                         &Apache::loncommon::show_role_extent($url,$context,'st'),
 4044:                                         &Apache::lonlocal::locallocaltime($now))).'<br />'.$logmsg.'<br />';
 4045:                         }
 4046:                     }
 4047:                 } else {
 4048: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 4049:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
 4050:                                $context);
 4051:                         $output = &Apache::lonhtmlcommon::confirm_success(&mt('Re-enabling [_1] in [_2]',
 4052:                                         &Apache::lonnet::plaintext($role),
 4053:                                         &Apache::loncommon::show_role_extent($url,$context,$role)),$result ne "ok").'<br />';
 4054:                     if ($result ne "ok") {
 4055:                         $output .= &mt('Error: [_1]',$result).'<br />';
 4056:                     }
 4057:                 }
 4058:                 $r->print($output);
 4059:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
 4060:                     push(@rolechanges,$role);
 4061:                 }
 4062: 	    }
 4063: # Re-enable custom role
 4064: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 4065:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 4066:                 my $result = &Apache::lonnet::assigncustomrole(
 4067:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 4068:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
 4069:                 $r->print(&Apache::lonhtmlcommon::confirm_success(
 4070:                     &mt('Re-enabling custom role [_1] by [_2] in [_3]',
 4071:                         $rolename,$rnam.':'.$rdom,&Apache::loncommon::show_role_extent($1,$context,'cr')),
 4072:                     $result ne "ok").'<br />');
 4073:                 if ($result ne "ok") {
 4074:                     $r->print(&mt('Error: [_1]',$result).'<br />');
 4075:                 }
 4076:                 if (!grep(/^cr$/,@rolechanges)) {
 4077:                     push(@rolechanges,'cr');
 4078:                 }
 4079:             }
 4080: 	} elsif ($key=~/^form\.act/) {
 4081:             my $udom = $env{'form.ccdomain'};
 4082:             my $uname = $env{'form.ccuname'};
 4083: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 4084:                 # Activate a custom role
 4085: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 4086: 		my $url='/'.$one.'/'.$two;
 4087: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 4088: 
 4089:                 my $start = ( $env{'form.start_'.$full} ?
 4090:                               $env{'form.start_'.$full} :
 4091:                               $now );
 4092:                 my $end   = ( $env{'form.end_'.$full} ?
 4093:                               $env{'form.end_'.$full} :
 4094:                               0 );
 4095:                                                                                      
 4096:                 # split multiple sections
 4097:                 my %sections = ();
 4098:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 4099:                 if ($num_sections == 0) {
 4100:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
 4101:                 } else {
 4102: 		    my %curr_groups =
 4103: 			&Apache::longroup::coursegroups($one,$two);
 4104:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4105:                         if (($sec eq 'none') || ($sec eq 'all') || 
 4106:                             exists($curr_groups{$sec})) {
 4107:                             $disallowed{$sec} = $url;
 4108:                             next;
 4109:                         }
 4110:                         my $securl = $url.'/'.$sec;
 4111: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
 4112:                     }
 4113:                 }
 4114:                 if (!grep(/^cr$/,@rolechanges)) {
 4115:                     push(@rolechanges,'cr');
 4116:                 }
 4117: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 4118: 		# Activate roles for sections with 3 id numbers
 4119: 		# set start, end times, and the url for the class
 4120: 		my ($one,$two,$three)=($1,$2,$3);
 4121: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 4122: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 4123: 			      $now );
 4124: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 4125: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 4126: 			      0 );
 4127: 		my $url='/'.$one.'/'.$two;
 4128:                 my $type = 'three';
 4129:                 # split multiple sections
 4130:                 my %sections = ();
 4131:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 4132:                 my $credits;
 4133:                 if ($three eq 'st') {
 4134:                     if ($showcredits) { 
 4135:                         my $defaultcredits = 
 4136:                             &Apache::lonuserutils::get_defaultcredits($one,$two);
 4137:                         $credits = $env{'form.credits_'.$one.'_'.$two.'_'.$three};
 4138:                         $credits =~ s/[^\d\.]//g;
 4139:                         if ($credits eq $defaultcredits) {
 4140:                             undef($credits);
 4141:                         }
 4142:                     }
 4143:                 }
 4144:                 if ($num_sections == 0) {
 4145:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4146:                 } else {
 4147:                     my %curr_groups = 
 4148: 			&Apache::longroup::coursegroups($one,$two);
 4149:                     my $emptysec = 0;
 4150:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4151:                         $sec =~ s/\W//g;
 4152:                         if ($sec ne '') {
 4153:                             if (($sec eq 'none') || ($sec eq 'all') || 
 4154:                                 exists($curr_groups{$sec})) {
 4155:                                 $disallowed{$sec} = $url;
 4156:                                 next;
 4157:                             }
 4158:                             my $securl = $url.'/'.$sec;
 4159:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context,$credits));
 4160:                         } else {
 4161:                             $emptysec = 1;
 4162:                         }
 4163:                     }
 4164:                     if ($emptysec) {
 4165:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context,$credits));
 4166:                     }
 4167:                 }
 4168:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
 4169:                     push(@rolechanges,$three);
 4170:                 }
 4171: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 4172: 		# Activate roles for sections with two id numbers
 4173: 		# set start, end times, and the url for the class
 4174: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 4175: 			      $env{'form.start_'.$1.'_'.$2} : 
 4176: 			      $now );
 4177: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 4178: 			      $env{'form.end_'.$1.'_'.$2} :
 4179: 			      0 );
 4180:                 my $one = $1;
 4181:                 my $two = $2;
 4182: 		my $url='/'.$one.'/';
 4183:                 # split multiple sections
 4184:                 my %sections = ();
 4185:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
 4186:                 if ($num_sections == 0) {
 4187:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4188:                 } else {
 4189:                     my $emptysec = 0;
 4190:                     foreach my $sec (sort {$a cmp $b} keys(%sections)) {
 4191:                         if ($sec ne '') {
 4192:                             my $securl = $url.'/'.$sec;
 4193:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
 4194:                         } else {
 4195:                             $emptysec = 1;
 4196:                         }
 4197:                     }
 4198:                     if ($emptysec) {
 4199:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
 4200:                     }
 4201:                 }
 4202:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
 4203:                     push(@rolechanges,$two);
 4204:                 }
 4205: 	    } else {
 4206: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
 4207:             }
 4208:             foreach my $key (sort(keys(%disallowed))) {
 4209:                 $r->print('<p class="LC_warning">');
 4210:                 if (($key eq 'none') || ($key eq 'all')) {  
 4211:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
 4212:                 } else {
 4213:                     $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>'));
 4214:                 }
 4215:                 $r->print('</p><p>'
 4216:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
 4217:                              ,'<a href="javascript:history.go(-1)'
 4218:                              ,'</a>')
 4219:                          .'</p><br />'
 4220:                 );
 4221:             }
 4222: 	}
 4223:     } # End of foreach (keys(%env))
 4224: # Flush the course logs so reverse user roles immediately updated
 4225:     $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
 4226:     if (@rolechanges == 0) {
 4227:         $r->print('<p>'.&mt('No roles to modify').'</p>');
 4228:     }
 4229:     return @rolechanges;
 4230: }
 4231: 
 4232: sub get_user_credits {
 4233:     my ($uname,$udom,$defaultcredits,$cdom,$cnum) = @_;
 4234:     if ($cdom eq '' || $cnum eq '') {
 4235:         return unless ($env{'request.course.id'});
 4236:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4237:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4238:     }
 4239:     my $credits;
 4240:     my %currhash =
 4241:         &Apache::lonnet::get('classlist',[$uname.':'.$udom],$cdom,$cnum);
 4242:     if (keys(%currhash) > 0) {
 4243:         my @items = split(/:/,$currhash{$uname.':'.$udom});
 4244:         my $crdidx = &Apache::loncoursedata::CL_CREDITS() - 3;
 4245:         $credits = $items[$crdidx];
 4246:         $credits =~ s/[^\d\.]//g;
 4247:     }
 4248:     if ($credits eq $defaultcredits) {
 4249:         undef($credits);
 4250:     }
 4251:     return $credits;
 4252: }
 4253: 
 4254: sub enroll_single_student {
 4255:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context,$crstype,
 4256:         $showcredits,$defaultcredits) = @_;
 4257:     $r->print('<h3>');
 4258:     if ($crstype eq 'Community') {
 4259:         $r->print(&mt('Enrolling Member'));
 4260:     } else {
 4261:         $r->print(&mt('Enrolling Student'));
 4262:     }
 4263:     $r->print('</h3>');
 4264: 
 4265:     # Remove non alphanumeric values from section
 4266:     $env{'form.sections'}=~s/\W//g;
 4267: 
 4268:     my $credits;
 4269:     if (($showcredits) && ($env{'form.credits'} ne '')) {
 4270:         $credits = $env{'form.credits'};
 4271:         $credits =~ s/[^\d\.]//g;
 4272:         if ($credits ne '') {
 4273:             if ($credits eq $defaultcredits) {
 4274:                 undef($credits);
 4275:             }
 4276:         }
 4277:     }
 4278: 
 4279:     # Clean out any old student roles the user has in this class.
 4280:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
 4281:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
 4282:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
 4283:     my $enroll_result =
 4284:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
 4285:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
 4286:             $env{'form.cmiddlename'},$env{'form.clastname'},
 4287:             $env{'form.generation'},$env{'form.sections'},$enddate,
 4288:             $startdate,'manual',undef,$env{'request.course.id'},'',$context,
 4289:             $credits);
 4290:     if ($enroll_result =~ /^ok/) {
 4291:         $r->print(&mt('[_1] enrolled','<b>'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.'</b>'));
 4292:         if ($env{'form.sections'} ne '') {
 4293:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
 4294:         }
 4295:         my ($showstart,$showend);
 4296:         if ($startdate <= $now) {
 4297:             $showstart = &mt('Access starts immediately');
 4298:         } else {
 4299:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
 4300:         }
 4301:         if ($enddate == 0) {
 4302:             $showend = &mt('ends: no ending date');
 4303:         } else {
 4304:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
 4305:         }
 4306:         $r->print('.<br />'.$showstart.'; '.$showend);
 4307:         if ($startdate <= $now && !$newuser) {
 4308:             $r->print('<p class="LC_info">');
 4309:             if ($crstype eq 'Community') {
 4310:                 $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.'));
 4311:             } else {
 4312:                 $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.'));
 4313:            }
 4314:            $r->print('</p>');
 4315:         }
 4316:     } else {
 4317:         $r->print(&mt('unable to enroll').": ".$enroll_result);
 4318:     }
 4319:     return;
 4320: }
 4321: 
 4322: sub get_defaultquota_text {
 4323:     my ($settingstatus) = @_;
 4324:     my $defquotatext; 
 4325:     if ($settingstatus eq '') {
 4326:         $defquotatext = &mt('default');
 4327:     } else {
 4328:         my ($usertypes,$order) =
 4329:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 4330:         if ($usertypes->{$settingstatus} eq '') {
 4331:             $defquotatext = &mt('default');
 4332:         } else {
 4333:             $defquotatext = &mt('default for [_1]',$usertypes->{$settingstatus});
 4334:         }
 4335:     }
 4336:     return $defquotatext;
 4337: }
 4338: 
 4339: sub update_result_form {
 4340:     my ($uhome) = @_;
 4341:     my $outcome = 
 4342:     '<form name="userupdate" method="post" action="">'."\n";
 4343:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 4344:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4345:     }
 4346:     if ($env{'form.origname'} ne '') {
 4347:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
 4348:     }
 4349:     foreach my $item ('sortby','seluname','seludom') {
 4350:         if (exists($env{'form.'.$item})) {
 4351:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
 4352:         }
 4353:     }
 4354:     if ($uhome eq 'no_host') {
 4355:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
 4356:     }
 4357:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
 4358:                 '<input type="hidden" name="currstate" value="" />'."\n".
 4359:                 '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 4360:                 '</form>';
 4361:     return $outcome;
 4362: }
 4363: 
 4364: sub quota_admin {
 4365:     my ($setquota,$changeHash,$name) = @_;
 4366:     my $quotachanged;
 4367:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 4368:         # Current user has quota modification privileges
 4369:         if (ref($changeHash) eq 'HASH') {
 4370:             $quotachanged = 1;
 4371:             $changeHash->{$name.'quota'} = $setquota;
 4372:         }
 4373:     }
 4374:     return $quotachanged;
 4375: }
 4376: 
 4377: sub tool_admin {
 4378:     my ($tool,$settool,$changeHash,$context) = @_;
 4379:     my $canchange = 0; 
 4380:     if ($context eq 'requestcourses') {
 4381:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
 4382:             $canchange = 1;
 4383:         }
 4384:     } elsif ($context eq 'reqcrsotherdom') {
 4385:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
 4386:             $canchange = 1;
 4387:         }
 4388:     } elsif ($context eq 'requestauthor') {
 4389:         if (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) {
 4390:             $canchange = 1;
 4391:         }
 4392:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
 4393:         # Current user has quota modification privileges
 4394:         $canchange = 1;
 4395:     }
 4396:     my $toolchanged;
 4397:     if ($canchange) {
 4398:         if (ref($changeHash) eq 'HASH') {
 4399:             $toolchanged = 1;
 4400:             if ($tool eq 'requestauthor') {
 4401:                 $changeHash->{$context} = $settool;
 4402:             } else {
 4403:                 $changeHash->{$context.'.'.$tool} = $settool;
 4404:             }
 4405:         }
 4406:     }
 4407:     return $toolchanged;
 4408: }
 4409: 
 4410: sub build_roles {
 4411:     my ($sectionstr,$sections,$role) = @_;
 4412:     my $num_sections = 0;
 4413:     if ($sectionstr=~ /,/) {
 4414:         my @secnums = split/,/,$sectionstr;
 4415:         if ($role eq 'st') {
 4416:             $secnums[0] =~ s/\W//g;
 4417:             $$sections{$secnums[0]} = 1;
 4418:             $num_sections = 1;
 4419:         } else {
 4420:             foreach my $sec (@secnums) {
 4421:                 $sec =~ ~s/\W//g;
 4422:                 if (!($sec eq "")) {
 4423:                     if (exists($$sections{$sec})) {
 4424:                         $$sections{$sec} ++;
 4425:                     } else {
 4426:                         $$sections{$sec} = 1;
 4427:                         $num_sections ++;
 4428:                     }
 4429:                 }
 4430:             }
 4431:         }
 4432:     } else {
 4433:         $sectionstr=~s/\W//g;
 4434:         unless ($sectionstr eq '') {
 4435:             $$sections{$sectionstr} = 1;
 4436:             $num_sections ++;
 4437:         }
 4438:     }
 4439: 
 4440:     return $num_sections;
 4441: }
 4442: 
 4443: # ========================================================== Custom Role Editor
 4444: 
 4445: sub custom_role_editor {
 4446:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4447:     my $action = $env{'form.customroleaction'};
 4448:     my ($rolename,$helpitem);
 4449:     if ($action eq 'new') {
 4450:         $rolename=$env{'form.newrolename'};
 4451:     } else {
 4452:         $rolename=$env{'form.rolename'};
 4453:     }
 4454: 
 4455:     my ($crstype,$context);
 4456:     if ($env{'request.course.id'}) {
 4457:         $crstype = &Apache::loncommon::course_type();
 4458:         $context = 'course';
 4459:         $helpitem = 'Course_Editing_Custom_Roles';
 4460:     } else {
 4461:         $context = 'domain';
 4462:         $crstype = 'course';
 4463:         $helpitem = 'Domain_Editing_Custom_Roles';
 4464:     }
 4465: 
 4466:     $rolename=~s/[^A-Za-z0-9]//gs;
 4467:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 4468: 	&print_username_entry_form($r,$context,undef,undef,undef,$crstype,$brcrum,
 4469:                                    $permission);
 4470:         return;
 4471:     }
 4472: 
 4473:     my $formname = 'form1';
 4474:     my %privs=();
 4475:     my $body_top = '<h2>';
 4476: # ------------------------------------------------------- Does this role exist?
 4477:     my ($rdummy,$roledef)=
 4478: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4479:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4480:         $body_top .= &mt('Existing Role').' "';
 4481: # ------------------------------------------------- Get current role privileges
 4482:         ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
 4483:         if ($privs{'system'} =~ /bre\&S/) {
 4484:             if ($context eq 'domain') {
 4485:                 $crstype = 'Course';
 4486:             } elsif ($crstype eq 'Community') {
 4487:                 $privs{'system'} =~ s/bre\&S//;
 4488:             }
 4489:         } elsif ($context eq 'domain') {
 4490:             $crstype = 'Course';
 4491:         }
 4492:     } else {
 4493:         $body_top .= &mt('New Role').' "';
 4494:         $roledef='';
 4495:     }
 4496:     $body_top .= $rolename.'"</h2>';
 4497: 
 4498: # ------------------------------------------------------- What can be assigned?
 4499:     my %full=();
 4500:     my %levels=(
 4501:                  course => {},
 4502:                  domain => {},
 4503:                  system => {},
 4504:                );
 4505:     my %levelscurrent=(
 4506:                         course => {},
 4507:                         domain => {},
 4508:                         system => {},
 4509:                       );
 4510:     &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4511:     my ($jsback,$elements) = &crumb_utilities();
 4512:     my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4513:     my $head_script =
 4514:         &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
 4515:                                                   \%full,\@templateroles,$jsback);
 4516:     push (@{$brcrum},
 4517:               {href => "javascript:backPage(document.$formname,'pickrole','')",
 4518:                text => "Pick custom role",
 4519:                faq  => 282,bug=>'Instructor Interface',},
 4520:               {href => "javascript:backPage(document.$formname,'','')",
 4521:                text => "Edit custom role",
 4522:                faq  => 282,
 4523:                bug  => 'Instructor Interface',
 4524:                help => $helpitem}
 4525:               );
 4526:     my $args = { bread_crumbs          => $brcrum,
 4527:                  bread_crumbs_component => 'User Management'};
 4528:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
 4529:                                              $head_script,$args).
 4530:               $body_top);
 4531:     $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
 4532:               &Apache::lonuserutils::custom_role_header($context,$crstype,
 4533:                                                         \@templateroles,$prefix));
 4534: 
 4535:     $r->print(<<ENDCCF);
 4536: <input type="hidden" name="phase" value="set_custom_roles" />
 4537: <input type="hidden" name="rolename" value="$rolename" />
 4538: ENDCCF
 4539:     $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4540:                                                        \%levelscurrent,$prefix));
 4541:     $r->print(&Apache::loncommon::end_data_table().
 4542:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
 4543:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 4544:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".
 4545:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 4546:    '<input type="submit" value="'.&mt('Save').'" /></form>');
 4547: }
 4548: 
 4549: # ---------------------------------------------------------- Call to definerole
 4550: sub set_custom_role {
 4551:     my ($r,$context,$brcrum,$prefix,$permission) = @_;
 4552:     my $rolename=$env{'form.rolename'};
 4553:     $rolename=~s/[^A-Za-z0-9]//gs;
 4554:     if (!$rolename) {
 4555: 	&custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4556:         return;
 4557:     }
 4558:     my ($jsback,$elements) = &crumb_utilities();
 4559:     my $jscript = '<script type="text/javascript">'
 4560:                  .'// <![CDATA['."\n"
 4561:                  .$jsback."\n"
 4562:                  .'// ]]>'."\n"
 4563:                  .'</script>'."\n";
 4564:     my $helpitem = 'Course_Editing_Custom_Roles';
 4565:     if ($context eq 'domain') {
 4566:         $helpitem = 'Domain_Editing_Custom_Roles';
 4567:     }
 4568:     push(@{$brcrum},
 4569:         {href => "javascript:backPage(document.customresult,'pickrole','')",
 4570:          text => "Pick custom role",
 4571:          faq  => 282,
 4572:          bug  => 'Instructor Interface',},
 4573:         {href => "javascript:backPage(document.customresult,'selected_custom_edit','')",
 4574:          text => "Edit custom role",
 4575:          faq  => 282,
 4576:          bug  => 'Instructor Interface',},
 4577:         {href => "javascript:backPage(document.customresult,'set_custom_roles','')",
 4578:          text => "Result",
 4579:          faq  => 282,
 4580:          bug  => 'Instructor Interface',
 4581:          help => $helpitem,}
 4582:         );
 4583:     my $args = { bread_crumbs           => $brcrum,
 4584:                  bread_crumbs_component => 'User Management'};
 4585:     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 4586: 
 4587:     my $newrole;
 4588:     my ($rdummy,$roledef)=
 4589: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 4590: 
 4591: # ------------------------------------------------------- Does this role exist?
 4592:     $r->print('<h3>');
 4593:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4594: 	$r->print(&mt('Existing Role').' "');
 4595:     } else {
 4596: 	$r->print(&mt('New Role').' "');
 4597: 	$roledef='';
 4598:         $newrole = 1;
 4599:     }
 4600:     $r->print($rolename.'"</h3>');
 4601: # ------------------------------------------------- Assign role and show result
 4602: 
 4603:     my $errmsg;
 4604:     my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
 4605:     # Assign role and return result
 4606:     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
 4607:                                              $newprivs{'c'});
 4608:     if ($result ne 'ok') {
 4609:         $errmsg = ': '.$result;
 4610:     }
 4611:     my $message =
 4612:         &Apache::lonhtmlcommon::confirm_success(
 4613:             &mt('Defining Role').$errmsg, ($result eq 'ok' ? 0 : 1));
 4614:     if ($env{'request.course.id'}) {
 4615:         my $url='/'.$env{'request.course.id'};
 4616:         $url=~s/\_/\//g;
 4617:         $result =
 4618:             &Apache::lonnet::assigncustomrole(
 4619:                 $env{'user.domain'},$env{'user.name'},
 4620:                 $url,
 4621:                 $env{'user.domain'},$env{'user.name'},
 4622:                 $rolename,undef,undef,undef,$context);
 4623:         if ($result ne 'ok') {
 4624:             $errmsg = ': '.$result;
 4625:         }
 4626:         $message .=
 4627:             '<br />'
 4628:            .&Apache::lonhtmlcommon::confirm_success(
 4629:                 &mt('Assigning Role to Self').$errmsg, ($result eq 'ok' ? 0 : 1));
 4630:     }
 4631:     $r->print(
 4632:         &Apache::loncommon::confirmwrapper($message)
 4633:        .'<br />'
 4634:        .&Apache::lonhtmlcommon::actionbox([
 4635:             '<a href="javascript:backPage(document.customresult,'."'pickrole'".')">'
 4636:            .&mt('Create or edit another custom role')
 4637:            .'</a>'])
 4638:        .'<form name="customresult" method="post" action="">'
 4639:        .&Apache::lonhtmlcommon::echo_form_input([])
 4640:        .'</form>'
 4641:     );
 4642: }
 4643: 
 4644: # ================================================================ Main Handler
 4645: sub handler {
 4646:     my $r = shift;
 4647:     if ($r->header_only) {
 4648:        &Apache::loncommon::content_type($r,'text/html');
 4649:        $r->send_http_header;
 4650:        return OK;
 4651:     }
 4652:     my ($context,$crstype,$cid,$cnum,$cdom,$allhelpitems);
 4653: 
 4654:     if ($env{'request.course.id'}) {
 4655:         $context = 'course';
 4656:         $crstype = &Apache::loncommon::course_type();
 4657:     } elsif ($env{'request.role'} =~ /^au\./) {
 4658:         $context = 'author';
 4659:     } else {
 4660:         $context = 'domain';
 4661:     }
 4662: 
 4663:     my ($permission,$allowed) =
 4664:         &Apache::lonuserutils::get_permission($context,$crstype);
 4665: 
 4666:     if ($allowed) {
 4667:         my @allhelp;
 4668:         if ($context eq 'course') {
 4669:             $cid = $env{'request.course.id'};
 4670:             $cdom = $env{'course.'.$cid.'.domain'};
 4671:             $cnum = $env{'course.'.$cid.'.num'};
 4672: 
 4673:             if ($permission->{'cusr'}) {
 4674:                 push(@allhelp,'Course_Create_Class_List');
 4675:             }
 4676:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4677:                 push(@allhelp,('Course_Change_Privileges','Course_View_Class_List'));
 4678:             }
 4679:             if ($permission->{'custom'}) {
 4680:                 push(@allhelp,'Course_Editing_Custom_Roles');
 4681:             }
 4682:             if ($permission->{'cusr'}) {
 4683:                 push(@allhelp,('Course_Add_Student','Course_Drop_Student'));
 4684:             }
 4685:             unless ($permission->{'cusr_section'}) {
 4686:                 if (&Apache::lonnet::auto_run($cnum,$cdom) && (($permission->{'cusr'}) || ($permission->{'view'}))) {
 4687:                     push(@allhelp,'Course_Automated_Enrollment');
 4688:                 }
 4689:                 if ($permission->{'selfenrolladmin'}) {
 4690:                     push(@allhelp,'Course_Approve_Selfenroll');
 4691:                 }
 4692:             }
 4693:             if ($permission->{'grp_manage'}) {
 4694:                 push(@allhelp,'Course_Manage_Group');
 4695:             }
 4696:             if ($permission->{'view'} || $permission->{'cusr'}) {
 4697:                 push(@allhelp,'Course_User_Logs');
 4698:             }
 4699:         } elsif ($context eq 'author') {
 4700:             push(@allhelp,('Author_Change_Privileges','Author_Create_Coauthor_List',
 4701:                            'Author_View_Coauthor_List','Author_User_Logs'));
 4702:         } else {
 4703:             if ($permission->{'cusr'}) {
 4704:                 push(@allhelp,'Domain_Change_Privileges');
 4705:                 if ($permission->{'activity'}) {
 4706:                     push(@allhelp,'Domain_User_Access_Logs');
 4707:                 }
 4708:                 push(@allhelp,('Domain_Create_Users','Domain_View_Users_List'));
 4709:                 if ($permission->{'custom'}) {
 4710:                     push(@allhelp,'Domain_Editing_Custom_Roles');
 4711:                 }
 4712:                 push(@allhelp,('Domain_Role_Approvals','Domain_Username_Approvals','Domain_Change_Logs'));
 4713:             } elsif ($permission->{'view'}) {
 4714:                 push(@allhelp,'Domain_View_Privileges');
 4715:                 if ($permission->{'activity'}) {
 4716:                     push(@allhelp,'Domain_User_Access_Logs');
 4717:                 }
 4718:                 push(@allhelp,('Domain_View_Users_List','Domain_Change_Logs'));
 4719:             }
 4720:         }
 4721:         if (@allhelp) {
 4722:             $allhelpitems = join(',',@allhelp);
 4723:         }
 4724:     }
 4725: 
 4726:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4727:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
 4728:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype','queue']);
 4729:     &Apache::lonhtmlcommon::clear_breadcrumbs();
 4730:     my $args;
 4731:     my $brcrum = [];
 4732:     my $bread_crumbs_component = 'User Management';
 4733:     if (($env{'form.action'} ne 'dateselect') && ($env{'form.action'} ne 'displayuserreq')) {
 4734:         $brcrum = [{href=>"/adm/createuser",
 4735:                     text=>"User Management",
 4736:                     help=>$allhelpitems}
 4737:                   ];
 4738:     }
 4739:     if (!$allowed) {
 4740:         if ($context eq 'course') {
 4741:             $r->internal_redirect('/adm/viewclasslist');
 4742:             return OK;
 4743:         }
 4744:         $env{'user.error.msg'}=
 4745:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
 4746:                                  "or view user status.";
 4747:         return HTTP_NOT_ACCEPTABLE;
 4748:     }
 4749: 
 4750:     &Apache::loncommon::content_type($r,'text/html');
 4751:     $r->send_http_header;
 4752: 
 4753:     my $showcredits;
 4754:     if ((($context eq 'course') && ($crstype eq 'Course')) || 
 4755:          ($context eq 'domain')) {
 4756:         my %domdefaults = 
 4757:             &Apache::lonnet::get_domain_defaults($env{'request.role.domain'});
 4758:         if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'}) {
 4759:             $showcredits = 1;
 4760:         }
 4761:     }
 4762: 
 4763:     # Main switch on form.action and form.state, as appropriate
 4764:     if (! exists($env{'form.action'})) {
 4765:         $args = {bread_crumbs => $brcrum,
 4766:                  bread_crumbs_component => $bread_crumbs_component}; 
 4767:         $r->print(&header(undef,$args));
 4768:         $r->print(&print_main_menu($permission,$context,$crstype));
 4769:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
 4770:         my $helpitem = 'Course_Create_Class_List';
 4771:         if ($context eq 'author') {
 4772:             $helpitem = 'Author_Create_Coauthor_List';
 4773:         } elsif ($context eq 'domain') {
 4774:             $helpitem = 'Domain_Create_Users';
 4775:         }
 4776:         push(@{$brcrum},
 4777:               { href => '/adm/createuser?action=upload&state=',
 4778:                 text => 'Upload Users List',
 4779:                 help => $helpitem,
 4780:               });
 4781:         $bread_crumbs_component = 'Upload Users List';
 4782:         $args = {bread_crumbs           => $brcrum,
 4783:                  bread_crumbs_component => $bread_crumbs_component};
 4784:         $r->print(&header(undef,$args));
 4785:         $r->print('<form name="studentform" method="post" '.
 4786:                   'enctype="multipart/form-data" '.
 4787:                   ' action="/adm/createuser">'."\n");
 4788:         if (! exists($env{'form.state'})) {
 4789:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4790:         } elsif ($env{'form.state'} eq 'got_file') {
 4791:             my $result = 
 4792:                 &Apache::lonuserutils::print_upload_manager_form($r,$context,
 4793:                                                                  $permission,
 4794:                                                                  $crstype,$showcredits);
 4795:             if ($result eq 'missingdata') {
 4796:                 delete($env{'form.state'});
 4797:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4798:             }
 4799:         } elsif ($env{'form.state'} eq 'enrolling') {
 4800:             if ($env{'form.datatoken'}) {
 4801:                 my $result = &Apache::lonuserutils::upfile_drop_add($r,$context,
 4802:                                                                     $permission,
 4803:                                                                     $showcredits);
 4804:                 if ($result eq 'missingdata') {
 4805:                     delete($env{'form.state'});
 4806:                     &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4807:                 } elsif ($result eq 'invalidhome') {
 4808:                     $env{'form.state'} = 'got_file';
 4809:                     delete($env{'form.lcserver'});
 4810:                     my $result =
 4811:                         &Apache::lonuserutils::print_upload_manager_form($r,$context,$permission,
 4812:                                                                          $crstype,$showcredits);
 4813:                     if ($result eq 'missingdata') {
 4814:                         delete($env{'form.state'});
 4815:                         &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4816:                     }
 4817:                 }
 4818:             } else {
 4819:                 delete($env{'form.state'});
 4820:                 &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4821:             }
 4822:         } else {
 4823:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
 4824:         }
 4825:         $r->print('</form>');
 4826:     } elsif (((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
 4827:               eq 'singlestudent')) && ($permission->{'cusr'})) ||
 4828:              (($env{'form.action'} eq 'singleuser') && ($permission->{'view'})) ||
 4829:              (($env{'form.action'} eq 'accesslogs') && ($permission->{'activity'}))) {
 4830:         my $phase = $env{'form.phase'};
 4831:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 4832: 	&Apache::loncreateuser::restore_prev_selections();
 4833: 	my $srch;
 4834: 	foreach my $item (@search) {
 4835: 	    $srch->{$item} = $env{'form.'.$item};
 4836: 	}
 4837:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
 4838:             ($phase eq 'createnewuser') || ($phase eq 'activity')) {
 4839:             if ($env{'form.phase'} eq 'createnewuser') {
 4840:                 my $response;
 4841:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
 4842:                     my $response =
 4843:                         '<span class="LC_warning">'
 4844:                        .&mt('You must specify a valid username. Only the following are allowed:'
 4845:                            .' letters numbers - . @')
 4846:                        .'</span>';
 4847:                     $env{'form.phase'} = '';
 4848:                     &print_username_entry_form($r,$context,$response,$srch,undef,
 4849:                                                $crstype,$brcrum,$permission);
 4850:                 } else {
 4851:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
 4852:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
 4853:                     &print_user_modification_page($r,$ccuname,$ccdomain,
 4854:                                                   $srch,$response,$context,
 4855:                                                   $permission,$crstype,$brcrum,
 4856:                                                   $showcredits);
 4857:                 }
 4858:             } elsif ($env{'form.phase'} eq 'get_user_info') {
 4859:                 my ($currstate,$response,$forcenewuser,$results) = 
 4860:                     &user_search_result($context,$srch);
 4861:                 if ($env{'form.currstate'} eq 'modify') {
 4862:                     $currstate = $env{'form.currstate'};
 4863:                 }
 4864:                 if ($currstate eq 'select') {
 4865:                     &print_user_selection_page($r,$response,$srch,$results,
 4866:                                                \@search,$context,undef,$crstype,
 4867:                                                $brcrum);
 4868:                 } elsif (($currstate eq 'modify') || ($env{'form.action'} eq 'accesslogs')) {
 4869:                     my ($ccuname,$ccdomain,$uhome);
 4870:                     if (($srch->{'srchby'} eq 'uname') && 
 4871:                         ($srch->{'srchtype'} eq 'exact')) {
 4872:                         $ccuname = $srch->{'srchterm'};
 4873:                         $ccdomain= $srch->{'srchdomain'};
 4874:                     } else {
 4875:                         my @matchedunames = keys(%{$results});
 4876:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 4877:                     }
 4878:                     $ccuname =&LONCAPA::clean_username($ccuname);
 4879:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
 4880:                     if ($env{'form.action'} eq 'accesslogs') {
 4881:                         my $uhome;
 4882:                         if (($ccuname ne '') && ($ccdomain ne '')) {
 4883:                            $uhome = &Apache::lonnet::homeserver($ccuname,$ccdomain);
 4884:                         }
 4885:                         if (($uhome eq '') || ($uhome eq 'no_host')) {
 4886:                             $env{'form.phase'} = '';
 4887:                             undef($forcenewuser);
 4888:                             #if ($response) {
 4889:                             #    unless ($response =~ m{\Q<br /><br />\E$}) {
 4890:                             #        $response .= '<br /><br />';
 4891:                             #    }
 4892:                             #}
 4893:                             &print_username_entry_form($r,$context,$response,$srch,
 4894:                                                        $forcenewuser,$crstype,$brcrum,
 4895:                                                        $permission);
 4896:                         } else {
 4897:                             &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4898:                         }
 4899:                     } else {
 4900:                         if ($env{'form.forcenewuser'}) {
 4901:                             $response = '';
 4902:                         }
 4903:                         &print_user_modification_page($r,$ccuname,$ccdomain,
 4904:                                                       $srch,$response,$context,
 4905:                                                       $permission,$crstype,$brcrum);
 4906:                     }
 4907:                 } elsif ($currstate eq 'query') {
 4908:                     &print_user_query_page($r,'createuser',$brcrum);
 4909:                 } else {
 4910:                     $env{'form.phase'} = '';
 4911:                     &print_username_entry_form($r,$context,$response,$srch,
 4912:                                                $forcenewuser,$crstype,$brcrum,
 4913:                                                $permission);
 4914:                 }
 4915:             } elsif ($env{'form.phase'} eq 'userpicked') {
 4916:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 4917:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 4918:                 if ($env{'form.action'} eq 'accesslogs') {
 4919:                     &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4920:                 } else {
 4921:                     &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
 4922:                                                   $context,$permission,$crstype,
 4923:                                                   $brcrum);
 4924:                 }
 4925:             } elsif ($env{'form.action'} eq 'accesslogs') {
 4926:                 my $ccuname = &LONCAPA::clean_username($env{'form.accessuname'});
 4927:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.accessudom'});
 4928:                 &print_useraccesslogs_display($r,$ccuname,$ccdomain,$permission,$brcrum);
 4929:             }
 4930:         } elsif ($env{'form.phase'} eq 'update_user_data') {
 4931:             &update_user_data($r,$context,$crstype,$brcrum,$showcredits);
 4932:         } else {
 4933:             &print_username_entry_form($r,$context,undef,$srch,undef,$crstype,
 4934:                                        $brcrum,$permission);
 4935:         }
 4936:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
 4937:         my $prefix;
 4938:         if ($env{'form.phase'} eq 'set_custom_roles') {
 4939:             &set_custom_role($r,$context,$brcrum,$prefix,$permission);
 4940:         } else {
 4941:             &custom_role_editor($r,$context,$brcrum,$prefix,$permission);
 4942:         }
 4943:     } elsif (($env{'form.action'} eq 'processauthorreq') &&
 4944:              ($permission->{'cusr'}) && 
 4945:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4946:         push(@{$brcrum},
 4947:                  {href => '/adm/createuser?action=processauthorreq',
 4948:                   text => 'Authoring Space requests',
 4949:                   help => 'Domain_Role_Approvals'});
 4950:         $bread_crumbs_component = 'Authoring requests';
 4951:         if ($env{'form.state'} eq 'done') {
 4952:             push(@{$brcrum},
 4953:                      {href => '/adm/createuser?action=authorreqqueue',
 4954:                       text => 'Result',
 4955:                       help => 'Domain_Role_Approvals'});
 4956:             $bread_crumbs_component = 'Authoring request result';
 4957:         }
 4958:         $args = { bread_crumbs           => $brcrum,
 4959:                   bread_crumbs_component => $bread_crumbs_component};
 4960:         my $js = &usernamerequest_javascript();
 4961:         $r->print(&header(&add_script($js),$args));
 4962:         if (!exists($env{'form.state'})) {
 4963:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestauthor',
 4964:                                                                             $env{'request.role.domain'}));
 4965:         } elsif ($env{'form.state'} eq 'done') {
 4966:             $r->print('<h3>'.&mt('Authoring request processing').'</h3>'."\n");
 4967:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestauthor',
 4968:                                                                          $env{'request.role.domain'}));
 4969:         }
 4970:     } elsif (($env{'form.action'} eq 'processusernamereq') &&
 4971:              ($permission->{'cusr'}) &&
 4972:              (&Apache::lonnet::allowed('cau',$env{'request.role.domain'}))) {
 4973:         push(@{$brcrum},
 4974:                  {href => '/adm/createuser?action=processusernamereq',
 4975:                   text => 'LON-CAPA account requests',
 4976:                   help => 'Domain_Username_Approvals'});
 4977:         $bread_crumbs_component = 'Account requests';
 4978:         if ($env{'form.state'} eq 'done') {
 4979:             push(@{$brcrum},
 4980:                      {href => '/adm/createuser?action=usernamereqqueue',
 4981:                       text => 'Result',
 4982:                       help => 'Domain_Username_Approvals'});
 4983:             $bread_crumbs_component = 'LON-CAPA account request result';
 4984:         }
 4985:         $args = { bread_crumbs           => $brcrum,
 4986:                   bread_crumbs_component => $bread_crumbs_component};
 4987:         my $js = &usernamerequest_javascript();
 4988:         $r->print(&header(&add_script($js),$args));
 4989:         if (!exists($env{'form.state'})) {
 4990:             $r->print(&Apache::loncoursequeueadmin::display_queued_requests('requestusername',
 4991:                                                                             $env{'request.role.domain'}));
 4992:         } elsif ($env{'form.state'} eq 'done') {
 4993:             $r->print('<h3>'.&mt('LON-CAPA account request processing').'</h3>'."\n");
 4994:             $r->print(&Apache::loncoursequeueadmin::update_request_queue('requestusername',
 4995:                                                                          $env{'request.role.domain'}));
 4996:         }
 4997:     } elsif (($env{'form.action'} eq 'displayuserreq') &&
 4998:              ($permission->{'cusr'})) {
 4999:         my $dom = $env{'form.domain'};
 5000:         my $uname = $env{'form.username'};
 5001:         my $warning;
 5002:         if (($dom =~ /^$match_domain$/) && (&Apache::lonnet::domain($dom) ne '')) {
 5003:             if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 5004:                 if (($uname =~ /^$match_username$/) && ($env{'form.queue'} eq 'approval')) {
 5005:                     my $uhome = &Apache::lonnet::homeserver($uname,$dom);
 5006:                     if ($uhome eq 'no_host') {
 5007:                         my $queue = $env{'form.queue'};
 5008:                         my $reqkey = &escape($uname).'_'.$queue; 
 5009:                         my $namespace = 'usernamequeue';
 5010:                         my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 5011:                         my %queued =
 5012:                             &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 5013:                         unless ($queued{$reqkey}) {
 5014:                             $warning = &mt('No information was found for this LON-CAPA account request.');
 5015:                         }
 5016:                     } else {
 5017:                         $warning = &mt('A LON-CAPA account already exists for the requested username and domain.');
 5018:                     }
 5019:                 } else {
 5020:                     $warning = &mt('LON-CAPA account request status check is for an invalid username.');
 5021:                 }
 5022:             } else {
 5023:                 $warning = &mt('You do not have rights to view LON-CAPA account requests in the domain specified.');
 5024:             }
 5025:         } else {
 5026:             $warning = &mt('LON-CAPA account request status check is for an invalid domain.');
 5027:         }
 5028:         my $args = { only_body => 1 };
 5029:         $r->print(&header(undef,$args).
 5030:                   '<h3>'.&mt('LON-CAPA Account Request Details').'</h3>');
 5031:         if ($warning ne '') {
 5032:             $r->print('<div class="LC_warning">'.$warning.'</div>');
 5033:         } else {
 5034:             my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 5035:             my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 5036:             my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 5037:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
 5038:                 if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
 5039:                     if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}) eq 'HASH') {
 5040:                         my %info =
 5041:                             &Apache::lonnet::get('nohist_requestedusernames',[$uname],$dom,$domconfiguser);
 5042:                         if (ref($info{$uname}) eq 'HASH') {
 5043:                             my $usertype = $info{$uname}{'inststatus'};
 5044:                             unless ($usertype) {
 5045:                                 $usertype = 'default';
 5046:                             }
 5047:                             my ($showstatus,$showemail,$pickstart);
 5048:                             my $numextras = 0;
 5049:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 5050:                             if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
 5051:                                 if (ref($usertypes) eq 'HASH') {
 5052:                                     if ($usertypes->{$usertype}) {
 5053:                                         $showstatus = $usertypes->{$usertype};
 5054:                                     } else {
 5055:                                         $showstatus = $othertitle;
 5056:                                     }
 5057:                                     if ($showstatus) {
 5058:                                         $numextras ++;
 5059:                                     }
 5060:                                 }
 5061:                             }
 5062:                             if (($info{$uname}{'email'} ne '') && ($info{$uname}{'email'} ne $uname)) {
 5063:                                 $showemail = $info{$uname}{'email'};
 5064:                                 $numextras ++;
 5065:                             }
 5066:                             if (ref($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}) eq 'HASH') {
 5067:                                 if ((ref($infofields) eq 'ARRAY') && (ref($infotitles) eq 'HASH')) {
 5068:                                     $pickstart = 1;
 5069:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5070:                                     my ($num,$count);
 5071:                                     $count = scalar(keys(%{$domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}}));
 5072:                                     $count += $numextras;
 5073:                                     foreach my $field (@{$infofields}) {
 5074:                                         next unless ($domconfig{'usercreation'}{'cancreate'}{'emailusername'}{$usertype}{$field});
 5075:                                         next unless ($infotitles->{$field});
 5076:                                         $r->print(&Apache::lonhtmlcommon::row_title($infotitles->{$field}).
 5077:                                                   $info{$uname}{$field});
 5078:                                         $num ++;
 5079:                                         unless ($count == $num) {
 5080:                                             $r->print(&Apache::lonhtmlcommon::row_closure());
 5081:                                         }
 5082:                                     }
 5083:                                 }
 5084:                             }
 5085:                             if ($numextras) {
 5086:                                 unless ($pickstart) {
 5087:                                     $r->print('<div>'.&Apache::lonhtmlcommon::start_pick_box());
 5088:                                     $pickstart = 1;
 5089:                                 }
 5090:                                 if ($showemail) {
 5091:                                     my $closure = '';
 5092:                                     unless ($showstatus) {
 5093:                                         $closure = 1;
 5094:                                     }
 5095:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('E-mail address')).
 5096:                                               $showemail.
 5097:                                               &Apache::lonhtmlcommon::row_closure($closure));
 5098:                                 }
 5099:                                 if ($showstatus) {
 5100:                                     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Status type[_1](self-reported)','<br />')).
 5101:                                               $showstatus.
 5102:                                               &Apache::lonhtmlcommon::row_closure(1));
 5103:                                 }
 5104:                             }
 5105:                             if ($pickstart) { 
 5106:                                 $r->print(&Apache::lonhtmlcommon::end_pick_box().'</div>');
 5107:                             } else {
 5108:                                 $r->print('<div>'.&mt('No information to display for this account request.').'</div>');
 5109:                             }
 5110:                         } else {
 5111:                             $r->print('<div>'.&mt('No information available for this account request.').'</div>');
 5112:                         }
 5113:                     }
 5114:                 }
 5115:             }
 5116:         }
 5117:         $r->print(&close_popup_form());
 5118:     } elsif (($env{'form.action'} eq 'listusers') && 
 5119:              ($permission->{'view'} || $permission->{'cusr'})) {
 5120:         my $helpitem = 'Course_View_Class_List';
 5121:         if ($context eq 'author') {
 5122:             $helpitem = 'Author_View_Coauthor_List';
 5123:         } elsif ($context eq 'domain') {
 5124:             $helpitem = 'Domain_View_Users_List';
 5125:         }
 5126:         if ($env{'form.phase'} eq 'bulkchange') {
 5127:             push(@{$brcrum},
 5128:                     {href => '/adm/createuser?action=listusers',
 5129:                      text => "List Users"},
 5130:                     {href => "/adm/createuser",
 5131:                      text => "Result",
 5132:                      help => $helpitem});
 5133:             $bread_crumbs_component = 'Update Users';
 5134:             $args = {bread_crumbs           => $brcrum,
 5135:                      bread_crumbs_component => $bread_crumbs_component};
 5136:             $r->print(&header(undef,$args));
 5137:             my $setting = $env{'form.roletype'};
 5138:             my $choice = $env{'form.bulkaction'};
 5139:             if ($permission->{'cusr'}) {
 5140:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice,$crstype);
 5141:             } else {
 5142:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
 5143:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
 5144:             }
 5145:         } else {
 5146:             push(@{$brcrum},
 5147:                     {href => '/adm/createuser?action=listusers',
 5148:                      text => "List Users",
 5149:                      help => $helpitem});
 5150:             $bread_crumbs_component = 'List Users';
 5151:             $args = {bread_crumbs           => $brcrum,
 5152:                      bread_crumbs_component => $bread_crumbs_component};
 5153:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
 5154:             my $formname = 'studentform';
 5155:             my $hidecall = "hide_searching();";
 5156:             if (($context eq 'domain') && (($env{'form.roletype'} eq 'course') ||
 5157:                 ($env{'form.roletype'} eq 'community'))) {
 5158:                 if ($env{'form.roletype'} eq 'course') {
 5159:                     ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
 5160:                         &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
 5161:                                                                 $formname);
 5162:                 } elsif ($env{'form.roletype'} eq 'community') {
 5163:                     $cb_jscript = 
 5164:                         &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
 5165:                     my %elements = (
 5166:                                       coursepick => 'radio',
 5167:                                       coursetotal => 'text',
 5168:                                       courselist => 'text',
 5169:                                    );
 5170:                     $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements);
 5171:                 }
 5172:                 $jscript .= &verify_user_display($context)."\n".
 5173:                             &Apache::loncommon::check_uncheck_jscript();
 5174:                 my $js = &add_script($jscript).$cb_jscript;
 5175:                 my $loadcode = 
 5176:                     &Apache::lonuserutils::course_selector_loadcode($formname);
 5177:                 if ($loadcode ne '') {
 5178:                     $args->{add_entries} = {onload => "$loadcode;$hidecall"};
 5179:                 } else {
 5180:                     $args->{add_entries} = {onload => $hidecall};
 5181:                 }
 5182:                 $r->print(&header($js,$args));
 5183:             } else {
 5184:                 $args->{add_entries} = {onload => $hidecall};
 5185:                 $jscript = &verify_user_display($context).
 5186:                            &Apache::loncommon::check_uncheck_jscript(); 
 5187:                 $r->print(&header(&add_script($jscript),$args));
 5188:             }
 5189:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
 5190:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 5191:                          $showcredits);
 5192:         }
 5193:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
 5194:         my $brtext;
 5195:         if ($crstype eq 'Community') {
 5196:             $brtext = 'Drop Members';
 5197:         } else {
 5198:             $brtext = 'Drop Students';
 5199:         }
 5200:         push(@{$brcrum},
 5201:                 {href => '/adm/createuser?action=drop',
 5202:                  text => $brtext,
 5203:                  help => 'Course_Drop_Student'});
 5204:         if ($env{'form.state'} eq 'done') {
 5205:             push(@{$brcrum},
 5206:                      {href=>'/adm/createuser?action=drop',
 5207:                       text=>"Result"});
 5208:         }
 5209:         $bread_crumbs_component = $brtext;
 5210:         $args = {bread_crumbs           => $brcrum,
 5211:                  bread_crumbs_component => $bread_crumbs_component}; 
 5212:         $r->print(&header(undef,$args));
 5213:         if (!exists($env{'form.state'})) {
 5214:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission,$crstype);
 5215:         } elsif ($env{'form.state'} eq 'done') {
 5216:             &Apache::lonuserutils::update_user_list($r,$context,undef,
 5217:                                                     $env{'form.action'});
 5218:         }
 5219:     } elsif ($env{'form.action'} eq 'dateselect') {
 5220:         if ($permission->{'cusr'}) {
 5221:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5222:                       &Apache::lonuserutils::date_section_selector($context,$permission,
 5223:                                                                    $crstype,$showcredits));
 5224:         } else {
 5225:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5226:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'); 
 5227:         }
 5228:     } elsif ($env{'form.action'} eq 'selfenroll') {
 5229:         if ($permission->{selfenrolladmin}) {
 5230:             my %currsettings = (
 5231:                 selfenroll_types              => $env{'course.'.$cid.'.internal.selfenroll_types'},
 5232:                 selfenroll_registered         => $env{'course.'.$cid.'.internal.selfenroll_registered'},
 5233:                 selfenroll_section            => $env{'course.'.$cid.'.internal.selfenroll_section'},
 5234:                 selfenroll_notifylist         => $env{'course.'.$cid.'.internal.selfenroll_notifylist'},
 5235:                 selfenroll_approval           => $env{'course.'.$cid.'.internal.selfenroll_approval'},
 5236:                 selfenroll_limit              => $env{'course.'.$cid.'.internal.selfenroll_limit'},
 5237:                 selfenroll_cap                => $env{'course.'.$cid.'.internal.selfenroll_cap'},
 5238:                 selfenroll_start_date         => $env{'course.'.$cid.'.internal.selfenroll_start_date'},
 5239:                 selfenroll_end_date           => $env{'course.'.$cid.'.internal.selfenroll_end_date'},
 5240:                 selfenroll_start_access       => $env{'course.'.$cid.'.internal.selfenroll_start_access'},
 5241:                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
 5242:                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
 5243:                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
 5244:                 uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
 5245:             );
 5246:             push(@{$brcrum},
 5247:                     {href => '/adm/createuser?action=selfenroll',
 5248:                      text => "Configure Self-enrollment",
 5249:                      help => 'Course_Self_Enrollment'});
 5250:             if (!exists($env{'form.state'})) {
 5251:                 $args = { bread_crumbs           => $brcrum,
 5252:                           bread_crumbs_component => 'Configure Self-enrollment'};
 5253:                 $r->print(&header(undef,$args));
 5254:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5255:                 &print_selfenroll_menu($r,'course',$cid,$cdom,$cnum,\%currsettings);
 5256:             } elsif ($env{'form.state'} eq 'done') {
 5257:                 push (@{$brcrum},
 5258:                           {href=>'/adm/createuser?action=selfenroll',
 5259:                            text=>"Result"});
 5260:                 $args = { bread_crumbs           => $brcrum,
 5261:                           bread_crumbs_component => 'Self-enrollment result'};
 5262:                 $r->print(&header(undef,$args));
 5263:                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
 5264:                 &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
 5265:             }
 5266:         } else {
 5267:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5268:                      '<span class="LC_error">'.&mt('You do not have permission to configure self-enrollment').'</span>');
 5269:         }
 5270:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
 5271:         if ($permission->{selfenrolladmin}) {
 5272:             push(@{$brcrum},
 5273:                      {href => '/adm/createuser?action=selfenrollqueue',
 5274:                       text => 'Enrollment requests',
 5275:                       help => 'Course_Approve_Selfenroll'});
 5276:             $bread_crumbs_component = 'Enrollment requests';
 5277:             if ($env{'form.state'} eq 'done') {
 5278:                 push(@{$brcrum},
 5279:                          {href => '/adm/createuser?action=selfenrollqueue',
 5280:                           text => 'Result',
 5281:                           help => 'Course_Approve_Selfenroll'});
 5282:                 $bread_crumbs_component = 'Enrollment result';
 5283:             }
 5284:             $args = { bread_crumbs           => $brcrum,
 5285:                       bread_crumbs_component => $bread_crumbs_component};
 5286:             $r->print(&header(undef,$args));
 5287:             my $coursedesc = $env{'course.'.$cid.'.description'};
 5288:             if (!exists($env{'form.state'})) {
 5289:                 $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
 5290:                 $r->print(&Apache::loncoursequeueadmin::display_queued_requests($context,
 5291:                                                                                 $cdom,$cnum));
 5292:             } elsif ($env{'form.state'} eq 'done') {
 5293:                 $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
 5294:                 $r->print(&Apache::loncoursequeueadmin::update_request_queue($context,
 5295:                               $cdom,$cnum,$coursedesc));
 5296:             }
 5297:         } else {
 5298:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5299:                      '<span class="LC_error">'.&mt('You do not have permission to manage self-enrollment').'</span>');
 5300:         }
 5301:     } elsif ($env{'form.action'} eq 'changelogs') {
 5302:         if ($permission->{cusr} || $permission->{view}) {
 5303:             &print_userchangelogs_display($r,$context,$permission,$brcrum);
 5304:         } else {
 5305:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5306:                      '<span class="LC_error">'.&mt('You do not have permission to view change logs').'</span>');
 5307:         }
 5308:     } elsif ($env{'form.action'} eq 'helpdesk') {
 5309:         if (($permission->{'owner'}) || ($permission->{'co-owner'})) {
 5310:             if ($env{'form.state'} eq 'process') {
 5311:                 if ($permission->{'owner'}) {
 5312:                     &update_helpdeskaccess($r,$permission,$brcrum);
 5313:                 } else {
 5314:                     &print_helpdeskaccess_display($r,$permission,$brcrum);
 5315:                 }
 5316:             } else {
 5317:                 &print_helpdeskaccess_display($r,$permission,$brcrum);
 5318:             }
 5319:         } else {
 5320:             $r->print(&header(undef,{'no_nav_bar' => 1}).
 5321:                       '<span class="LC_error">'.&mt('You do not have permission to view helpdesk access').'</span>');
 5322:         }
 5323:     } else {
 5324:         $bread_crumbs_component = 'User Management';
 5325:         $args = { bread_crumbs           => $brcrum,
 5326:                   bread_crumbs_component => $bread_crumbs_component};
 5327:         $r->print(&header(undef,$args));
 5328:         $r->print(&print_main_menu($permission,$context,$crstype));
 5329:     }
 5330:     $r->print(&Apache::loncommon::end_page());
 5331:     return OK;
 5332: }
 5333: 
 5334: sub header {
 5335:     my ($jscript,$args) = @_;
 5336:     my $start_page;
 5337:     if (ref($args) eq 'HASH') {
 5338:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
 5339:     } else {
 5340:         $start_page=&Apache::loncommon::start_page('User Management',$jscript);
 5341:     }
 5342:     return $start_page;
 5343: }
 5344: 
 5345: sub add_script {
 5346:     my ($js) = @_;
 5347:     return '<script type="text/javascript">'."\n"
 5348:           .'// <![CDATA['."\n"
 5349:           .$js."\n"
 5350:           .'// ]]>'."\n"
 5351:           .'</script>'."\n";
 5352: }
 5353: 
 5354: sub usernamerequest_javascript {
 5355:     my $js = <<ENDJS;
 5356: 
 5357: function openusernamereqdisplay(dom,uname,queue) {
 5358:     var url = '/adm/createuser?action=displayuserreq';
 5359:     url += '&domain='+dom+'&username='+uname+'&queue='+queue;
 5360:     var title = 'Account_Request_Browser';
 5361:     var options = 'scrollbars=1,resizable=1,menubar=0';
 5362:     options += ',width=700,height=600';
 5363:     var stdeditbrowser = open(url,title,options,'1');
 5364:     stdeditbrowser.focus();
 5365:     return;
 5366: }
 5367:  
 5368: ENDJS
 5369: }
 5370: 
 5371: sub close_popup_form {
 5372:     my $close= &mt('Close Window');
 5373:     return << "END";
 5374: <p><form name="displayreq" action="" method="post">
 5375: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 5376: </form></p>
 5377: END
 5378: }
 5379: 
 5380: sub verify_user_display {
 5381:     my ($context) = @_;
 5382:     my %lt = &Apache::lonlocal::texthash (
 5383:         course    => 'course(s): description, section(s), status',
 5384:         community => 'community(s): description, section(s), status',
 5385:         author    => 'author',
 5386:     );
 5387:     my $photos;
 5388:     if (($context eq 'course') && $env{'request.course.id'}) {
 5389:         $photos = $env{'course.'.$env{'request.course.id'}.'.internal.showphoto'};
 5390:     }
 5391:     my $output = <<"END";
 5392: 
 5393: function hide_searching() {
 5394:     if (document.getElementById('searching')) {
 5395:         document.getElementById('searching').style.display = 'none';
 5396:     }
 5397:     return;
 5398: }
 5399: 
 5400: function display_update() {
 5401:     document.studentform.action.value = 'listusers';
 5402:     document.studentform.phase.value = 'display';
 5403:     document.studentform.submit();
 5404: }
 5405: 
 5406: function updateCols(caller) {
 5407:     var context = '$context';
 5408:     var photos = '$photos';
 5409:     if (caller == 'Status') {
 5410:         if ((context == 'domain') && 
 5411:             ((document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'course') ||
 5412:              (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community'))) {
 5413:             document.getElementById('showcolstatus').checked = false;
 5414:             document.getElementById('showcolstatus').disabled = 'disabled';
 5415:             document.getElementById('showcolstart').checked = false;
 5416:             document.getElementById('showcolend').checked = false;
 5417:         } else {
 5418:             if (document.studentform.Status.options[document.studentform.Status.selectedIndex].value == 'Any') {
 5419:                 document.getElementById('showcolstatus').checked = true;
 5420:                 document.getElementById('showcolstatus').disabled = '';
 5421:                 document.getElementById('showcolstart').checked = true;
 5422:                 document.getElementById('showcolend').checked = true;
 5423:             } else {
 5424:                 document.getElementById('showcolstatus').checked = false;
 5425:                 document.getElementById('showcolstatus').disabled = 'disabled';
 5426:                 document.getElementById('showcolstart').checked = false;
 5427:                 document.getElementById('showcolend').checked = false;
 5428:             }
 5429:         }
 5430:     }
 5431:     if (caller == 'output') {
 5432:         if (photos == 1) {
 5433:             if (document.getElementById('showcolphoto')) {
 5434:                 var photoitem = document.getElementById('showcolphoto');
 5435:                 if (document.studentform.output.options[document.studentform.output.selectedIndex].value == 'html') {
 5436:                     photoitem.checked = true;
 5437:                     photoitem.disabled = '';
 5438:                 } else {
 5439:                     photoitem.checked = false;
 5440:                     photoitem.disabled = 'disabled';
 5441:                 }
 5442:             }
 5443:         }
 5444:     }
 5445:     if (caller == 'showrole') {
 5446:         if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any') ||
 5447:             (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'cr')) {
 5448:             document.getElementById('showcolrole').checked = true;
 5449:             document.getElementById('showcolrole').disabled = '';
 5450:         } else {
 5451:             document.getElementById('showcolrole').checked = false;
 5452:             document.getElementById('showcolrole').disabled = 'disabled';
 5453:         }
 5454:         if (context == 'domain') {
 5455:             var quotausageshow = 0;
 5456:             if ((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:                 }
 5469:             }
 5470:             if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'domain') {
 5471:                 document.getElementById('showcolextent').disabled = 'disabled';
 5472:                 document.getElementById('showcolextent').checked = 'false';
 5473:                 document.getElementById('showextent').style.display='none';
 5474:                 document.getElementById('showcoltextextent').innerHTML = '';
 5475:                 if ((document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'au') ||
 5476:                     (document.studentform.showrole.options[document.studentform.showrole.selectedIndex].value == 'Any')) {
 5477:                     if (document.getElementById('showcolauthorusage')) {
 5478:                         document.getElementById('showcolauthorusage').disabled = '';
 5479:                     }
 5480:                     if (document.getElementById('showcolauthorquota')) {
 5481:                         document.getElementById('showcolauthorquota').disabled = '';
 5482:                     }
 5483:                     quotausageshow = 1;
 5484:                 }
 5485:             } else {
 5486:                 document.getElementById('showextent').style.display='block';
 5487:                 document.getElementById('showextent').style.textAlign='left';
 5488:                 document.getElementById('showextent').style.textFace='normal';
 5489:                 if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'author') {
 5490:                     document.getElementById('showcolextent').disabled = '';
 5491:                     document.getElementById('showcolextent').checked = 'true';
 5492:                     document.getElementById('showcoltextextent').innerHTML="$lt{'author'}";
 5493:                 } else {
 5494:                     document.getElementById('showcolextent').disabled = '';
 5495:                     document.getElementById('showcolextent').checked = 'true';
 5496:                     if (document.studentform.roletype.options[document.studentform.roletype.selectedIndex].value == 'community') {
 5497:                         document.getElementById('showcoltextextent').innerHTML="$lt{'community'}";
 5498:                     } else {
 5499:                         document.getElementById('showcoltextextent').innerHTML="$lt{'course'}";
 5500:                     }
 5501:                 }
 5502:             }
 5503:             if (quotausageshow == 0)  {
 5504:                 if (document.getElementById('showcolauthorusage')) {
 5505:                     document.getElementById('showcolauthorusage').checked = false;
 5506:                     document.getElementById('showcolauthorusage').disabled = 'disabled';
 5507:                 }
 5508:                 if (document.getElementById('showcolauthorquota')) {
 5509:                     document.getElementById('showcolauthorquota').checked = false;
 5510:                     document.getElementById('showcolauthorquota').disabled = 'disabled';
 5511:                 }
 5512:             }
 5513:         }
 5514:     }
 5515:     return;
 5516: }
 5517: 
 5518: END
 5519:     return $output;
 5520: 
 5521: }
 5522: 
 5523: ###############################################################
 5524: ###############################################################
 5525: #  Menu Phase One
 5526: sub print_main_menu {
 5527:     my ($permission,$context,$crstype) = @_;
 5528:     my $linkcontext = $context;
 5529:     my $stuterm = lc(&Apache::lonnet::plaintext('st',$crstype));
 5530:     if (($context eq 'course') && ($crstype eq 'Community')) {
 5531:         $linkcontext = lc($crstype);
 5532:         $stuterm = 'Members';
 5533:     }
 5534:     my %links = (
 5535:                 domain => {
 5536:                             upload     => 'Upload a File of Users',
 5537:                             singleuser => 'Add/Modify a User',
 5538:                             listusers  => 'Manage Users',
 5539:                             },
 5540:                 author => {
 5541:                             upload     => 'Upload a File of Co-authors',
 5542:                             singleuser => 'Add/Modify a Co-author',
 5543:                             listusers  => 'Manage Co-authors',
 5544:                             },
 5545:                 course => {
 5546:                             upload     => 'Upload a File of Course Users',
 5547:                             singleuser => 'Add/Modify a Course User',
 5548:                             listusers  => 'List and Modify Multiple Course Users',
 5549:                             },
 5550:                 community => {
 5551:                             upload     => 'Upload a File of Community Users',
 5552:                             singleuser => 'Add/Modify a Community User',
 5553:                             listusers  => 'List and Modify Multiple Community Users',
 5554:                            },
 5555:                 );
 5556:      my %linktitles = (
 5557:                 domain => {
 5558:                             singleuser => 'Add a user to the domain, and/or a course or community in the domain.',
 5559:                             listusers  => 'Show and manage users in this domain.',
 5560:                             },
 5561:                 author => {
 5562:                             singleuser => 'Add a user with a co- or assistant author role.',
 5563:                             listusers  => 'Show and manage co- or assistant authors.',
 5564:                             },
 5565:                 course => {
 5566:                             singleuser => 'Add a user with a certain role to this course.',
 5567:                             listusers  => 'Show and manage users in this course.',
 5568:                             },
 5569:                 community => {
 5570:                             singleuser => 'Add a user with a certain role to this community.',
 5571:                             listusers  => 'Show and manage users in this community.',
 5572:                            },
 5573:                 );
 5574:   if ($linkcontext eq 'domain') {
 5575:       unless ($permission->{'cusr'}) {
 5576:           $links{'domain'}{'singleuser'} = 'View a User';
 5577:           $linktitles{'domain'}{'singleuser'} = 'View information about a user in the domain';
 5578:       }
 5579:   } elsif ($linkcontext eq 'course') {
 5580:       unless ($permission->{'cusr'}) {
 5581:           $links{'course'}{'singleuser'} = 'View a Course User';
 5582:           $linktitles{'course'}{'singleuser'} = 'View information about a user in this course';
 5583:           $links{'course'}{'listusers'} = 'List Course Users';
 5584:           $linktitles{'course'}{'listusers'} = 'Show information about users in this course';
 5585:       }
 5586:   } elsif ($linkcontext eq 'community') {
 5587:       unless ($permission->{'cusr'}) {
 5588:           $links{'community'}{'singleuser'} = 'View a Community User';
 5589:           $linktitles{'community'}{'singleuser'} = 'View information about a user in this community';
 5590:           $links{'community'}{'listusers'} = 'List Community Users';
 5591:           $linktitles{'community'}{'listusers'} = 'Show information about users in this community';
 5592:       }
 5593:   }
 5594:   my @menu = ( {categorytitle => 'Single Users', 
 5595:          items =>
 5596:          [
 5597:             {
 5598:              linktext => $links{$linkcontext}{'singleuser'},
 5599:              icon => 'edit-redo.png',
 5600:              #help => 'Course_Change_Privileges',
 5601:              url => '/adm/createuser?action=singleuser',
 5602:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5603:              linktitle => $linktitles{$linkcontext}{'singleuser'},
 5604:             },
 5605:          ]},
 5606: 
 5607:          {categorytitle => 'Multiple Users',
 5608:          items => 
 5609:          [
 5610:             {
 5611:              linktext => $links{$linkcontext}{'upload'},
 5612:              icon => 'uplusr.png',
 5613:              #help => 'Course_Create_Class_List',
 5614:              url => '/adm/createuser?action=upload',
 5615:              permission => $permission->{'cusr'},
 5616:              linktitle => 'Upload a CSV or a text file containing users.',
 5617:             },
 5618:             {
 5619:              linktext => $links{$linkcontext}{'listusers'},
 5620:              icon => 'mngcu.png',
 5621:              #help => 'Course_View_Class_List',
 5622:              url => '/adm/createuser?action=listusers',
 5623:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5624:              linktitle => $linktitles{$linkcontext}{'listusers'}, 
 5625:             },
 5626: 
 5627:          ]},
 5628: 
 5629:          {categorytitle => 'Administration',
 5630:          items => [ ]},
 5631:        );
 5632: 
 5633:     if ($context eq 'domain'){
 5634:         push(@{  $menu[0]->{items} }, # Single Users
 5635:             {
 5636:              linktext => 'User Access Log',
 5637:              icon => 'document-properties.png',
 5638:              #help => 'Domain_User_Access_Logs',
 5639:              url => '/adm/createuser?action=accesslogs',
 5640:              permission => $permission->{'activity'},
 5641:              linktitle => 'View user access log.',
 5642:             }
 5643:         );
 5644:         
 5645:         push(@{ $menu[2]->{items} }, #Category: Administration
 5646:             {
 5647:              linktext => 'Custom Roles',
 5648:              icon => 'emblem-photos.png',
 5649:              #help => 'Course_Editing_Custom_Roles',
 5650:              url => '/adm/createuser?action=custom',
 5651:              permission => $permission->{'custom'},
 5652:              linktitle => 'Configure a custom role.',
 5653:             },
 5654:             {
 5655:              linktext => 'Authoring Space Requests',
 5656:              icon => 'selfenrl-queue.png',
 5657:              #help => 'Domain_Role_Approvals',
 5658:              url => '/adm/createuser?action=processauthorreq',
 5659:              permission => $permission->{'cusr'},
 5660:              linktitle => 'Approve or reject author role requests',
 5661:             },
 5662:             {
 5663:              linktext => 'LON-CAPA Account Requests',
 5664:              icon => 'list-add.png',
 5665:              #help => 'Domain_Username_Approvals',
 5666:              url => '/adm/createuser?action=processusernamereq',
 5667:              permission => $permission->{'cusr'},
 5668:              linktitle => 'Approve or reject LON-CAPA account requests',
 5669:             },
 5670:             {
 5671:              linktext => 'Change Log',
 5672:              icon => 'document-properties.png',
 5673:              #help => 'Course_User_Logs',
 5674:              url => '/adm/createuser?action=changelogs',
 5675:              permission => ($permission->{'cusr'} || $permission->{'view'}),
 5676:              linktitle => 'View change log.',
 5677:             },
 5678:         );
 5679:         
 5680:     }elsif ($context eq 'course'){
 5681:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
 5682: 
 5683:         my %linktext = (
 5684:                          'Course'    => {
 5685:                                           single => 'Add/Modify a Student', 
 5686:                                           drop   => 'Drop Students',
 5687:                                           groups => 'Course Groups',
 5688:                                         },
 5689:                          'Community' => {
 5690:                                           single => 'Add/Modify a Member', 
 5691:                                           drop   => 'Drop Members',
 5692:                                           groups => 'Community Groups',
 5693:                                         },
 5694:                        );
 5695:         $linktext{'Placement'} = $linktext{'Course'};
 5696: 
 5697:         my %linktitle = (
 5698:             'Course' => {
 5699:                   single => 'Add a user with the role of student to this course',
 5700:                   drop   => 'Remove a student from this course.',
 5701:                   groups => 'Manage course groups',
 5702:                         },
 5703:             'Community' => {
 5704:                   single => 'Add a user with the role of member to this community',
 5705:                   drop   => 'Remove a member from this community.',
 5706:                   groups => 'Manage community groups',
 5707:                            },
 5708:         );
 5709: 
 5710:         $linktitle{'Placement'} = $linktitle{'Course'};
 5711: 
 5712:         push(@{ $menu[0]->{items} }, #Category: Single Users
 5713:             {   
 5714:              linktext => $linktext{$crstype}{'single'},
 5715:              #help => 'Course_Add_Student',
 5716:              icon => 'list-add.png',
 5717:              url => '/adm/createuser?action=singlestudent',
 5718:              permission => $permission->{'cusr'},
 5719:              linktitle => $linktitle{$crstype}{'single'},
 5720:             },
 5721:         );
 5722:         
 5723:         push(@{ $menu[1]->{items} }, #Category: Multiple Users 
 5724:             {
 5725:              linktext => $linktext{$crstype}{'drop'},
 5726:              icon => 'edit-undo.png',
 5727:              #help => 'Course_Drop_Student',
 5728:              url => '/adm/createuser?action=drop',
 5729:              permission => $permission->{'cusr'},
 5730:              linktitle => $linktitle{$crstype}{'drop'},
 5731:             },
 5732:         );
 5733:         push(@{ $menu[2]->{items} }, #Category: Administration
 5734:             {
 5735:              linktext => 'Helpdesk Access',
 5736:              icon => 'helpdesk-access.png',
 5737:              #help => 'Course_Helpdesk_Access',
 5738:              url => '/adm/createuser?action=helpdesk',
 5739:              permission => ($permission->{'owner'} || $permission->{'co-owner'}),
 5740:              linktitle => 'Helpdesk access options',
 5741:             },
 5742:             {
 5743:              linktext => 'Custom Roles',
 5744:              icon => 'emblem-photos.png',
 5745:              #help => 'Course_Editing_Custom_Roles',
 5746:              url => '/adm/createuser?action=custom',
 5747:              permission => $permission->{'custom'},
 5748:              linktitle => 'Configure a custom role.',
 5749:             },
 5750:             {
 5751:              linktext => $linktext{$crstype}{'groups'},
 5752:              icon => 'grps.png',
 5753:              #help => 'Course_Manage_Group',
 5754:              url => '/adm/coursegroups?refpage=cusr',
 5755:              permission => $permission->{'grp_manage'},
 5756:              linktitle => $linktitle{$crstype}{'groups'},
 5757:             },
 5758:             {
 5759:              linktext => 'Change Log',
 5760:              icon => 'document-properties.png',
 5761:              #help => 'Course_User_Logs',
 5762:              url => '/adm/createuser?action=changelogs',
 5763:              permission => ($permission->{'view'} || $permission->{'cusr'}),
 5764:              linktitle => 'View change log.',
 5765:             },
 5766:         );
 5767:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
 5768:             push(@{ $menu[2]->{items} },
 5769:                     {
 5770:                      linktext => 'Enrollment Requests',
 5771:                      icon => 'selfenrl-queue.png',
 5772:                      #help => 'Course_Approve_Selfenroll',
 5773:                      url => '/adm/createuser?action=selfenrollqueue',
 5774:                      permission => $permission->{'selfenrolladmin'},
 5775:                      linktitle =>'Approve or reject enrollment requests.',
 5776:                     },
 5777:             );
 5778:         }
 5779:         
 5780:         if (!exists($permission->{'cusr_section'})){
 5781:             if ($crstype ne 'Community') {
 5782:                 push(@{ $menu[2]->{items} },
 5783:                     {
 5784:                      linktext => 'Automated Enrollment',
 5785:                      icon => 'roles.png',
 5786:                      #help => 'Course_Automated_Enrollment',
 5787:                      permission => (&Apache::lonnet::auto_run($cnum,$cdom)
 5788:                                          && (($permission->{'cusr'}) ||
 5789:                                              ($permission->{'view'}))),
 5790:                      url  => '/adm/populate',
 5791:                      linktitle => 'Automated enrollment manager.',
 5792:                     }
 5793:                 );
 5794:             }
 5795:             push(@{ $menu[2]->{items} }, 
 5796:                 {
 5797:                  linktext => 'User Self-Enrollment',
 5798:                  icon => 'self_enroll.png',
 5799:                  #help => 'Course_Self_Enrollment',
 5800:                  url => '/adm/createuser?action=selfenroll',
 5801:                  permission => $permission->{'selfenrolladmin'},
 5802:                  linktitle => 'Configure user self-enrollment.',
 5803:                 },
 5804:             );
 5805:         }
 5806:     } elsif ($context eq 'author') {
 5807:         push(@{ $menu[2]->{items} }, #Category: Administration
 5808:             {
 5809:              linktext => 'Change Log',
 5810:              icon => 'document-properties.png',
 5811:              #help => 'Course_User_Logs',
 5812:              url => '/adm/createuser?action=changelogs',
 5813:              permission => $permission->{'cusr'},
 5814:              linktitle => 'View change log.',
 5815:             },
 5816:         );
 5817:     }
 5818:     return Apache::lonhtmlcommon::generate_menu(@menu);
 5819: #               { text => 'View Log-in History',
 5820: #                 help => 'Course_User_Logins',
 5821: #                 action => 'logins',
 5822: #                 permission => $permission->{'cusr'},
 5823: #               });
 5824: }
 5825: 
 5826: sub restore_prev_selections {
 5827:     my %saveable_parameters = ('srchby'   => 'scalar',
 5828: 			       'srchin'   => 'scalar',
 5829: 			       'srchtype' => 'scalar',
 5830: 			       );
 5831:     &Apache::loncommon::store_settings('user','user_picker',
 5832: 				       \%saveable_parameters);
 5833:     &Apache::loncommon::restore_settings('user','user_picker',
 5834: 					 \%saveable_parameters);
 5835: }
 5836: 
 5837: sub print_selfenroll_menu {
 5838:     my ($r,$context,$cid,$cdom,$cnum,$currsettings,$additional,$readonly) = @_;
 5839:     my $crstype = &Apache::loncommon::course_type();
 5840:     my $formname = 'selfenroll';
 5841:     my $nolink = 1;
 5842:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 5843:     my $groupslist = &Apache::lonuserutils::get_groupslist();
 5844:     my $setsec_js = 
 5845:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
 5846:     my %alerts = &Apache::lonlocal::texthash(
 5847:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
 5848:         butn => 'but no user types have been checked.',
 5849:         wilf => "Please uncheck 'activate' or check at least one type.",
 5850:     );
 5851:     my $disabled;
 5852:     if ($readonly) {
 5853:        $disabled = ' disabled="disabled"';
 5854:     }
 5855:     &js_escape(\%alerts);
 5856:     my $selfenroll_js = <<"ENDSCRIPT";
 5857: function update_types(caller,num) {
 5858:     var delidx = getIndexByName('selfenroll_delete');
 5859:     var actidx = getIndexByName('selfenroll_activate');
 5860:     if (caller == 'selfenroll_all') {
 5861:         var selall;
 5862:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5863:             if (document.$formname.selfenroll_all[i].checked) {
 5864:                 selall = document.$formname.selfenroll_all[i].value;
 5865:             }
 5866:         }
 5867:         if (selall == 1) {
 5868:             if (delidx != -1) {
 5869:                 if (document.$formname.selfenroll_delete.length) {
 5870:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5871:                         document.$formname.selfenroll_delete[j].checked = true;
 5872:                     }
 5873:                 } else {
 5874:                     document.$formname.elements[delidx].checked = true;
 5875:                 }
 5876:             }
 5877:             if (actidx != -1) {
 5878:                 if (document.$formname.selfenroll_activate.length) {
 5879:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5880:                         document.$formname.selfenroll_activate[j].checked = false;
 5881:                     }
 5882:                 } else {
 5883:                     document.$formname.elements[actidx].checked = false;
 5884:                 }
 5885:             }
 5886:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
 5887:         }
 5888:     }
 5889:     if (caller == 'selfenroll_activate') {
 5890:         if (document.$formname.selfenroll_activate.length) {
 5891:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5892:                 if (document.$formname.selfenroll_activate[j].value == num) {
 5893:                     if (document.$formname.selfenroll_activate[j].checked) {
 5894:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5895:                             if (document.$formname.selfenroll_all[i].value == '1') {
 5896:                                 document.$formname.selfenroll_all[i].checked = false;
 5897:                             }
 5898:                             if (document.$formname.selfenroll_all[i].value == '0') {
 5899:                                 document.$formname.selfenroll_all[i].checked = true;
 5900:                             }
 5901:                         }
 5902:                     }
 5903:                 }
 5904:             }
 5905:         } else {
 5906:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
 5907:                 if (document.$formname.selfenroll_all[i].value == '1') {
 5908:                     document.$formname.selfenroll_all[i].checked = false;
 5909:                 }
 5910:                 if (document.$formname.selfenroll_all[i].value == '0') {
 5911:                     document.$formname.selfenroll_all[i].checked = true;
 5912:                 }
 5913:             }
 5914:         }
 5915:     }
 5916:     if (caller == 'selfenroll_delete') {
 5917:         if (document.$formname.selfenroll_delete.length) {
 5918:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
 5919:                 if (document.$formname.selfenroll_delete[j].value == num) {
 5920:                     if (document.$formname.selfenroll_delete[j].checked) {
 5921:                         var delindex = getIndexByName('selfenroll_types_'+num);
 5922:                         if (delindex != -1) { 
 5923:                             if (document.$formname.elements[delindex].length) {
 5924:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5925:                                     document.$formname.elements[delindex][k].checked = false;
 5926:                                 }
 5927:                             } else {
 5928:                                 document.$formname.elements[delindex].checked = false;
 5929:                             }
 5930:                         }
 5931:                     }
 5932:                 }
 5933:             }
 5934:         } else {
 5935:             if (document.$formname.selfenroll_delete.checked) {
 5936:                 var delindex = getIndexByName('selfenroll_types_'+num);
 5937:                 if (delindex != -1) {
 5938:                     if (document.$formname.elements[delindex].length) {
 5939:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
 5940:                             document.$formname.elements[delindex][k].checked = false;
 5941:                         }
 5942:                     } else {
 5943:                         document.$formname.elements[delindex].checked = false;
 5944:                     }
 5945:                 }
 5946:             }
 5947:         }
 5948:     }
 5949:     return;
 5950: }
 5951: 
 5952: function validate_types(form) {
 5953:     var needaction = new Array();
 5954:     var countfail = 0;
 5955:     var actidx = getIndexByName('selfenroll_activate');
 5956:     if (actidx != -1) {
 5957:         if (document.$formname.selfenroll_activate.length) {
 5958:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
 5959:                 var num = document.$formname.selfenroll_activate[j].value;
 5960:                 if (document.$formname.selfenroll_activate[j].checked) {
 5961:                     countfail = check_types(num,countfail,needaction)
 5962:                 }
 5963:             }
 5964:         } else {
 5965:             if (document.$formname.selfenroll_activate.checked) {
 5966:                 var num = document.$formname.selfenroll_activate.value;
 5967:                 countfail = check_types(num,countfail,needaction)
 5968:             }
 5969:         }
 5970:     }
 5971:     if (countfail > 0) {
 5972:         var msg = "$alerts{'acto'}\\n";
 5973:         var loopend = needaction.length -1;
 5974:         if (loopend > 0) {
 5975:             for (var m=0; m<loopend; m++) {
 5976:                 msg += needaction[m]+", ";
 5977:             }
 5978:         }
 5979:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
 5980:         alert(msg);
 5981:         return; 
 5982:     }
 5983:     setSections(form);
 5984: }
 5985: 
 5986: function check_types(num,countfail,needaction) {
 5987:     var boxname = 'selfenroll_types_'+num;
 5988:     var typeidx = getIndexByName(boxname);
 5989:     var count = 0;
 5990:     if (typeidx != -1) {
 5991:         if (document.$formname.elements[boxname].length) {
 5992:             for (var k=0; k<document.$formname.elements[boxname].length; k++) {
 5993:                 if (document.$formname.elements[boxname][k].checked) {
 5994:                     count ++;
 5995:                 }
 5996:             }
 5997:         } else {
 5998:             if (document.$formname.elements[typeidx].checked) {
 5999:                 count ++;
 6000:             }
 6001:         }
 6002:         if (count == 0) {
 6003:             var domidx = getIndexByName('selfenroll_dom_'+num);
 6004:             if (domidx != -1) {
 6005:                 var domname = document.$formname.elements[domidx].value;
 6006:                 needaction[countfail] = domname;
 6007:                 countfail ++;
 6008:             }
 6009:         }
 6010:     }
 6011:     return countfail;
 6012: }
 6013: 
 6014: function toggleNotify() {
 6015:     var selfenrollApproval = 0;
 6016:     if (document.$formname.selfenroll_approval.length) {
 6017:         for (var i=0; i<document.$formname.selfenroll_approval.length; i++) {
 6018:             if (document.$formname.selfenroll_approval[i].checked) {
 6019:                 selfenrollApproval = document.$formname.selfenroll_approval[i].value;
 6020:                 break;        
 6021:             }
 6022:         }
 6023:     }
 6024:     if (document.getElementById('notified')) {
 6025:         if (selfenrollApproval == 0) {
 6026:             document.getElementById('notified').style.display='none';
 6027:         } else {
 6028:             document.getElementById('notified').style.display='block';
 6029:         }
 6030:     }
 6031:     return;
 6032: }
 6033: 
 6034: function getIndexByName(item) {
 6035:     for (var i=0;i<document.$formname.elements.length;i++) {
 6036:         if (document.$formname.elements[i].name == item) {
 6037:             return i;
 6038:         }
 6039:     }
 6040:     return -1;
 6041: }
 6042: ENDSCRIPT
 6043: 
 6044:     my $output = '<script type="text/javascript">'."\n".
 6045:                  '// <![CDATA['."\n".
 6046:                  $setsec_js."\n".$selfenroll_js."\n".
 6047:                  '// ]]>'."\n".
 6048:                  '</script>'."\n".
 6049:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
 6050:  
 6051:     my $visactions = &cat_visibility();
 6052:     my ($cathash,%cattype);
 6053:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 6054:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 6055:         $cathash = $domconfig{'coursecategories'}{'cats'};
 6056:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 6057:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 6058:         if ($cattype{'auth'} eq '') {
 6059:             $cattype{'auth'} = 'std';
 6060:         }
 6061:         if ($cattype{'unauth'} eq '') {
 6062:             $cattype{'unauth'} = 'std';
 6063:         }
 6064:     } else {
 6065:         $cathash = {};
 6066:         $cattype{'auth'} = 'std';
 6067:         $cattype{'unauth'} = 'std';
 6068:     }
 6069:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 6070:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6071:                   '<br />'.
 6072:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6073:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 6074:                   '</ul>');
 6075:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 6076:         if ($currsettings->{'uniquecode'}) {
 6077:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 6078:         } else {
 6079:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 6080:                   '<br />'.
 6081:                   '<br />'.$visactions->{'take'}.'<ul>'.
 6082:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 6083:                   '</ul><br />');
 6084:         }
 6085:     } else {
 6086:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 6087:         if (ref($visactions) eq 'HASH') {
 6088:             if ($visible) {
 6089:                 $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
 6090:            } else {
 6091:                 $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
 6092:                           .$visactions->{'yous'}.
 6093:                            '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
 6094:                 if (ref($vismsgs) eq 'ARRAY') {
 6095:                     $output .= '<br />'.$visactions->{'make'}.'<ul>';
 6096:                     foreach my $item (@{$vismsgs}) {
 6097:                         $output .= '<li>'.$visactions->{$item}.'</li>';
 6098:                     }
 6099:                     $output .= '</ul>';
 6100:                 }
 6101:                 $output .= '</p>';
 6102:             }
 6103:         }
 6104:     }
 6105:     my $actionhref = '/adm/createuser';
 6106:     if ($context eq 'domain') {
 6107:         $actionhref = '/adm/modifycourse';
 6108:     }
 6109: 
 6110:     my %noedit;
 6111:     unless ($context eq 'domain') {
 6112:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 6113:     }
 6114:     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
 6115:                &Apache::lonhtmlcommon::start_pick_box();
 6116:     if (ref($row) eq 'ARRAY') {
 6117:         foreach my $item (@{$row}) {
 6118:             my $title = $item; 
 6119:             if (ref($lt) eq 'HASH') {
 6120:                 $title = $lt->{$item};
 6121:             }
 6122:             $output .= &Apache::lonhtmlcommon::row_title($title);
 6123:             if ($item eq 'types') {
 6124:                 my $curr_types;
 6125:                 if (ref($currsettings) eq 'HASH') {
 6126:                     $curr_types = $currsettings->{'selfenroll_types'};
 6127:                 }
 6128:                 if ($noedit{$item}) {
 6129:                     if ($curr_types eq '*') {
 6130:                         $output .= &mt('Any user in any domain');   
 6131:                     } else {
 6132:                         my @entries = split(/;/,$curr_types);
 6133:                         if (@entries > 0) {
 6134:                             $output .= '<ul>'; 
 6135:                             foreach my $entry (@entries) {
 6136:                                 my ($currdom,$typestr) = split(/:/,$entry);
 6137:                                 next if ($typestr eq '');
 6138:                                 my $domdesc = &Apache::lonnet::domain($currdom);
 6139:                                 my @currinsttypes = split(',',$typestr);
 6140:                                 my ($othertitle,$usertypes,$types) = 
 6141:                                     &Apache::loncommon::sorted_inst_types($currdom);
 6142:                                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6143:                                     $usertypes->{'any'} = &mt('any user'); 
 6144:                                     if (keys(%{$usertypes}) > 0) {
 6145:                                         $usertypes->{'other'} = &mt('other users');
 6146:                                     }
 6147:                                     my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
 6148:                                     $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
 6149:                                  }
 6150:                             }
 6151:                             $output .= '</ul>';
 6152:                         } else {
 6153:                             $output .= &mt('None');
 6154:                         }
 6155:                     }
 6156:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6157:                     next;
 6158:                 }
 6159:                 my $showdomdesc = 1;
 6160:                 my $includeempty = 1;
 6161:                 my $num = 0;
 6162:                 $output .= &Apache::loncommon::start_data_table().
 6163:                            &Apache::loncommon::start_data_table_row()
 6164:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
 6165:                            .&mt('Any user in any domain:')
 6166:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
 6167:                 if ($curr_types eq '*') {
 6168:                     $output .= ' checked="checked" '; 
 6169:                 }
 6170:                 $output .= 'onchange="javascript:update_types('.
 6171:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('Yes').'</label>'.
 6172:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
 6173:                 if ($curr_types ne '*') {
 6174:                     $output .= ' checked="checked" ';
 6175:                 }
 6176:                 $output .= ' onchange="javascript:update_types('.
 6177:                            "'selfenroll_all'".');"'.$disabled.' />'.&mt('No').'</label></td>'.
 6178:                            &Apache::loncommon::end_data_table_row().
 6179:                            &Apache::loncommon::end_data_table().
 6180:                            &mt('Or').'<br />'.
 6181:                            &Apache::loncommon::start_data_table();
 6182:                 my %currdoms;
 6183:                 if ($curr_types eq '') {
 6184:                     $output .= &new_selfenroll_dom_row($cdom,'0');
 6185:                 } elsif ($curr_types ne '*') {
 6186:                     my @entries = split(/;/,$curr_types);
 6187:                     if (@entries > 0) {
 6188:                         foreach my $entry (@entries) {
 6189:                             my ($currdom,$typestr) = split(/:/,$entry);
 6190:                             $currdoms{$currdom} = 1;
 6191:                             my $domdesc = &Apache::lonnet::domain($currdom);
 6192:                             my @currinsttypes = split(',',$typestr);
 6193:                             $output .= &Apache::loncommon::start_data_table_row()
 6194:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
 6195:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
 6196:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
 6197:                                        .'" value="'.$currdom.'" /></span><br />'
 6198:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
 6199:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');"'.$disabled.' />'
 6200:                                        .&mt('Delete').'</label></span></td>';
 6201:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
 6202:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes,$readonly).'</td>'
 6203:                                        .&Apache::loncommon::end_data_table_row();
 6204:                             $num ++;
 6205:                         }
 6206:                     }
 6207:                 }
 6208:                 my $add_domtitle = &mt('Users in additional domain:');
 6209:                 if ($curr_types eq '*') { 
 6210:                     $add_domtitle = &mt('Users in specific domain:');
 6211:                 } elsif ($curr_types eq '') {
 6212:                     $add_domtitle = &mt('Users in other domain:');
 6213:                 }
 6214:                 my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$cdom);
 6215:                 $output .= &Apache::loncommon::start_data_table_row()
 6216:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
 6217:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
 6218:                                                                 $includeempty,$showdomdesc,'',$trusted,$untrusted,$readonly)
 6219:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
 6220:                            .'</td>'.&Apache::loncommon::end_data_table_row()
 6221:                            .&Apache::loncommon::end_data_table();
 6222:             } elsif ($item eq 'registered') {
 6223:                 my ($regon,$regoff);
 6224:                 my $registered;
 6225:                 if (ref($currsettings) eq 'HASH') {
 6226:                     $registered = $currsettings->{'selfenroll_registered'};
 6227:                 }
 6228:                 if ($noedit{$item}) {
 6229:                     if ($registered) {
 6230:                         $output .= &mt('Must be registered in course');
 6231:                     } else {
 6232:                         $output .= &mt('No requirement');
 6233:                     }
 6234:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6235:                     next;
 6236:                 }
 6237:                 if ($registered) {
 6238:                     $regon = ' checked="checked" ';
 6239:                     $regoff = '';
 6240:                 } else {
 6241:                     $regon = '';
 6242:                     $regoff = ' checked="checked" ';
 6243:                 }
 6244:                 $output .= '<label>'.
 6245:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.$disabled.' />'.
 6246:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
 6247:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.$disabled.' />'.
 6248:                            &mt('No').'</label>';
 6249:             } elsif ($item eq 'enroll_dates') {
 6250:                 my ($starttime,$endtime);
 6251:                 if (ref($currsettings) eq 'HASH') {
 6252:                     $starttime = $currsettings->{'selfenroll_start_date'};
 6253:                     $endtime = $currsettings->{'selfenroll_end_date'};
 6254:                     if ($starttime eq '') {
 6255:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6256:                     }
 6257:                     if ($endtime eq '') {
 6258:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6259:                     }
 6260:                 }
 6261:                 if ($noedit{$item}) {
 6262:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6263:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6264:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6265:                     next;
 6266:                 }
 6267:                 my $startform =
 6268:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
 6269:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6270:                 my $endform =
 6271:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
 6272:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6273:                 $output .= &selfenroll_date_forms($startform,$endform);
 6274:             } elsif ($item eq 'access_dates') {
 6275:                 my ($starttime,$endtime);
 6276:                 if (ref($currsettings) eq 'HASH') {
 6277:                     $starttime = $currsettings->{'selfenroll_start_access'};
 6278:                     $endtime = $currsettings->{'selfenroll_end_access'};
 6279:                     if ($starttime eq '') {
 6280:                         $starttime = $currsettings->{'default_enrollment_start_date'};
 6281:                     }
 6282:                     if ($endtime eq '') {
 6283:                         $endtime = $currsettings->{'default_enrollment_end_date'};
 6284:                     }
 6285:                 }
 6286:                 if ($noedit{$item}) {
 6287:                     $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
 6288:                                                           &Apache::lonlocal::locallocaltime($endtime));
 6289:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6290:                     next;
 6291:                 }
 6292:                 my $startform =
 6293:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
 6294:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6295:                 my $endform =
 6296:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
 6297:                                       $disabled,undef,undef,undef,undef,undef,undef,$nolink);
 6298:                 $output .= &selfenroll_date_forms($startform,$endform);
 6299:             } elsif ($item eq 'section') {
 6300:                 my $currsec;
 6301:                 if (ref($currsettings) eq 'HASH') {
 6302:                     $currsec = $currsettings->{'selfenroll_section'};
 6303:                 }
 6304:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
 6305:                 my $newsecval;
 6306:                 if ($currsec ne 'none' && $currsec ne '') {
 6307:                     if (!defined($sections_count{$currsec})) {
 6308:                         $newsecval = $currsec;
 6309:                     }
 6310:                 }
 6311:                 if ($noedit{$item}) {
 6312:                     if ($currsec ne '') {
 6313:                         $output .= $currsec;
 6314:                     } else {
 6315:                         $output .= &mt('No specific section');
 6316:                     }
 6317:                     $output .= '<br />'.&mt('(Set by Domain Coordinator)');
 6318:                     next;
 6319:                 }
 6320:                 my $sections_select = 
 6321:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec,$disabled);
 6322:                 $output .= '<table class="LC_createuser">'."\n".
 6323:                            '<tr class="LC_section_row">'."\n".
 6324:                            '<td align="center">'.&mt('Existing sections')."\n".
 6325:                            '<br />'.$sections_select.'</td><td align="center">'.
 6326:                            &mt('New section').'<br />'."\n".
 6327:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'"'.$disabled.' />'."\n".
 6328:                            '<input type="hidden" name="sections" value="" />'."\n".
 6329:                            '</td></tr></table>'."\n";
 6330:             } elsif ($item eq 'approval') {
 6331:                 my ($currnotified,$currapproval,%appchecked);
 6332:                 my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 6333:                 if (ref($currsettings) eq 'HASH') {
 6334:                     $currnotified = $currsettings->{'selfenroll_notifylist'};
 6335:                     $currapproval = $currsettings->{'selfenroll_approval'};
 6336:                 }
 6337:                 if ($currapproval !~ /^[012]$/) {
 6338:                     $currapproval = 0;
 6339:                 }
 6340:                 if ($noedit{$item}) {
 6341:                     $output .=  $selfdescs{'approval'}{$currapproval}.
 6342:                                 '<br />'.&mt('(Set by Domain Coordinator)');
 6343:                     next;
 6344:                 }
 6345:                 $appchecked{$currapproval} = ' checked="checked"';
 6346:                 for my $i (0..2) {
 6347:                     $output .= '<label>'.
 6348:                                '<input type="radio" name="selfenroll_approval" value="'.$i.'"'.
 6349:                                $appchecked{$i}.' onclick="toggleNotify();"'.$disabled.' />'.
 6350:                                $selfdescs{'approval'}{$i}.'</label>'.('&nbsp;'x2);
 6351:                 }
 6352:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
 6353:                 my (@ccs,%notified);
 6354:                 my $ccrole = 'cc';
 6355:                 if ($crstype eq 'Community') {
 6356:                     $ccrole = 'co';
 6357:                 }
 6358:                 if ($advhash{$ccrole}) {
 6359:                     @ccs = split(/,/,$advhash{$ccrole});
 6360:                 }
 6361:                 if ($currnotified) {
 6362:                     foreach my $current (split(/,/,$currnotified)) {
 6363:                         $notified{$current} = 1;
 6364:                         if (!grep(/^\Q$current\E$/,@ccs)) {
 6365:                             push(@ccs,$current);
 6366:                         }
 6367:                     }
 6368:                 }
 6369:                 if (@ccs) {
 6370:                     my $style;
 6371:                     unless ($currapproval) {
 6372:                         $style = ' style="display: none;"'; 
 6373:                     }
 6374:                     $output .= '<br /><div id="notified"'.$style.'>'.
 6375:                                &mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.
 6376:                                &Apache::loncommon::start_data_table().
 6377:                                &Apache::loncommon::start_data_table_row();
 6378:                     my $count = 0;
 6379:                     my $numcols = 4;
 6380:                     foreach my $cc (sort(@ccs)) {
 6381:                         my $notifyon;
 6382:                         my ($ccuname,$ccudom) = split(/:/,$cc);
 6383:                         if ($notified{$cc}) {
 6384:                             $notifyon = ' checked="checked" ';
 6385:                         }
 6386:                         if ($count && !$count%$numcols) {
 6387:                             $output .= &Apache::loncommon::end_data_table_row().
 6388:                                        &Apache::loncommon::start_data_table_row()
 6389:                         }
 6390:                         $output .= '<td><span class="LC_nobreak"><label>'.
 6391:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'"'.$disabled.' />'.
 6392:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
 6393:                                    '</label></span></td>';
 6394:                         $count ++;
 6395:                     }
 6396:                     my $rem = $count%$numcols;
 6397:                     if ($rem) {
 6398:                         my $emptycols = $numcols - $rem;
 6399:                         for (my $i=0; $i<$emptycols; $i++) { 
 6400:                             $output .= '<td>&nbsp;</td>';
 6401:                         }
 6402:                     }
 6403:                     $output .= &Apache::loncommon::end_data_table_row().
 6404:                                &Apache::loncommon::end_data_table().
 6405:                                '</div>';
 6406:                 }
 6407:             } elsif ($item eq 'limit') {
 6408:                 my ($crslimit,$selflimit,$nolimit,$currlim,$currcap);
 6409:                 if (ref($currsettings) eq 'HASH') {
 6410:                     $currlim = $currsettings->{'selfenroll_limit'};
 6411:                     $currcap = $currsettings->{'selfenroll_cap'};
 6412:                 }
 6413:                 if ($noedit{$item}) {
 6414:                     if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
 6415:                         if ($currlim eq 'allstudents') {
 6416:                             $output .= &mt('Limit by total students');
 6417:                         } elsif ($currlim eq 'selfenrolled') {
 6418:                             $output .= &mt('Limit by total self-enrolled students');
 6419:                         }
 6420:                         $output .= ' '.&mt('Maximum: [_1]',$currcap).
 6421:                                    '<br />'.&mt('(Set by Domain Coordinator)');
 6422:                     } else {
 6423:                         $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
 6424:                     }
 6425:                     next;
 6426:                 }
 6427:                 if ($currlim eq 'allstudents') {
 6428:                     $crslimit = ' checked="checked" ';
 6429:                     $selflimit = ' ';
 6430:                     $nolimit = ' ';
 6431:                 } elsif ($currlim eq 'selfenrolled') {
 6432:                     $crslimit = ' ';
 6433:                     $selflimit = ' checked="checked" ';
 6434:                     $nolimit = ' '; 
 6435:                 } else {
 6436:                     $crslimit = ' ';
 6437:                     $selflimit = ' ';
 6438:                     $nolimit = ' checked="checked" ';
 6439:                 }
 6440:                 $output .= '<table><tr><td><label>'.
 6441:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.$disabled.'/>'.
 6442:                            &mt('No limit').'</label></td><td><label>'.
 6443:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.$disabled.'/>'.
 6444:                            &mt('Limit by total students').'</label></td><td><label>'.
 6445:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.$disabled.'/>'.
 6446:                            &mt('Limit by total self-enrolled students').
 6447:                            '</td></tr><tr>'.
 6448:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
 6449:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
 6450:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'"'.$disabled.' /></td></tr></table>';
 6451:             }
 6452:             $output .= &Apache::lonhtmlcommon::row_closure(1);
 6453:         }
 6454:     }
 6455:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<br />';
 6456:     unless ($readonly) {
 6457:         $output .= '<input type="button" name="selfenrollconf" value="'
 6458:                    .&mt('Save').'" onclick="validate_types(this.form);" />';
 6459:     }
 6460:     $output .= '<input type="hidden" name="action" value="selfenroll" />'
 6461:               .'<input type="hidden" name="state" value="done" />'."\n"
 6462:               .$additional.'</form>';
 6463:     $r->print($output);
 6464:     return;
 6465: }
 6466: 
 6467: sub get_noedit_fields {
 6468:     my ($cdom,$cnum,$crstype,$row) = @_;
 6469:     my %noedit;
 6470:     if (ref($row) eq 'ARRAY') {
 6471:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
 6472:                                                            'internal.selfenrollmgrdc',
 6473:                                                            'internal.selfenrollmgrcc'],$cdom,$cnum);
 6474:         my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
 6475:         my (%specific_managebydc,%specific_managebycc,%default_managebydc);
 6476:         map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
 6477:         map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
 6478:         my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 6479:         map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
 6480: 
 6481:         foreach my $item (@{$row}) {
 6482:             next if ($specific_managebycc{$item});
 6483:             if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
 6484:                 $noedit{$item} = 1;
 6485:             }
 6486:         }
 6487:     }
 6488:     return %noedit;
 6489: } 
 6490: 
 6491: sub visible_in_stdcat {
 6492:     my ($cdom,$cnum,$domconf) = @_;
 6493:     my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
 6494:     unless (ref($domconf) eq 'HASH') {
 6495:         return ($visible,$cansetvis,\@vismsgs);
 6496:     }
 6497:     if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6498:         if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
 6499:             $settable{'togglecats'} = 1;
 6500:         }
 6501:         if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
 6502:             $settable{'categorize'} = 1;
 6503:         }
 6504:         $cathash = $domconf->{'coursecategories'}{'cats'};
 6505:     }
 6506:     if ($settable{'togglecats'} && $settable{'categorize'}) {
 6507:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
 6508:     } elsif ($settable{'togglecats'}) {
 6509:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
 6510:     } elsif ($settable{'categorize'}) {
 6511:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
 6512:     } else {
 6513:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
 6514:     }
 6515:      
 6516:     my %currsettings =
 6517:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
 6518:                              $cdom,$cnum);
 6519:     $visible = 0;
 6520:     if ($currsettings{'internal.coursecode'} ne '') {
 6521:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6522:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6523:             if (ref($cathash) eq 'HASH') {
 6524:                 if ($cathash->{'instcode::0'} eq '') {
 6525:                     push(@vismsgs,'dc_addinst'); 
 6526:                 } else {
 6527:                     $visible = 1;
 6528:                 }
 6529:             } else {
 6530:                 $visible = 1;
 6531:             }
 6532:         } else {
 6533:             $visible = 1;
 6534:         }
 6535:     } else {
 6536:         if (ref($cathash) eq 'HASH') {
 6537:             if ($cathash->{'instcode::0'} ne '') {
 6538:                 push(@vismsgs,'dc_instcode');
 6539:             }
 6540:         } else {
 6541:             push(@vismsgs,'dc_instcode');
 6542:         }
 6543:     }
 6544:     if ($currsettings{'categories'} ne '') {
 6545:         my $cathash;
 6546:         if (ref($domconf->{'coursecategories'}) eq 'HASH') {
 6547:             $cathash = $domconf->{'coursecategories'}{'cats'};
 6548:             if (ref($cathash) eq 'HASH') {
 6549:                 if (keys(%{$cathash}) == 0) {
 6550:                     push(@vismsgs,'dc_catalog');
 6551:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
 6552:                     push(@vismsgs,'dc_categories');
 6553:                 } else {
 6554:                     my @currcategories = split('&',$currsettings{'categories'});
 6555:                     my $matched = 0;
 6556:                     foreach my $cat (@currcategories) {
 6557:                         if ($cathash->{$cat} ne '') {
 6558:                             $visible = 1;
 6559:                             $matched = 1;
 6560:                             last;
 6561:                         }
 6562:                     }
 6563:                     if (!$matched) {
 6564:                         if ($settable{'categorize'}) { 
 6565:                             push(@vismsgs,'chgcat');
 6566:                         } else {
 6567:                             push(@vismsgs,'dc_chgcat');
 6568:                         }
 6569:                     }
 6570:                 }
 6571:             }
 6572:         }
 6573:     } else {
 6574:         if (ref($cathash) eq 'HASH') {
 6575:             if ((keys(%{$cathash}) > 1) || 
 6576:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
 6577:                 if ($settable{'categorize'}) {
 6578:                     push(@vismsgs,'addcat');
 6579:                 } else {
 6580:                     push(@vismsgs,'dc_addcat');
 6581:                 }
 6582:             }
 6583:         }
 6584:     }
 6585:     if ($currsettings{'hidefromcat'} eq 'yes') {
 6586:         $visible = 0;
 6587:         if ($settable{'togglecats'}) {
 6588:             unshift(@vismsgs,'unhide');
 6589:         } else {
 6590:             unshift(@vismsgs,'dc_unhide')
 6591:         }
 6592:     }
 6593:     return ($visible,$cansetvis,\@vismsgs);
 6594: }
 6595: 
 6596: sub cat_visibility {
 6597:     my %visactions = &Apache::lonlocal::texthash(
 6598:                    vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
 6599:                    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.',
 6600:                    miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
 6601:                    none => 'Display of a course catalog is disabled for this domain.',
 6602:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
 6603:                    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.',
 6604:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
 6605:                    take => 'Take the following action to ensure the course appears in the Catalog:',
 6606:                    dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
 6607:                    dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
 6608:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
 6609:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
 6610:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
 6611:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
 6612:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
 6613:                    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',
 6614:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
 6615:     );
 6616:     $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>"');
 6617:     $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>"');
 6618:     $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
 6619:     return \%visactions;
 6620: }
 6621: 
 6622: sub new_selfenroll_dom_row {
 6623:     my ($newdom,$num) = @_;
 6624:     my $domdesc = &Apache::lonnet::domain($newdom);
 6625:     my $output;
 6626:     if ($domdesc ne '') {
 6627:         $output .= &Apache::loncommon::start_data_table_row()
 6628:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
 6629:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
 6630:                    .'" value="'.$newdom.'" /></span><br />'
 6631:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
 6632:                    .'name="selfenroll_activate" value="'.$num.'" '
 6633:                    .'onchange="javascript:update_types('
 6634:                    ."'selfenroll_activate','$num'".');" />'
 6635:                    .&mt('Activate').'</label></span></td>';
 6636:         my @currinsttypes;
 6637:         $output .= '<td>'.&mt('User types:').'<br />'
 6638:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
 6639:                    .&Apache::loncommon::end_data_table_row();
 6640:     }
 6641:     return $output;
 6642: }
 6643: 
 6644: sub selfenroll_inst_types {
 6645:     my ($num,$currdom,$currinsttypes,$readonly) = @_;
 6646:     my $output;
 6647:     my $numinrow = 4;
 6648:     my $count = 0;
 6649:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
 6650:     my $othervalue = 'any';
 6651:     my $disabled;
 6652:     if ($readonly) {
 6653:         $disabled = ' disabled="disabled"';
 6654:     }
 6655:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6656:         if (keys(%{$usertypes}) > 0) {
 6657:             $othervalue = 'other';
 6658:         }
 6659:         $output .= '<table><tr>';
 6660:         foreach my $type (@{$types}) {
 6661:             if (($count > 0) && ($count%$numinrow == 0)) {
 6662:                 $output .= '</tr><tr>';
 6663:             }
 6664:             if (defined($usertypes->{$type})) {
 6665:                 my $esc_type = &escape($type);
 6666:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
 6667:                            $esc_type.'" ';
 6668:                 if (ref($currinsttypes) eq 'ARRAY') {
 6669:                     if (@{$currinsttypes} > 0) {
 6670:                         if (grep(/^any$/,@{$currinsttypes})) {
 6671:                             $output .= 'checked="checked"';
 6672:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
 6673:                             $output .= 'checked="checked"';
 6674:                         }
 6675:                     } else {
 6676:                         $output .= 'checked="checked"';
 6677:                     }
 6678:                 }
 6679:                 $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$usertypes->{$type}.'</label></span></td>';
 6680:             }
 6681:             $count ++;
 6682:         }
 6683:         if (($count > 0) && ($count%$numinrow == 0)) {
 6684:             $output .= '</tr><tr>';
 6685:         }
 6686:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
 6687:         if (ref($currinsttypes) eq 'ARRAY') {
 6688:             if (@{$currinsttypes} > 0) {
 6689:                 if (grep(/^any$/,@{$currinsttypes})) { 
 6690:                     $output .= ' checked="checked"';
 6691:                 } elsif ($othervalue eq 'other') {
 6692:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
 6693:                         $output .= ' checked="checked"';
 6694:                     }
 6695:                 }
 6696:             } else {
 6697:                 $output .= ' checked="checked"';
 6698:             }
 6699:         } else {
 6700:             $output .= ' checked="checked"';
 6701:         }
 6702:         $output .= ' name="selfenroll_types_'.$num.'"'.$disabled.' />'.$othertitle.'</label></span></td></tr></table>';
 6703:     }
 6704:     return $output;
 6705: }
 6706: 
 6707: sub selfenroll_date_forms {
 6708:     my ($startform,$endform) = @_;
 6709:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
 6710:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
 6711:                                                     'LC_oddrow_value')."\n".
 6712:                   $startform."\n".
 6713:                   &Apache::lonhtmlcommon::row_closure(1).
 6714:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
 6715:                                                    'LC_oddrow_value')."\n".
 6716:                   $endform."\n".
 6717:                   &Apache::lonhtmlcommon::row_closure(1).
 6718:                   &Apache::lonhtmlcommon::end_pick_box();
 6719:     return $output;
 6720: }
 6721: 
 6722: sub print_userchangelogs_display {
 6723:     my ($r,$context,$permission,$brcrum) = @_;
 6724:     my $formname = 'rolelog';
 6725:     my ($username,$domain,$crstype,$viewablesec,%roleslog);
 6726:     if ($context eq 'domain') {
 6727:         $domain = $env{'request.role.domain'};
 6728:         %roleslog=&Apache::lonnet::dump_dom('nohist_rolelog',$domain);
 6729:     } else {
 6730:         if ($context eq 'course') { 
 6731:             $domain = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6732:             $username = $env{'course.'.$env{'request.course.id'}.'.num'};
 6733:             $crstype = &Apache::loncommon::course_type();
 6734:             $viewablesec = &Apache::lonuserutils::viewable_section($permission);
 6735:             my %saveable_parameters = ('show' => 'scalar',);
 6736:             &Apache::loncommon::store_course_settings('roles_log',
 6737:                                                       \%saveable_parameters);
 6738:             &Apache::loncommon::restore_course_settings('roles_log',
 6739:                                                         \%saveable_parameters);
 6740:         } elsif ($context eq 'author') {
 6741:             $domain = $env{'user.domain'}; 
 6742:             if ($env{'request.role'} =~ m{^au\./\Q$domain\E/$}) {
 6743:                 $username = $env{'user.name'};
 6744:             } else {
 6745:                 undef($domain);
 6746:             }
 6747:         }
 6748:         if ($domain ne '' && $username ne '') { 
 6749:             %roleslog=&Apache::lonnet::dump('nohist_rolelog',$domain,$username);
 6750:         }
 6751:     }
 6752:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 6753: 
 6754:     my $helpitem;
 6755:     if ($context eq 'course') {
 6756:         $helpitem = 'Course_User_Logs';
 6757:     } elsif ($context eq 'domain') {
 6758:         $helpitem = 'Domain_Role_Logs';
 6759:     } elsif ($context eq 'author') {
 6760:         $helpitem = 'Author_User_Logs';
 6761:     }
 6762:     push (@{$brcrum},
 6763:              {href => '/adm/createuser?action=changelogs',
 6764:               text => 'User Management Logs',
 6765:               help => $helpitem});
 6766:     my $bread_crumbs_component = 'User Changes';
 6767:     my $args = { bread_crumbs           => $brcrum,
 6768:                  bread_crumbs_component => $bread_crumbs_component};
 6769: 
 6770:     # Create navigation javascript
 6771:     my $jsnav = &userlogdisplay_js($formname);
 6772: 
 6773:     my $jscript = (<<ENDSCRIPT);
 6774: <script type="text/javascript">
 6775: // <![CDATA[
 6776: $jsnav
 6777: // ]]>
 6778: </script>
 6779: ENDSCRIPT
 6780: 
 6781:     # print page header
 6782:     $r->print(&header($jscript,$args));
 6783: 
 6784:     # set defaults
 6785:     my $now = time();
 6786:     my $defstart = $now - (7*24*3600); #7 days ago 
 6787:     my %defaults = (
 6788:                      page               => '1',
 6789:                      show               => '10',
 6790:                      role               => 'any',
 6791:                      chgcontext         => 'any',
 6792:                      rolelog_start_date => $defstart,
 6793:                      rolelog_end_date   => $now,
 6794:                    );
 6795:     my $more_records = 0;
 6796: 
 6797:     # set current
 6798:     my %curr;
 6799:     foreach my $item ('show','page','role','chgcontext') {
 6800:         $curr{$item} = $env{'form.'.$item};
 6801:     }
 6802:     my ($startdate,$enddate) = 
 6803:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
 6804:     $curr{'rolelog_start_date'} = $startdate;
 6805:     $curr{'rolelog_end_date'} = $enddate;
 6806:     foreach my $key (keys(%defaults)) {
 6807:         if ($curr{$key} eq '') {
 6808:             $curr{$key} = $defaults{$key};
 6809:         }
 6810:     }
 6811:     my (%whodunit,%changed,$version);
 6812:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
 6813:     my ($minshown,$maxshown);
 6814:     $minshown = 1;
 6815:     my $count = 0;
 6816:     if ($curr{'show'} =~ /\D/) {
 6817:         $curr{'page'} = 1;
 6818:     } else {
 6819:         $maxshown = $curr{'page'} * $curr{'show'};
 6820:         if ($curr{'page'} > 1) {
 6821:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 6822:         }
 6823:     }
 6824: 
 6825:     # Form Header
 6826:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 6827:               &role_display_filter($context,$formname,$domain,$username,\%curr,
 6828:                                    $version,$crstype));
 6829: 
 6830:     my $showntableheader = 0;
 6831: 
 6832:     # Table Header
 6833:     my $tableheader = 
 6834:         &Apache::loncommon::start_data_table_header_row()
 6835:        .'<th>&nbsp;</th>'
 6836:        .'<th>'.&mt('When').'</th>'
 6837:        .'<th>'.&mt('Who made the change').'</th>'
 6838:        .'<th>'.&mt('Changed User').'</th>'
 6839:        .'<th>'.&mt('Role').'</th>';
 6840: 
 6841:     if ($context eq 'course') {
 6842:         $tableheader .= '<th>'.&mt('Section').'</th>';
 6843:     }
 6844:     $tableheader .=
 6845:         '<th>'.&mt('Context').'</th>'
 6846:        .'<th>'.&mt('Start').'</th>'
 6847:        .'<th>'.&mt('End').'</th>'
 6848:        .&Apache::loncommon::end_data_table_header_row();
 6849: 
 6850:     # Display user change log data
 6851:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
 6852:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
 6853:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
 6854:         if ($curr{'show'} !~ /\D/) {
 6855:             if ($count >= $curr{'page'} * $curr{'show'}) {
 6856:                 $more_records = 1;
 6857:                 last;
 6858:             }
 6859:         }
 6860:         if ($curr{'role'} ne 'any') {
 6861:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
 6862:         }
 6863:         if ($curr{'chgcontext'} ne 'any') {
 6864:             if ($curr{'chgcontext'} eq 'selfenroll') {
 6865:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
 6866:             } else {
 6867:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
 6868:             }
 6869:         }
 6870:         if (($context eq 'course') && ($viewablesec ne '')) {
 6871:             next if ($roleslog{$id}{'logentry'}{'section'} ne $viewablesec);
 6872:         }
 6873:         $count ++;
 6874:         next if ($count < $minshown);
 6875:         unless ($showntableheader) {
 6876:             $r->print(&Apache::loncommon::start_data_table()
 6877:                      .$tableheader);
 6878:             $r->rflush();
 6879:             $showntableheader = 1;
 6880:         }
 6881:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
 6882:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
 6883:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
 6884:         }
 6885:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
 6886:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
 6887:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
 6888:         }
 6889:         my $sec = $roleslog{$id}{'logentry'}{'section'};
 6890:         if ($sec eq '') {
 6891:             $sec = &mt('None');
 6892:         }
 6893:         my ($rolestart,$roleend);
 6894:         if ($roleslog{$id}{'delflag'}) {
 6895:             $rolestart = &mt('deleted');
 6896:             $roleend = &mt('deleted');
 6897:         } else {
 6898:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
 6899:             $roleend = $roleslog{$id}{'logentry'}{'end'};
 6900:             if ($rolestart eq '' || $rolestart == 0) {
 6901:                 $rolestart = &mt('No start date'); 
 6902:             } else {
 6903:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
 6904:             }
 6905:             if ($roleend eq '' || $roleend == 0) { 
 6906:                 $roleend = &mt('No end date');
 6907:             } else {
 6908:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
 6909:             }
 6910:         }
 6911:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
 6912:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
 6913:             $chgcontext = 'selfenroll';
 6914:         }
 6915:         my %lt = &rolechg_contexts($context,$crstype);
 6916:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
 6917:             $chgcontext = $lt{$chgcontext};
 6918:         }
 6919:         $r->print(
 6920:             &Apache::loncommon::start_data_table_row()
 6921:            .'<td>'.$count.'</td>'
 6922:            .'<td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td>'
 6923:            .'<td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td>'
 6924:            .'<td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td>'
 6925:            .'<td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'},$crstype).'</td>');
 6926:         if ($context eq 'course') { 
 6927:             $r->print('<td>'.$sec.'</td>');
 6928:         }
 6929:         $r->print(
 6930:             '<td>'.$chgcontext.'</td>'
 6931:            .'<td>'.$rolestart.'</td>'
 6932:            .'<td>'.$roleend.'</td>'
 6933:            .&Apache::loncommon::end_data_table_row()."\n");
 6934:     }
 6935: 
 6936:     if ($showntableheader) { # Table footer, if content displayed above
 6937:         $r->print(&Apache::loncommon::end_data_table().
 6938:                   &userlogdisplay_navlinks(\%curr,$more_records));
 6939:     } else { # No content displayed above
 6940:         $r->print('<p class="LC_info">'
 6941:                  .&mt('There are no records to display.')
 6942:                  .'</p>'
 6943:         );
 6944:     }
 6945: 
 6946:     # Form Footer
 6947:     $r->print( 
 6948:         '<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 6949:        .'<input type="hidden" name="action" value="changelogs" />'
 6950:        .'</form>');
 6951:     return;
 6952: }
 6953: 
 6954: sub print_useraccesslogs_display {
 6955:     my ($r,$uname,$udom,$permission,$brcrum) = @_;
 6956:     my $formname = 'accesslog';
 6957:     my $form = 'document.accesslog';
 6958: 
 6959: # set breadcrumbs
 6960:     my %breadcrumb_text = &singleuser_breadcrumb('','domain',$udom);
 6961:     my $prevphasestr;
 6962:     if ($env{'form.popup'}) {
 6963:         $brcrum = [];
 6964:     } else {
 6965:         push (@{$brcrum},
 6966:             {href => "javascript:backPage($form)",
 6967:              text => $breadcrumb_text{'search'}});
 6968:         my @prevphases;
 6969:         if ($env{'form.prevphases'}) {
 6970:             @prevphases = split(/,/,$env{'form.prevphases'});
 6971:             $prevphasestr = $env{'form.prevphases'};
 6972:         }
 6973:         if (($env{'form.phase'} eq 'userpicked') || (grep(/^userpicked$/,@prevphases))) {
 6974:             push(@{$brcrum},
 6975:                   {href => "javascript:backPage($form,'get_user_info','select')",
 6976:                    text => $breadcrumb_text{'userpicked'}});
 6977:             if ($env{'form.phase'} eq 'userpicked') {
 6978:                 $prevphasestr = 'userpicked';
 6979:             }
 6980:         }
 6981:     }
 6982:     push(@{$brcrum},
 6983:              {href => '/adm/createuser?action=accesslogs',
 6984:               text => 'User access logs',
 6985:               help => 'Domain_User_Access_Logs'});
 6986:     my $bread_crumbs_component = 'User Access Logs';
 6987:     my $args = { bread_crumbs           => $brcrum,
 6988:                  bread_crumbs_component => 'User Management'};
 6989:     if ($env{'form.popup'}) {
 6990:         $args->{'no_nav_bar'} = 1;
 6991:         $args->{'bread_crumbs_nomenu'} = 1;
 6992:     }
 6993: 
 6994: # set javascript
 6995:     my ($jsback,$elements) = &crumb_utilities();
 6996:     my $jsnav = &userlogdisplay_js($formname);
 6997: 
 6998:     my $jscript = (<<ENDSCRIPT);
 6999: <script type="text/javascript">
 7000: // <![CDATA[
 7001: 
 7002: $jsback
 7003: $jsnav
 7004: 
 7005: // ]]>
 7006: </script>
 7007: 
 7008: ENDSCRIPT
 7009: 
 7010: # print page header
 7011:     $r->print(&header($jscript,$args));
 7012: 
 7013: # early out unless log data can be displayed.
 7014:     unless ($permission->{'activity'}) {
 7015:         $r->print('<p class="LC_warning">'
 7016:                  .&mt('You do not have rights to display user access logs.')
 7017:                  .'</p>');
 7018:         if ($env{'form.popup'}) {
 7019:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7020:         } else {
 7021:             $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7022:         }
 7023:         return;
 7024:     }
 7025: 
 7026:     unless ($udom eq $env{'request.role.domain'}) {
 7027:         $r->print('<p class="LC_warning">'
 7028:                  .&mt("User's domain must match role's domain")
 7029:                  .'</p>'
 7030:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7031:         return;
 7032:     }
 7033: 
 7034:     if (($uname eq '') || ($udom eq '')) {
 7035:         $r->print('<p class="LC_warning">'
 7036:                  .&mt('Invalid username or domain')
 7037:                  .'</p>'
 7038:                  .&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7039:         return;
 7040:     }
 7041: 
 7042:     if (&Apache::lonnet::privileged($uname,$udom,
 7043:                                     [$env{'request.role.domain'}],['dc','su'])) {
 7044:         unless (&Apache::lonnet::privileged($env{'user.name'},$env{'user.domain'},
 7045:                                             [$env{'request.role.domain'}],['dc','su'])) {
 7046:             $r->print('<p class="LC_warning">'
 7047:                  .&mt('You need to be a privileged user to display user access logs for [_1]',
 7048:                       &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),
 7049:                                                          $uname,$udom))
 7050:                  .'</p>');
 7051:             if ($env{'form.popup'}) {
 7052:                 $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
 7053:             } else {
 7054:                 $r->print(&earlyout_accesslog_form($formname,$prevphasestr,$udom));
 7055:             }
 7056:             return;
 7057:         }
 7058:     }
 7059: 
 7060: # set defaults
 7061:     my $now = time();
 7062:     my $defstart = $now - (7*24*3600);
 7063:     my %defaults = (
 7064:                      page                 => '1',
 7065:                      show                 => '10',
 7066:                      activity             => 'any',
 7067:                      accesslog_start_date => $defstart,
 7068:                      accesslog_end_date   => $now,
 7069:                    );
 7070:     my $more_records = 0;
 7071: 
 7072: # set current
 7073:     my %curr;
 7074:     foreach my $item ('show','page','activity') {
 7075:         $curr{$item} = $env{'form.'.$item};
 7076:     }
 7077:     my ($startdate,$enddate) =
 7078:         &Apache::lonuserutils::get_dates_from_form('accesslog_start_date','accesslog_end_date');
 7079:     $curr{'accesslog_start_date'} = $startdate;
 7080:     $curr{'accesslog_end_date'} = $enddate;
 7081:     foreach my $key (keys(%defaults)) {
 7082:         if ($curr{$key} eq '') {
 7083:             $curr{$key} = $defaults{$key};
 7084:         }
 7085:     }
 7086:     my ($minshown,$maxshown);
 7087:     $minshown = 1;
 7088:     my $count = 0;
 7089:     if ($curr{'show'} =~ /\D/) {
 7090:         $curr{'page'} = 1;
 7091:     } else {
 7092:         $maxshown = $curr{'page'} * $curr{'show'};
 7093:         if ($curr{'page'} > 1) {
 7094:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 7095:         }
 7096:     }
 7097: 
 7098: # form header
 7099:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">'.
 7100:               &activity_display_filter($formname,\%curr));
 7101: 
 7102:     my $showntableheader = 0;
 7103:     my ($nav_script,$nav_links);
 7104: 
 7105: # table header
 7106:     my $tableheader = '<h3>'.
 7107:         &mt('User access logs for: [_1]',
 7108:             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom)).'</h3>'
 7109:        .&Apache::loncommon::start_data_table_header_row()
 7110:        .'<th>&nbsp;</th>'
 7111:        .'<th>'.&mt('When').'</th>'
 7112:        .'<th>'.&mt('HostID').'</th>'
 7113:        .'<th>'.&mt('Event').'</th>'
 7114:        .'<th>'.&mt('Other data').'</th>'
 7115:        .&Apache::loncommon::end_data_table_header_row();
 7116: 
 7117:     my %filters=(
 7118:         start  => $curr{'accesslog_start_date'},
 7119:         end    => $curr{'accesslog_end_date'},
 7120:         action => $curr{'activity'},
 7121:     );
 7122: 
 7123:     my $reply = &Apache::lonnet::userlog_query($uname,$udom,%filters);
 7124:     unless ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7125:         my (%courses,%missing);
 7126:         my @results = split(/\&/,$reply);
 7127:         foreach my $item (reverse(@results)) {
 7128:             my ($timestamp,$host,$event) = split(/:/,$item);
 7129:             next unless ($event =~ /^(Log|Role)/);
 7130:             if ($curr{'show'} !~ /\D/) {
 7131:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 7132:                     $more_records = 1;
 7133:                     last;
 7134:                 }
 7135:             }
 7136:             $count ++;
 7137:             next if ($count < $minshown);
 7138:             unless ($showntableheader) {
 7139:                 $r->print($nav_script
 7140:                          .&Apache::loncommon::start_data_table()
 7141:                          .$tableheader);
 7142:                 $r->rflush();
 7143:                 $showntableheader = 1;
 7144:             }
 7145:             my ($shown,$extra);
 7146:             my ($event,$data) = split(/\s+/,&unescape($event),2);
 7147:             if ($event eq 'Role') {
 7148:                 my ($rolecode,$extent) = split(/\./,$data,2);
 7149:                 next if ($extent eq '');
 7150:                 my ($crstype,$desc,$info);
 7151:                 if ($extent =~ m{^/($match_domain)/($match_courseid)(?:/(\w+)|)$}) {
 7152:                     my ($cdom,$cnum,$sec) = ($1,$2,$3);
 7153:                     my $cid = $cdom.'_'.$cnum;
 7154:                     if (exists($courses{$cid})) {
 7155:                         $crstype = $courses{$cid}{'type'};
 7156:                         $desc = $courses{$cid}{'description'};
 7157:                     } elsif ($missing{$cid}) {
 7158:                         $crstype = 'Course';
 7159:                         $desc = 'Course/Community';
 7160:                     } else {
 7161:                         my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7162:                         if (ref($crsinfo{$cdom.'_'.$cnum}) eq 'HASH') {
 7163:                             $courses{$cid} = $crsinfo{$cid};
 7164:                             $crstype = $crsinfo{$cid}{'type'};
 7165:                             $desc = $crsinfo{$cid}{'description'};
 7166:                         } else {
 7167:                             $missing{$cid} = 1;
 7168:                         }
 7169:                     }
 7170:                     $extra = &mt($crstype).': <a href="/public/'.$cdom.'/'.$cnum.'/syllabus">'.$desc.'</a>';
 7171:                     if ($sec ne '') {
 7172:                        $extra .= ' ('.&mt('Section: [_1]',$sec).')';
 7173:                     }
 7174:                 } elsif ($extent =~ m{^/($match_domain)/($match_username|$)}) {
 7175:                     my ($dom,$name) = ($1,$2);
 7176:                     if ($rolecode eq 'au') {
 7177:                         $extra = '';
 7178:                     } elsif ($rolecode =~ /^(ca|aa)$/) {
 7179:                         $extra = &mt('Authoring Space: [_1]',$name.':'.$dom);
 7180:                     } elsif ($rolecode =~ /^(li|dg|dh|dc|sc)$/) {
 7181:                         $extra = &mt('Domain: [_1]',$dom);
 7182:                     }
 7183:                 }
 7184:                 my $rolename;
 7185:                 if ($rolecode =~ m{^cr/($match_domain)/($match_username)/(\w+)}) {
 7186:                     my $role = $3;
 7187:                     my $owner = "($2:$1)";
 7188:                     if ($2 eq $1.'-domainconfig') {
 7189:                         $owner = '(ad hoc)';
 7190:                     }
 7191:                     $rolename = &mt('Custom role: [_1]',$role.' '.$owner);
 7192:                 } else {
 7193:                     $rolename = &Apache::lonnet::plaintext($rolecode,$crstype);
 7194:                 }
 7195:                 $shown = &mt('Role selection: [_1]',$rolename);
 7196:             } else {
 7197:                 $shown = &mt($event);
 7198:                 if ($data =~ /^webdav/) {
 7199:                     my ($path,$clientip) = split(/\s+/,$data,2);
 7200:                     $path =~ s/^webdav//;
 7201:                     if ($clientip ne '') {
 7202:                         $extra = &mt('Client IP address: [_1]',$clientip);
 7203:                     }
 7204:                     if ($path ne '') {
 7205:                         $shown .= ' '.&mt('(WebDAV access to [_1])',$path);
 7206:                     }
 7207:                 } elsif ($data ne '') {
 7208:                     $extra = &mt('Client IP address: [_1]',$data);
 7209:                 }
 7210:             }
 7211:             $r->print(
 7212:             &Apache::loncommon::start_data_table_row()
 7213:            .'<td>'.$count.'</td>'
 7214:            .'<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>'
 7215:            .'<td>'.$host.'</td>'
 7216:            .'<td>'.$shown.'</td>'
 7217:            .'<td>'.$extra.'</td>'
 7218:            .&Apache::loncommon::end_data_table_row()."\n");
 7219:         }
 7220:     }
 7221: 
 7222:     if ($showntableheader) { # Table footer, if content displayed above
 7223:         $r->print(&Apache::loncommon::end_data_table().
 7224:                   &userlogdisplay_navlinks(\%curr,$more_records));
 7225:     } else { # No content displayed above
 7226:         $r->print('<p class="LC_info">'
 7227:                  .&mt('There are no records to display.')
 7228:                  .'</p>');
 7229:     }
 7230: 
 7231:     if ($env{'form.popup'} == 1) {
 7232:         $r->print('<input type="hidden" name="popup" value="1" />'."\n");
 7233:     }
 7234: 
 7235:     # Form Footer
 7236:     $r->print(
 7237:         '<input type="hidden" name="currstate" value="" />'
 7238:        .'<input type="hidden" name="accessuname" value="'.$uname.'" />'
 7239:        .'<input type="hidden" name="accessudom" value="'.$udom.'" />'
 7240:        .'<input type="hidden" name="page" value="'.$curr{'page'}.'" />'
 7241:        .'<input type="hidden" name="prevphases" value="'.$prevphasestr.'" />'
 7242:        .'<input type="hidden" name="phase" value="activity" />'
 7243:        .'<input type="hidden" name="action" value="accesslogs" />'
 7244:        .'<input type="hidden" name="srchdomain" value="'.$udom.'" />'
 7245:        .'<input type="hidden" name="srchby" value="'.$env{'form.srchby'}.'" />'
 7246:        .'<input type="hidden" name="srchtype" value="'.$env{'form.srchtype'}.'" />'
 7247:        .'<input type="hidden" name="srchterm" value="'.&HTML::Entities::encode($env{'form.srchterm'},'<>"&').'" />'
 7248:        .'<input type="hidden" name="srchin" value="'.$env{'form.srchin'}.'" />'
 7249:        .'</form>');
 7250:     return;
 7251: }
 7252: 
 7253: sub earlyout_accesslog_form {
 7254:     my ($formname,$prevphasestr,$udom) = @_;
 7255:     my $srchterm = &HTML::Entities::encode($env{'form.srchterm'},'<>"&');
 7256:    return <<"END";
 7257: <form action="/adm/createuser" method="post" name="$formname">
 7258: <input type="hidden" name="currstate" value="" />
 7259: <input type="hidden" name="prevphases" value="$prevphasestr" />
 7260: <input type="hidden" name="phase" value="activity" />
 7261: <input type="hidden" name="action" value="accesslogs" />
 7262: <input type="hidden" name="srchdomain" value="$udom" />
 7263: <input type="hidden" name="srchby" value="$env{'form.srchby'}" />
 7264: <input type="hidden" name="srchtype" value="$env{'form.srchtype'}" />
 7265: <input type="hidden" name="srchterm" value="$srchterm" />
 7266: <input type="hidden" name="srchin" value="$env{'form.srchin'}" />
 7267: </form>
 7268: END
 7269: }
 7270: 
 7271: sub activity_display_filter {
 7272:     my ($formname,$curr) = @_;
 7273:     my $nolink = 1;
 7274:     my $output = '<table><tr><td valign="top">'.
 7275:                  '<span class="LC_nobreak"><b>'.&mt('Actions/page:').'</b></span><br />'.
 7276:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7277:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7278:                  '</td><td>&nbsp;&nbsp;</td>';
 7279:     my $startform =
 7280:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_start_date',
 7281:                                             $curr->{'accesslog_start_date'},undef,
 7282:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7283:     my $endform =
 7284:         &Apache::lonhtmlcommon::date_setter($formname,'accesslog_end_date',
 7285:                                             $curr->{'accesslog_end_date'},undef,
 7286:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7287:     my %lt = &Apache::lonlocal::texthash (
 7288:                                           activity => 'Activity',
 7289:                                           Role     => 'Role selection',
 7290:                                           log      => 'Log-in or Logout',
 7291:     );
 7292:     $output .= '<td valign="top"><b>'.&mt('Window during which actions occurred:').'</b><br />'.
 7293:                '<table><tr><td>'.&mt('After:').
 7294:                '</td><td>'.$startform.'</td></tr>'.
 7295:                '<tr><td>'.&mt('Before:').'</td>'.
 7296:                '<td>'.$endform.'</td></tr></table>'.
 7297:                '</td>'.
 7298:                '<td>&nbsp;&nbsp;</td>'.
 7299:                '<td valign="top"><b>'.&mt('Activities').'</b><br />'.
 7300:                '<select name="activity"><option value="any"';
 7301:     if ($curr->{'activity'} eq 'any') {
 7302:         $output .= ' selected="selected"';
 7303:     }
 7304:     $output .= '>'.&mt('Any').'</option>'."\n";
 7305:     foreach my $activity ('Role','log') {
 7306:         my $selstr = '';
 7307:         if ($activity eq $curr->{'activity'}) {
 7308:             $selstr = ' selected="selected"';
 7309:         }
 7310:         $output .= '<option value="'.$activity.'"'.$selstr.'>'.$lt{$activity}.'</option>';
 7311:     }
 7312:     $output .= '</select></td>'.
 7313:                '</tr></table>';
 7314:     # Update Display button
 7315:     $output .= '<p>'
 7316:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7317:               .'</p><hr />';
 7318:     return $output;
 7319: }
 7320: 
 7321: sub userlogdisplay_js {
 7322:     my ($formname) = @_;
 7323:     return <<"ENDSCRIPT";
 7324: 
 7325: function chgPage(caller) {
 7326:     if (caller == 'previous') {
 7327:         document.$formname.page.value --;
 7328:     }
 7329:     if (caller == 'next') {
 7330:         document.$formname.page.value ++;
 7331:     }
 7332:     document.$formname.submit();
 7333:     return;
 7334: }
 7335: ENDSCRIPT
 7336: }
 7337: 
 7338: sub userlogdisplay_navlinks {
 7339:     my ($curr,$more_records) = @_;
 7340:     return unless(ref($curr) eq 'HASH');
 7341:     # Navigation Buttons
 7342:     my $nav_links = '<p>';
 7343:     if (($curr->{'page'} > 1) || ($more_records)) {
 7344:         if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
 7345:             $nav_links .= '<input type="button"'
 7346:                          .' onclick="javascript:chgPage('."'previous'".');"'
 7347:                          .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
 7348:                          .'" /> ';
 7349:         }
 7350:         if ($more_records) {
 7351:             $nav_links .= '<input type="button"'
 7352:                          .' onclick="javascript:chgPage('."'next'".');"'
 7353:                          .' value="'.&mt('Next [_1] changes',$curr->{'show'})
 7354:                          .'" />';
 7355:         }
 7356:     }
 7357:     $nav_links .= '</p>';
 7358:     return $nav_links;
 7359: }
 7360: 
 7361: sub role_display_filter {
 7362:     my ($context,$formname,$cdom,$cnum,$curr,$version,$crstype) = @_;
 7363:     my $lctype;
 7364:     if ($context eq 'course') {
 7365:         $lctype = lc($crstype);
 7366:     }
 7367:     my $nolink = 1;
 7368:     my $output = '<table><tr><td valign="top">'.
 7369:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b></span><br />'.
 7370:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 7371:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 7372:                  '</td><td>&nbsp;&nbsp;</td>';
 7373:     my $startform =
 7374:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
 7375:                                             $curr->{'rolelog_start_date'},undef,
 7376:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7377:     my $endform =
 7378:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
 7379:                                             $curr->{'rolelog_end_date'},undef,
 7380:                                             undef,undef,undef,undef,undef,undef,$nolink);
 7381:     my %lt = &rolechg_contexts($context,$crstype);
 7382:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br />'.
 7383:                '<table><tr><td>'.&mt('After:').
 7384:                '</td><td>'.$startform.'</td></tr>'.
 7385:                '<tr><td>'.&mt('Before:').'</td>'.
 7386:                '<td>'.$endform.'</td></tr></table>'.
 7387:                '</td>'.
 7388:                '<td>&nbsp;&nbsp;</td>'.
 7389:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
 7390:                '<select name="role"><option value="any"';
 7391:     if ($curr->{'role'} eq 'any') {
 7392:         $output .= ' selected="selected"';
 7393:     }
 7394:     $output .=  '>'.&mt('Any').'</option>'."\n";
 7395:     my @roles = &Apache::lonuserutils::roles_by_context($context,1,$crstype);
 7396:     foreach my $role (@roles) {
 7397:         my $plrole;
 7398:         if ($role eq 'cr') {
 7399:             $plrole = &mt('Custom Role');
 7400:         } else {
 7401:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 7402:         }
 7403:         my $selstr = '';
 7404:         if ($role eq $curr->{'role'}) {
 7405:             $selstr = ' selected="selected"';
 7406:         }
 7407:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
 7408:     }
 7409:     $output .= '</select></td>'.
 7410:                '<td>&nbsp;&nbsp;</td>'.
 7411:                '<td valign="top"><b>'.
 7412:                &mt('Context:').'</b><br /><select name="chgcontext">';
 7413:     my @posscontexts;
 7414:     if ($context eq 'course') {
 7415:         @posscontexts = ('any','automated','updatenow','createcourse','course','domain','selfenroll','requestcourses');
 7416:     } elsif ($context eq 'domain') {
 7417:         @posscontexts = ('any','domain','requestauthor','domconfig','server');
 7418:     } else {
 7419:         @posscontexts = ('any','author','domain');
 7420:     } 
 7421:     foreach my $chgtype (@posscontexts) {
 7422:         my $selstr = '';
 7423:         if ($curr->{'chgcontext'} eq $chgtype) {
 7424:             $selstr = ' selected="selected"';
 7425:         }
 7426:         if ($context eq 'course') {
 7427:             if (($chgtype eq 'automated') || ($chgtype eq 'updatenow')) {
 7428:                 next if (!&Apache::lonnet::auto_run($cnum,$cdom));
 7429:             }
 7430:         }
 7431:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
 7432:     }
 7433:     $output .= '</select></td>'
 7434:               .'</tr></table>';
 7435: 
 7436:     # Update Display button
 7437:     $output .= '<p>'
 7438:               .'<input type="submit" value="'.&mt('Update Display').'" />'
 7439:               .'</p>';
 7440: 
 7441:     # Server version info
 7442:     my $needsrev = '2.11.0';
 7443:     if ($context eq 'course') {
 7444:         $needsrev = '2.7.0';
 7445:     }
 7446:     
 7447:     $output .= '<p class="LC_info">'
 7448:               .&mt('Only changes made from servers running LON-CAPA [_1] or later are displayed.'
 7449:                   ,$needsrev);
 7450:     if ($version) {
 7451:         $output .= ' '.&mt('This LON-CAPA server is version [_1]',$version);
 7452:     }
 7453:     $output .= '</p><hr />';
 7454:     return $output;
 7455: }
 7456: 
 7457: sub rolechg_contexts {
 7458:     my ($context,$crstype) = @_;
 7459:     my %lt;
 7460:     if ($context eq 'course') {
 7461:         %lt = &Apache::lonlocal::texthash (
 7462:                                              any          => 'Any',
 7463:                                              automated    => 'Automated Enrollment',
 7464:                                              updatenow    => 'Roster Update',
 7465:                                              createcourse => 'Course Creation',
 7466:                                              course       => 'User Management in course',
 7467:                                              domain       => 'User Management in domain',
 7468:                                              selfenroll   => 'Self-enrolled',
 7469:                                              requestcourses => 'Course Request',
 7470:                                          );
 7471:         if ($crstype eq 'Community') {
 7472:             $lt{'createcourse'} = &mt('Community Creation');
 7473:             $lt{'course'} = &mt('User Management in community');
 7474:             $lt{'requestcourses'} = &mt('Community Request');
 7475:         }
 7476:     } elsif ($context eq 'domain') {
 7477:         %lt = &Apache::lonlocal::texthash (
 7478:                                              any           => 'Any',
 7479:                                              domain        => 'User Management in domain',
 7480:                                              requestauthor => 'Authoring Request',
 7481:                                              server        => 'Command line script (DC role)',
 7482:                                              domconfig     => 'Self-enrolled',
 7483:                                          );
 7484:     } else {
 7485:         %lt = &Apache::lonlocal::texthash (
 7486:                                              any    => 'Any',
 7487:                                              domain => 'User Management in domain',
 7488:                                              author => 'User Management by author',
 7489:                                          );
 7490:     } 
 7491:     return %lt;
 7492: }
 7493: 
 7494: sub print_helpdeskaccess_display {
 7495:     my ($r,$permission,$brcrum) = @_;
 7496:     my $formname = 'helpdeskaccess';
 7497:     my $helpitem = 'Course_Helpdesk_Access';
 7498:     push (@{$brcrum},
 7499:              {href => '/adm/createuser?action=helpdesk',
 7500:               text => 'Helpdesk Access',
 7501:               help => $helpitem});
 7502:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 7503:     my $args = { bread_crumbs           => $brcrum,
 7504:                  bread_crumbs_component => $bread_crumbs_component};
 7505: 
 7506:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7507:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7508:     my $confname = $cdom.'-domainconfig';
 7509:     my $crstype = &Apache::loncommon::course_type();
 7510: 
 7511:     my @accesstypes = ('all','dh','da','none');
 7512:     my ($numstatustypes,@jsarray);
 7513:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 7514:     if (ref($types) eq 'ARRAY') {
 7515:         if (@{$types} > 0) {
 7516:             $numstatustypes = scalar(@{$types});
 7517:             push(@accesstypes,'status');
 7518:             @jsarray = ('bystatus');
 7519:         }
 7520:     }
 7521:     my %customroles = &get_domain_customroles($cdom,$confname);
 7522:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 7523:     if (keys(%domhelpdesk)) {
 7524:        push(@accesstypes,('inc','exc'));
 7525:        push(@jsarray,('notinc','notexc'));
 7526:     }
 7527:     push(@jsarray,'privs');
 7528:     my $hiddenstr = join("','",@jsarray);
 7529:     my $rolestr = join("','",sort(keys(%customroles)));
 7530: 
 7531:     my $jscript;
 7532:     my (%settings,%overridden);
 7533:     if (keys(%customroles)) {
 7534:         &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 7535:                                 $types,\%customroles,\%settings,\%overridden);
 7536:         my %jsfull=();
 7537:         my %jslevels= (
 7538:                      course => {},
 7539:                      domain => {},
 7540:                      system => {},
 7541:                     );
 7542:         my %jslevelscurrent=(
 7543:                            course => {},
 7544:                            domain => {},
 7545:                            system => {},
 7546:                           );
 7547:         my (%privs,%jsprivs);
 7548:         &Apache::lonuserutils::custom_role_privs(\%privs,\%jsfull,\%jslevels,\%jslevelscurrent);
 7549:         foreach my $priv (keys(%jsfull)) {
 7550:             if ($jslevels{'course'}{$priv}) {
 7551:                 $jsprivs{$priv} = 1;
 7552:             }
 7553:         }
 7554:         my (%elements,%stored);
 7555:         foreach my $role (keys(%customroles)) {
 7556:             $elements{$role.'_access'} = 'radio';
 7557:             $elements{$role.'_incrs'} = 'radio';
 7558:             if ($numstatustypes) {
 7559:                 $elements{$role.'_status'} = 'checkbox';
 7560:             }
 7561:             if (keys(%domhelpdesk) > 0) {
 7562:                 $elements{$role.'_staff_inc'} = 'checkbox';
 7563:                 $elements{$role.'_staff_exc'} = 'checkbox';
 7564:             }
 7565:             $elements{$role.'_override'} = 'checkbox';
 7566:             if (ref($settings{$role}) eq 'HASH') {
 7567:                 if ($settings{$role}{'access'} ne '') {
 7568:                     my $curraccess = $settings{$role}{'access'};
 7569:                     $stored{$role.'_access'} = $curraccess;
 7570:                     $stored{$role.'_incrs'} = 1;
 7571:                     if ($curraccess eq 'status') {
 7572:                         if (ref($settings{$role}{'status'}) eq 'ARRAY') {
 7573:                             $stored{$role.'_status'} = $settings{$role}{'status'};
 7574:                         }
 7575:                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 7576:                         if (ref($settings{$role}{$curraccess}) eq 'ARRAY') {
 7577:                             $stored{$role.'_staff_'.$curraccess} = $settings{$role}{$curraccess};
 7578:                         }
 7579:                     }
 7580:                 } else {
 7581:                     $stored{$role.'_incrs'} = 0;
 7582:                 }
 7583:                 $stored{$role.'_override'} = [];
 7584:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.adhocpriv.'.$role}) {
 7585:                     if (ref($settings{$role}{'off'}) eq 'ARRAY') {
 7586:                         foreach my $priv (@{$settings{$role}{'off'}}) {
 7587:                             push(@{$stored{$role.'_override'}},$priv);
 7588:                         }
 7589:                     }
 7590:                     if (ref($settings{$role}{'on'}) eq 'ARRAY') {
 7591:                         foreach my $priv (@{$settings{$role}{'on'}}) {
 7592:                             unless (grep(/^$priv$/,@{$stored{$role.'_override'}})) {
 7593:                                 push(@{$stored{$role.'_override'}},$priv);
 7594:                             }
 7595:                         }
 7596:                     }
 7597:                 }
 7598:             } else {
 7599:                 $stored{$role.'_incrs'} = 0;
 7600:             }
 7601:         }
 7602:         $jscript = &Apache::lonhtmlcommon::set_form_elements(\%elements,\%stored);
 7603:     }
 7604: 
 7605:     my $js = <<"ENDJS";
 7606: <script type="text/javascript">
 7607: // <![CDATA[
 7608: $jscript;
 7609: 
 7610: function switchRoleTab(caller,role) {
 7611:     if (document.getElementById(role+'_maindiv')) {
 7612:         if (caller.id != 'LC_current_minitab') {
 7613:             if (document.getElementById('LC_current_minitab')) {
 7614:                 document.getElementById('LC_current_minitab').id=null;
 7615:             }
 7616:             var roledivs = Array('$rolestr');
 7617:             if (roledivs.length > 0) {
 7618:                 for (var i=0; i<roledivs.length; i++) {
 7619:                     if (document.getElementById(roledivs[i]+'_maindiv')) {
 7620:                         document.getElementById(roledivs[i]+'_maindiv').style.display='none';
 7621:                     }
 7622:                 }
 7623:             }
 7624:             caller.id = 'LC_current_minitab';
 7625:             document.getElementById(role+'_maindiv').style.display='block';
 7626:         }
 7627:     }
 7628:     return false;
 7629: }
 7630: 
 7631: function helpdeskAccess(role) {
 7632:     var curraccess = null;
 7633:     if (document.$formname.elements[role+'_access'].length) {
 7634:         for (var i=0; i<document.$formname.elements[role+'_access'].length; i++) {
 7635:             if (document.$formname.elements[role+'_access'][i].checked) {
 7636:                 curraccess = document.$formname.elements[role+'_access'][i].value;
 7637:             }
 7638:         }
 7639:     }
 7640:     var shown = Array();
 7641:     var hidden = Array();
 7642:     if (curraccess == 'none') {
 7643:         hidden = Array ('$hiddenstr');
 7644:     } else {
 7645:         if (curraccess == 'status') {
 7646:             shown = Array ('bystatus','privs');
 7647:             hidden = Array ('notinc','notexc');
 7648:         } else {
 7649:             if (curraccess == 'exc') {
 7650:                 shown = Array ('notexc','privs');
 7651:                 hidden = Array ('notinc','bystatus');
 7652:             }
 7653:             if (curraccess == 'inc') {
 7654:                 shown = Array ('notinc','privs');
 7655:                 hidden = Array ('notexc','bystatus');
 7656:             }
 7657:             if (curraccess == 'all') {
 7658:                 shown = Array ('privs');
 7659:                 hidden = Array ('notinc','notexc','bystatus');
 7660:             }
 7661:         }
 7662:     }
 7663:     if (hidden.length > 0) {
 7664:         for (var i=0; i<hidden.length; i++) {
 7665:             if (document.getElementById(role+'_'+hidden[i])) {
 7666:                 document.getElementById(role+'_'+hidden[i]).style.display = 'none';
 7667:             }
 7668:         }
 7669:     }
 7670:     if (shown.length > 0) {
 7671:         for (var i=0; i<shown.length; i++) {
 7672:             if (document.getElementById(role+'_'+shown[i])) {
 7673:                 if (shown[i] == 'privs') {
 7674:                     document.getElementById(role+'_'+shown[i]).style.display = 'block';
 7675:                 } else {
 7676:                     document.getElementById(role+'_'+shown[i]).style.display = 'inline';
 7677:                 }
 7678:             }
 7679:         }
 7680:     }
 7681:     return;
 7682: }
 7683: 
 7684: function toggleAccess(role) {
 7685:     if ((document.getElementById(role+'_setincrs')) &&
 7686:         (document.getElementById(role+'_setindom'))) {
 7687:         for (var i=0; i<document.$formname.elements[role+'_incrs'].length; i++) {
 7688:             if (document.$formname.elements[role+'_incrs'][i].checked) {
 7689:                 if (document.$formname.elements[role+'_incrs'][i].value == 1) {
 7690:                     document.getElementById(role+'_setindom').style.display = 'none';
 7691:                     document.getElementById(role+'_setincrs').style.display = 'block';
 7692:                 } else {
 7693:                     document.getElementById(role+'_setincrs').style.display = 'none';
 7694:                     document.getElementById(role+'_setindom').style.display = 'block';
 7695:                 }
 7696:                 break;
 7697:             }
 7698:         }
 7699:     }
 7700:     return;
 7701: }
 7702: 
 7703: // ]]>
 7704: </script>
 7705: ENDJS
 7706: 
 7707:     $args->{add_entries} = {onload => "javascript:setFormElements(document.$formname)"};
 7708: 
 7709:     # print page header
 7710:     $r->print(&header($js,$args));
 7711:     # print form header
 7712:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
 7713: 
 7714:     if (keys(%customroles)) {
 7715:         my %lt = &Apache::lonlocal::texthash(
 7716:                     'aco'    => 'As course owner you may override the defaults set in the domain for role usage and/or privileges.',
 7717:                     'rou'    => 'Role usage',
 7718:                     'whi'    => 'Which helpdesk personnel may use this role?',
 7719:                     'udd'    => 'Use domain default',
 7720:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 7721:                     'dh'     => 'All with domain helpdesk role',
 7722:                     'da'     => 'All with domain helpdesk assistant role',
 7723:                     'none'   => 'None',
 7724:                     'status' => 'Determined based on institutional status',
 7725:                     'inc'    => 'Include all, but exclude specific personnel',
 7726:                     'exc'    => 'Exclude all, but include specific personnel',
 7727:                     'hel'    => 'Helpdesk',
 7728:                     'rpr'    => 'Role privileges',
 7729:                  );
 7730:         $lt{'tfh'} = &mt("Custom [_1]ad hoc[_2] course roles available for use by the domain's helpdesk are as follows",'<i>','</i>');
 7731:         my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 7732:         my (%domcurrent,%ordered,%description,%domusage,$disabled);
 7733:         if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 7734:             if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 7735:                 %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 7736:             }
 7737:         }
 7738:         my $count = 0;
 7739:         foreach my $role (sort(keys(%customroles))) {
 7740:             my ($order,$desc,$access_in_dom);
 7741:             if (ref($domcurrent{$role}) eq 'HASH') {
 7742:                 $order = $domcurrent{$role}{'order'};
 7743:                 $desc = $domcurrent{$role}{'desc'};
 7744:                 $access_in_dom = $domcurrent{$role}{'access'};
 7745:             }
 7746:             if ($order eq '') {
 7747:                 $order = $count;
 7748:             }
 7749:             $ordered{$order} = $role;
 7750:             if ($desc ne '') {
 7751:                 $description{$role} = $desc;
 7752:             } else {
 7753:                 $description{$role}= $role;
 7754:             }
 7755:             $count++;
 7756:         }
 7757:         %domusage = &domain_adhoc_access(\%customroles,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 7758:         my @roles_by_num = ();
 7759:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 7760:             push(@roles_by_num,$ordered{$item});
 7761:         }
 7762:         $r->print('<p>'.$lt{'tfh'}.': <i>'.join('</i>, <i>',map { $description{$_}; } @roles_by_num).'</i>.');
 7763:         if ($permission->{'owner'}) {
 7764:             $r->print('<br />'.$lt{'aco'}.'</p><p>');
 7765:             $r->print('<input type="hidden" name="state" value="process" />'.
 7766:                       '<input type="submit" value="'.&mt('Save changes').'" />');
 7767:         } else {
 7768:             if ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'}) {
 7769:                 my ($ownername,$ownerdom) = split(/:/,$env{'course.'.$env{'request.course.id'}.'.internal.courseowner'});
 7770:                 $r->print('<br />'.&mt('The course owner -- [_1] -- can override the default access and/or privileges for these ad hoc roles.',
 7771:                                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($ownername,$ownerdom),$ownername,$ownerdom)));
 7772:             }
 7773:             $disabled = ' disabled="disabled"';
 7774:         }
 7775:         $r->print('</p>');
 7776: 
 7777:         $r->print('<div id="LC_minitab_header"><ul>');
 7778:         my $count = 0;
 7779:         my %visibility;
 7780:         foreach my $role (@roles_by_num) {
 7781:             my $id;
 7782:             if ($count == 0) {
 7783:                 $id=' id="LC_current_minitab"';
 7784:                 $visibility{$role} = ' style="display:block"';
 7785:             } else {
 7786:                 $visibility{$role} = ' style="display:none"';
 7787:             }
 7788:             $count ++;
 7789:             $r->print('<li'.$id.'><a href="#" onclick="javascript:switchRoleTab(this.parentNode,'."'$role'".');">'.$description{$role}.'</a></li>');
 7790:         }
 7791:         $r->print('</ul></div>');
 7792: 
 7793:         foreach my $role (@roles_by_num) {
 7794:             my %usecheck = (
 7795:                              all => ' checked="checked"',
 7796:                            );
 7797:             my %displaydiv = (
 7798:                                 status => 'none',
 7799:                                 inc    => 'none',
 7800:                                 exc    => 'none',
 7801:                                 priv   => 'block',
 7802:                              );
 7803:             my (%selected,$overridden,$incrscheck,$indomcheck,$indomvis,$incrsvis);
 7804:             if (ref($settings{$role}) eq 'HASH') {
 7805:                 if ($settings{$role}{'access'} ne '') {
 7806:                     $indomvis = ' style="display:none"';
 7807:                     $incrsvis = ' style="display:block"';
 7808:                     $incrscheck = ' checked="checked"';
 7809:                     if ($settings{$role}{'access'} ne 'all') {
 7810:                         $usecheck{$settings{$role}{'access'}} = $usecheck{'all'};
 7811:                         delete($usecheck{'all'});
 7812:                         if ($settings{$role}{'access'} eq 'status') {
 7813:                             my $access = 'status';
 7814:                             $displaydiv{$access} = 'inline';
 7815:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7816:                                 $selected{$access} = $settings{$role}{$access};
 7817:                             }
 7818:                         } elsif ($settings{$role}{'access'} =~ /^(inc|exc)$/) {
 7819:                             my $access = $1;
 7820:                             $displaydiv{$access} = 'inline';
 7821:                             if (ref($settings{$role}{$access}) eq 'ARRAY') {
 7822:                                 $selected{$access} = $settings{$role}{$access};
 7823:                             }
 7824:                         } elsif ($settings{$role}{'access'} eq 'none') {
 7825:                             $displaydiv{'priv'} = 'none';
 7826:                         }
 7827:                     }
 7828:                 } else {
 7829:                     $indomcheck = ' checked="checked"';
 7830:                     $indomvis = ' style="display:block"';
 7831:                     $incrsvis = ' style="display:none"';
 7832:                 }
 7833:             } else {
 7834:                 $indomcheck = ' checked="checked"';
 7835:                 $indomvis = ' style="display:block"';
 7836:                 $incrsvis = ' style="display:none"';
 7837:             }
 7838:             $r->print('<div class="LC_left_float" id="'.$role.'_maindiv"'.$visibility{$role}.'>'.
 7839:                       '<fieldset><legend>'.$lt{'rou'}.'</legend>'.
 7840:                       '<p>'.$lt{'whi'}.' <span class="LC_nobreak">'.
 7841:                       '<label><input type="radio" name="'.$role.'_incrs" value="1"'.$incrscheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7842:                       &mt('Set here in [_1]',lc($crstype)).'</label>'.
 7843:                       '<span>'.('&nbsp;'x2).
 7844:                       '<label><input type="radio" name="'.$role.'_incrs" value="0"'.$indomcheck.' onclick="toggleAccess('."'$role'".');"'.$disabled.'>'.
 7845:                       $lt{'udd'}.'</label><span></p>'.
 7846:                       '<div id="'.$role.'_setindom"'.$indomvis.'>'.
 7847:                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span></div>'.
 7848:                       '<div id="'.$role.'_setincrs"'.$incrsvis.'>');
 7849:             foreach my $access (@accesstypes) {
 7850:                 $r->print('<p><label><input type="radio" name="'.$role.'_access" value="'.$access.'" '.$usecheck{$access}.
 7851:                           ' onclick="helpdeskAccess('."'$role'".');"'.$disabled.' />'.$lt{$access}.'</label>');
 7852:                 if ($access eq 'status') {
 7853:                     $r->print('<div id="'.$role.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 7854:                               &Apache::lonuserutils::adhoc_status_types($cdom,undef,$role,$selected{$access},
 7855:                                                                         $othertitle,$usertypes,$types,$disabled).
 7856:                               '</div>');
 7857:                 } elsif (($access eq 'inc') && (keys(%domhelpdesk) > 0)) {
 7858:                     $r->print('<div id="'.$role.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 7859:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7860:                                                                  \%domhelpdesk,$disabled).
 7861:                               '</div>');
 7862:                 } elsif (($access eq 'exc') && (keys(%domhelpdesk) > 0)) {
 7863:                     $r->print('<div id="'.$role.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 7864:                               &Apache::lonuserutils::adhoc_staff($access,undef,$role,$selected{$access},
 7865:                                                                  \%domhelpdesk,$disabled).
 7866:                               '</div>');
 7867:                 }
 7868:                 $r->print('</p>');
 7869:             }
 7870:             $r->print('</div></fieldset>');
 7871:             my %full=();
 7872:             my %levels= (
 7873:                          course => {},
 7874:                          domain => {},
 7875:                          system => {},
 7876:                         );
 7877:             my %levelscurrent=(
 7878:                                course => {},
 7879:                                domain => {},
 7880:                                system => {},
 7881:                               );
 7882:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 7883:             $r->print('<fieldset id="'.$role.'_privs" style="display:'.$displaydiv{'priv'}.'">'.
 7884:                       '<legend>'.$lt{'rpr'}.'</legend>'.
 7885:                       &role_priv_table($role,$permission,$crstype,\%full,\%levels,\%levelscurrent,$overridden{$role}).
 7886:                       '</fieldset></div><div style="padding:0;clear:both;margin:0;border:0"></div>');
 7887:         }
 7888:         if ($permission->{'owner'}) {
 7889:             $r->print('<p><input type="submit" value="'.&mt('Save changes').'" /></p>');
 7890:         }
 7891:     } else {
 7892:         $r->print(&mt('Helpdesk roles have not yet been created in this domain.'));
 7893:     }
 7894:     # Form Footer
 7895:     $r->print('<input type="hidden" name="action" value="helpdesk" />'
 7896:              .'</form>');
 7897:     return;
 7898: }
 7899: 
 7900: sub domain_adhoc_access {
 7901:     my ($roles,$domcurrent,$accesstypes,$usertypes,$othertitle) = @_;
 7902:     my %domusage;
 7903:     return unless ((ref($roles) eq 'HASH') && (ref($domcurrent) eq 'HASH') && (ref($accesstypes) eq 'ARRAY'));
 7904:     foreach my $role (keys(%{$roles})) {
 7905:         if (ref($domcurrent->{$role}) eq 'HASH') {
 7906:             my $access = $domcurrent->{$role}{'access'};
 7907:             if (($access eq '') || (!grep(/^\Q$access\E$/,@{$accesstypes}))) {
 7908:                 $access = 'all';
 7909:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',&Apache::lonnet::plaintext('dh'),
 7910:                                                                                           &Apache::lonnet::plaintext('da'));
 7911:             } elsif ($access eq 'status') {
 7912:                 if (ref($domcurrent->{$role}{$access}) eq 'ARRAY') {
 7913:                     my @shown;
 7914:                     foreach my $type (@{$domcurrent->{$role}{$access}}) {
 7915:                         unless ($type eq 'default') {
 7916:                             if ($usertypes->{$type}) {
 7917:                                 push(@shown,$usertypes->{$type});
 7918:                             }
 7919:                         }
 7920:                     }
 7921:                     if (grep(/^default$/,@{$domcurrent->{$role}{$access}})) {
 7922:                         push(@shown,$othertitle);
 7923:                     }
 7924:                     if (@shown) {
 7925:                         my $shownstatus = join(' '.&mt('or').' ',@shown);
 7926:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role, and institutional status: [_3]',
 7927:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownstatus);
 7928:                     } else {
 7929:                         $domusage{$role} = &mt('No one in the domain');
 7930:                     }
 7931:                 }
 7932:             } elsif ($access eq 'inc') {
 7933:                 my @dominc = ();
 7934:                 if (ref($domcurrent->{$role}{'inc'}) eq 'ARRAY') {
 7935:                     foreach my $user (@{$domcurrent->{$role}{'inc'}}) {
 7936:                         my ($uname,$udom) = split(/:/,$user);
 7937:                         push(@dominc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7938:                     }
 7939:                     my $showninc = join(', ',@dominc);
 7940:                     if ($showninc ne '') {
 7941:                         $domusage{$role} = &mt('Include any user in domain with active [_1] or [_2] role, except: [_3]',
 7942:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$showninc);
 7943:                     } else {
 7944:                         $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7945:                                                &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7946:                     }
 7947:                 }
 7948:             } elsif ($access eq 'exc') {
 7949:                 my @domexc = ();
 7950:                 if (ref($domcurrent->{$role}{'exc'}) eq 'ARRAY') {
 7951:                     foreach my $user (@{$domcurrent->{$role}{'exc'}}) {
 7952:                         my ($uname,$udom) = split(/:/,$user);
 7953:                         push(@domexc,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom));
 7954:                     }
 7955:                 }
 7956:                 my $shownexc = join(', ',@domexc);
 7957:                 if ($shownexc ne '') {
 7958:                     $domusage{$role} = &mt('Only the following in the domain with active [_1] or [_2] role: [_3]',
 7959:                                            &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'),$shownexc);
 7960:                 } else {
 7961:                     $domusage{$role} = &mt('No one in the domain');
 7962:                 }
 7963:             } elsif ($access eq 'none') {
 7964:                 $domusage{$role} = &mt('No one in the domain');
 7965:             } elsif ($access eq 'dh') {
 7966:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('dh'));
 7967:             } elsif ($access eq 'da') {
 7968:                 $domusage{$role} = &mt('Any user in domain with active [_1] role',&Apache::lonnet::plaintext('da'));
 7969:             } elsif ($access eq 'all') {
 7970:                 $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7971:                                        &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7972:             }
 7973:         } else {
 7974:             $domusage{$role} = &mt('Any user in domain with active [_1] or [_2] role',
 7975:                                    &Apache::lonnet::plaintext('dh'),&Apache::lonnet::plaintext('da'));
 7976:         }
 7977:     }
 7978:     return %domusage;
 7979: }
 7980: 
 7981: sub get_domain_customroles {
 7982:     my ($cdom,$confname) = @_;
 7983:     my %existing=&Apache::lonnet::dump('roles',$cdom,$confname,'rolesdef_');
 7984:     my %customroles;
 7985:     foreach my $key (keys(%existing)) {
 7986:         if ($key=~/^rolesdef\_(\w+)$/) {
 7987:             my $rolename = $1;
 7988:             my %privs;
 7989:             ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 7990:             $customroles{$rolename} = \%privs;
 7991:         }
 7992:     }
 7993:     return %customroles;
 7994: }
 7995: 
 7996: sub role_priv_table {
 7997:     my ($role,$permission,$crstype,$full,$levels,$levelscurrent,$overridden) = @_;
 7998:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
 7999:                    (ref($levelscurrent) eq 'HASH'));
 8000:     my %lt=&Apache::lonlocal::texthash (
 8001:                     'crl'  => 'Course Level Privilege',
 8002:                     'def'  => 'Domain Defaults',
 8003:                     'ove'  => 'Override in Course',
 8004:                     'ine'  => 'In effect',
 8005:                     'dis'  => 'Disabled',
 8006:                     'ena'  => 'Enabled',
 8007:                    );
 8008:     if ($crstype eq 'Community') {
 8009:         $lt{'ove'} = 'Override in Community',
 8010:     }
 8011:     my @status = ('Disabled','Enabled');
 8012:     my (%on,%off);
 8013:     if (ref($overridden) eq 'HASH') {
 8014:         if (ref($overridden->{'on'}) eq 'ARRAY') {
 8015:             map { $on{$_} = 1; } (@{$overridden->{'on'}});
 8016:         }
 8017:         if (ref($overridden->{'off'}) eq 'ARRAY') {
 8018:             map { $off{$_} = 1; } (@{$overridden->{'off'}});
 8019:         }
 8020:     }
 8021:     my $output=&Apache::loncommon::start_data_table().
 8022:                &Apache::loncommon::start_data_table_header_row().
 8023:                '<th>'.$lt{'crl'}.'</th><th>'.$lt{'def'}.'</th><th>'.$lt{'ove'}.
 8024:                '</th><th>'.$lt{'ine'}.'</th>'.
 8025:                &Apache::loncommon::end_data_table_header_row();
 8026:     foreach my $priv (sort(keys(%{$full}))) {
 8027:         next unless ($levels->{'course'}{$priv});
 8028:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
 8029:         my ($default,$ineffect);
 8030:         if ($levelscurrent->{'course'}{$priv}) {
 8031:             $default = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8032:             $ineffect = $default;
 8033:         }
 8034:         my ($customstatus,$checked);
 8035:         $output .= &Apache::loncommon::start_data_table_row().
 8036:                    '<td>'.$privtext.'</td>'.
 8037:                    '<td>'.$default.'</td><td>';
 8038:         if (($levelscurrent->{'course'}{$priv}) && ($off{$priv})) {
 8039:             if ($permission->{'owner'}) {
 8040:                 $checked = ' checked="checked"';
 8041:             }
 8042:             $customstatus = '<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.$lt{'dis'}.'" />';
 8043:             $ineffect = $customstatus;
 8044:         } elsif ((!$levelscurrent->{'course'}{$priv}) && ($on{$priv})) {
 8045:             if ($permission->{'owner'}) {
 8046:                 $checked = ' checked="checked"';
 8047:             }
 8048:             $customstatus = '<img src="/adm/lonIcons/navmap.correct.gif" alt="'.$lt{'ena'}.'" />';
 8049:             $ineffect = $customstatus;
 8050:         }
 8051:         if ($permission->{'owner'}) {
 8052:             $output .= '<input type="checkbox" name="'.$role.'_override" value="'.$priv.'"'.$checked.' />';
 8053:         } else {
 8054:             $output .= $customstatus;
 8055:         }
 8056:         $output .= '</td><td>'.$ineffect.'</td>'.
 8057:                    &Apache::loncommon::end_data_table_row();
 8058:     }
 8059:     $output .= &Apache::loncommon::end_data_table();
 8060:     return $output;
 8061: }
 8062: 
 8063: sub get_adhocrole_settings {
 8064:     my ($cid,$accesstypes,$types,$customroles,$settings,$overridden) = @_;
 8065:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($customroles) eq 'HASH') &&
 8066:                    (ref($settings) eq 'HASH') && (ref($overridden) eq 'HASH'));
 8067:     foreach my $role (split(/,/,$env{'course.'.$cid.'.internal.adhocaccess'})) {
 8068:         my ($curraccess,$rest) = split(/=/,$env{'course.'.$cid.'.internal.adhoc.'.$role});
 8069:         if (($curraccess ne '') && (grep(/^\Q$curraccess\E$/,@{$accesstypes}))) {
 8070:             $settings->{$role}{'access'} = $curraccess;
 8071:             if (($curraccess eq 'status') && (ref($types) eq 'ARRAY')) {
 8072:                 my @status = split(/,/,$rest);
 8073:                 my @currstatus;
 8074:                 foreach my $type (@status) {
 8075:                     if ($type eq 'default') {
 8076:                         push(@currstatus,$type);
 8077:                     } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8078:                         push(@currstatus,$type);
 8079:                     }
 8080:                 }
 8081:                 if (@currstatus) {
 8082:                     $settings->{$role}{$curraccess} = \@currstatus;
 8083:                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 8084:                     my @personnel = split(/,/,$rest);
 8085:                     $settings->{$role}{$curraccess} = \@personnel;
 8086:                 }
 8087:             }
 8088:         }
 8089:     }
 8090:     foreach my $role (keys(%{$customroles})) {
 8091:         if ($env{'course.'.$cid.'.internal.adhocpriv.'.$role}) {
 8092:             my %currentprivs;
 8093:             if (ref($customroles->{$role}) eq 'HASH') {
 8094:                 if (exists($customroles->{$role}{'course'})) {
 8095:                     my %full=();
 8096:                     my %levels= (
 8097:                                   course => {},
 8098:                                   domain => {},
 8099:                                   system => {},
 8100:                                 );
 8101:                     my %levelscurrent=(
 8102:                                         course => {},
 8103:                                         domain => {},
 8104:                                         system => {},
 8105:                                       );
 8106:                     &Apache::lonuserutils::custom_role_privs($customroles->{$role},\%full,\%levels,\%levelscurrent);
 8107:                     %currentprivs = %{$levelscurrent{'course'}};
 8108:                 }
 8109:             }
 8110:             foreach my $item (split(/,/,$env{'course.'.$cid.'.internal.adhocpriv.'.$role})) {
 8111:                 next if ($item eq '');
 8112:                 my ($rule,$rest) = split(/=/,$item);
 8113:                 next unless (($rule eq 'off') || ($rule eq 'on'));
 8114:                 foreach my $priv (split(/:/,$rest)) {
 8115:                     if ($priv ne '') {
 8116:                         if ($rule eq 'off') {
 8117:                             push(@{$overridden->{$role}{'off'}},$priv);
 8118:                             if ($currentprivs{$priv}) {
 8119:                                 push(@{$settings->{$role}{'off'}},$priv);
 8120:                             }
 8121:                         } else {
 8122:                             push(@{$overridden->{$role}{'on'}},$priv);
 8123:                             unless ($currentprivs{$priv}) {
 8124:                                 push(@{$settings->{$role}{'on'}},$priv);
 8125:                             }
 8126:                         }
 8127:                     }
 8128:                 }
 8129:             }
 8130:         }
 8131:     }
 8132:     return;
 8133: }
 8134: 
 8135: sub update_helpdeskaccess {
 8136:     my ($r,$permission,$brcrum) = @_;
 8137:     my $helpitem = 'Course_Helpdesk_Access';
 8138:     push (@{$brcrum},
 8139:              {href => '/adm/createuser?action=helpdesk',
 8140:               text => 'Helpdesk Access',
 8141:               help => $helpitem},
 8142:              {href => '/adm/createuser?action=helpdesk',
 8143:               text => 'Result',
 8144:               help => $helpitem}
 8145:          );
 8146:     my $bread_crumbs_component = 'Helpdesk Staff Access';
 8147:     my $args = { bread_crumbs           => $brcrum,
 8148:                  bread_crumbs_component => $bread_crumbs_component};
 8149: 
 8150:     # print page header
 8151:     $r->print(&header('',$args));
 8152:     unless ((ref($permission) eq 'HASH') && ($permission->{'owner'})) {
 8153:         $r->print('<p class="LC_error">'.&mt('You do not have permission to change helpdesk access.').'</p>');
 8154:         return;
 8155:     }
 8156:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
 8157:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8158:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8159:     my $confname = $cdom.'-domainconfig';
 8160:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($cdom);
 8161:     my $crstype = &Apache::loncommon::course_type();
 8162:     my %customroles = &get_domain_customroles($cdom,$confname);
 8163:     my (%settings,%overridden);
 8164:     &get_adhocrole_settings($env{'request.course.id'},\@accesstypes,
 8165:                             $types,\%customroles,\%settings,\%overridden);
 8166:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($cdom,['dh','da']);
 8167:     my (%changed,%storehash,@todelete);
 8168: 
 8169:     if (keys(%customroles)) {
 8170:         my (%newsettings,@incrs);
 8171:         foreach my $role (keys(%customroles)) {
 8172:             $newsettings{$role} = {
 8173:                                     access => '',
 8174:                                     status => '',
 8175:                                     exc    => '',
 8176:                                     inc    => '',
 8177:                                     on     => '',
 8178:                                     off    => '',
 8179:                                   };
 8180:             my %current;
 8181:             if (ref($settings{$role}) eq 'HASH') {
 8182:                 %current = %{$settings{$role}};
 8183:             }
 8184:             if (ref($overridden{$role}) eq 'HASH') {
 8185:                 $current{'overridden'} = $overridden{$role};
 8186:             }
 8187:             if ($env{'form.'.$role.'_incrs'}) {
 8188:                 my $access = $env{'form.'.$role.'_access'};
 8189:                 if (grep(/^\Q$access\E$/,@accesstypes)) {
 8190:                     push(@incrs,$role);
 8191:                     unless ($current{'access'} eq $access) {
 8192:                         $changed{$role}{'access'} = 1;
 8193:                         $storehash{'internal.adhoc.'.$role} = $access;
 8194:                     }
 8195:                     if ($access eq 'status') {
 8196:                         my @statuses = &Apache::loncommon::get_env_multiple('form.'.$role.'_status');
 8197:                         my @stored;
 8198:                         my @shownstatus;
 8199:                         if (ref($types) eq 'ARRAY') {
 8200:                             foreach my $type (sort(@statuses)) {
 8201:                                 if ($type eq 'default') {
 8202:                                     push(@stored,$type);
 8203:                                 } elsif (grep(/^\Q$type\E$/,@{$types})) {
 8204:                                     push(@stored,$type);
 8205:                                     push(@shownstatus,$usertypes->{$type});
 8206:                                 }
 8207:                             }
 8208:                             if (grep(/^default$/,@statuses)) {
 8209:                                 push(@shownstatus,$othertitle);
 8210:                             }
 8211:                             $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8212:                         }
 8213:                         $newsettings{$role}{'status'} = join(' '.&mt('or').' ',@shownstatus);
 8214:                         if (ref($current{'status'}) eq 'ARRAY') {
 8215:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{'status'});
 8216:                             if (@diffs) {
 8217:                                 $changed{$role}{'status'} = 1;
 8218:                             }
 8219:                         } elsif (@stored) {
 8220:                             $changed{$role}{'status'} = 1;
 8221:                         }
 8222:                     } elsif (($access eq 'inc') || ($access eq 'exc')) {
 8223:                         my @personnel = &Apache::loncommon::get_env_multiple('form.'.$role.'_staff_'.$access);
 8224:                         my @newspecstaff;
 8225:                         my @stored;
 8226:                         my @currstaff;
 8227:                         foreach my $person (sort(@personnel)) {
 8228:                             if ($domhelpdesk{$person}) {
 8229:                                 push(@stored,$person);
 8230:                             }
 8231:                         }
 8232:                         if (ref($current{$access}) eq 'ARRAY') {
 8233:                             my @diffs = &Apache::loncommon::compare_arrays(\@stored,$current{$access});
 8234:                             if (@diffs) {
 8235:                                 $changed{$role}{$access} = 1;
 8236:                             }
 8237:                         } elsif (@stored) {
 8238:                             $changed{$role}{$access} = 1;
 8239:                         }
 8240:                         $storehash{'internal.adhoc.'.$role} .= '='.join(',',@stored);
 8241:                         foreach my $person (@stored) {
 8242:                             my ($uname,$udom) = split(/:/,$person);
 8243:                             push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
 8244:                         }
 8245:                         $newsettings{$role}{$access} = join(', ',sort(@newspecstaff));
 8246:                     }
 8247:                     $newsettings{$role}{'access'} = $access;
 8248:                 }
 8249:             } else {
 8250:                 if (($current{'access'} ne '') && (grep(/^\Q$current{'access'}\E$/,@accesstypes))) {
 8251:                     $changed{$role}{'access'} = 1;
 8252:                     $newsettings{$role} = {};
 8253:                     push(@todelete,'internal.adhoc.'.$role);
 8254:                 }
 8255:             }
 8256:             if (($env{'form.'.$role.'_incrs'}) && ($env{'form.'.$role.'_access'} eq 'none')) {
 8257:                 if (ref($current{'overridden'}) eq 'HASH') {
 8258:                     push(@todelete,'internal.adhocpriv.'.$role);
 8259:                 }
 8260:             } else {
 8261:                 my %full=();
 8262:                 my %levels= (
 8263:                              course => {},
 8264:                              domain => {},
 8265:                              system => {},
 8266:                             );
 8267:                 my %levelscurrent=(
 8268:                                    course => {},
 8269:                                    domain => {},
 8270:                                    system => {},
 8271:                                   );
 8272:                 &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 8273:                 my (@updatedon,@updatedoff,@override);
 8274:                 @override = &Apache::loncommon::get_env_multiple('form.'.$role.'_override');
 8275:                 if (@override) {
 8276:                     foreach my $priv (sort(keys(%full))) {
 8277:                         next unless ($levels{'course'}{$priv});
 8278:                         if (grep(/^\Q$priv\E$/,@override)) {
 8279:                             if ($levelscurrent{'course'}{$priv}) {
 8280:                                 push(@updatedoff,$priv);
 8281:                             } else {
 8282:                                 push(@updatedon,$priv);
 8283:                             }
 8284:                         }
 8285:                     }
 8286:                 }
 8287:                 if (@updatedon) {
 8288:                     $newsettings{$role}{'on'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedon));
 8289:                 }
 8290:                 if (@updatedoff) {
 8291:                     $newsettings{$role}{'off'} = join('</li><li>', map { &Apache::lonnet::plaintext($_,$crstype) } (@updatedoff));
 8292:                 }
 8293:                 if (ref($current{'overridden'}) eq 'HASH') {
 8294:                     if (ref($current{'overridden'}{'on'}) eq 'ARRAY') {
 8295:                         if (@updatedon) {
 8296:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedon,$current{'overridden'}{'on'});
 8297:                             if (@diffs) {
 8298:                                 $changed{$role}{'on'} = 1;
 8299:                             }
 8300:                         } else {
 8301:                             $changed{$role}{'on'} = 1;
 8302:                         }
 8303:                     } elsif (@updatedon) {
 8304:                         $changed{$role}{'on'} = 1;
 8305:                     }
 8306:                     if (ref($current{'overridden'}{'off'}) eq 'ARRAY') {
 8307:                         if (@updatedoff) {
 8308:                             my @diffs = &Apache::loncommon::compare_arrays(\@updatedoff,$current{'overridden'}{'off'});
 8309:                             if (@diffs) {
 8310:                                 $changed{$role}{'off'} = 1;
 8311:                             }
 8312:                         } else {
 8313:                             $changed{$role}{'off'} = 1;
 8314:                         }
 8315:                     } elsif (@updatedoff) {
 8316:                         $changed{$role}{'off'} = 1;
 8317:                     }
 8318:                 } else {
 8319:                     if (@updatedon) {
 8320:                         $changed{$role}{'on'} = 1;
 8321:                     }
 8322:                     if (@updatedoff) {
 8323:                         $changed{$role}{'off'} = 1;
 8324:                     }
 8325:                 }
 8326:                 if (ref($changed{$role}) eq 'HASH') {
 8327:                     if (($changed{$role}{'on'} || $changed{$role}{'off'})) {
 8328:                         my $newpriv;
 8329:                         if (@updatedon) {
 8330:                             $newpriv = 'on='.join(':',@updatedon);
 8331:                         }
 8332:                         if (@updatedoff) {
 8333:                             $newpriv .= ($newpriv ? ',' : '' ).'off='.join(':',@updatedoff);
 8334:                         }
 8335:                         if ($newpriv eq '') {
 8336:                             push(@todelete,'internal.adhocpriv.'.$role);
 8337:                         } else {
 8338:                             $storehash{'internal.adhocpriv.'.$role} = $newpriv;
 8339:                         }
 8340:                     }
 8341:                 }
 8342:             }
 8343:         }
 8344:         if (@incrs) {
 8345:             $storehash{'internal.adhocaccess'} = join(',',@incrs);
 8346:         } elsif (@todelete) {
 8347:             push(@todelete,'internal.adhocaccess');
 8348:         }
 8349:         if (keys(%changed)) {
 8350:             my ($putres,$delres);
 8351:             if (keys(%storehash)) {
 8352:                 $putres = &Apache::lonnet::put('environment',\%storehash,$cdom,$cnum);
 8353:                 my %newenvhash;
 8354:                 foreach my $key (keys(%storehash)) {
 8355:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $storehash{$key};
 8356:                 }
 8357:                 &Apache::lonnet::appenv(\%newenvhash);
 8358:             }
 8359:             if (@todelete) {
 8360:                 $delres = &Apache::lonnet::del('environment',\@todelete,$cdom,$cnum);
 8361:                 foreach my $key (@todelete) {
 8362:                     &Apache::lonnet::delenv('course.'.$env{'request.course.id'}.'.'.$key);
 8363:                 }
 8364:             }
 8365:             if (($putres eq 'ok') || ($delres eq 'ok')) {
 8366:                 my %domconfig = &Apache::lonnet::get_dom('configuration',['helpsettings'],$cdom);
 8367:                 my (%domcurrent,%ordered,%description,%domusage);
 8368:                 if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 8369:                     if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 8370:                         %domcurrent = %{$domconfig{'helpsettings'}{'adhoc'}};
 8371:                     }
 8372:                 }
 8373:                 my $count = 0;
 8374:                 foreach my $role (sort(keys(%customroles))) {
 8375:                     my ($order,$desc);
 8376:                     if (ref($domcurrent{$role}) eq 'HASH') {
 8377:                         $order = $domcurrent{$role}{'order'};
 8378:                         $desc = $domcurrent{$role}{'desc'};
 8379:                     }
 8380:                     if ($order eq '') {
 8381:                         $order = $count;
 8382:                     }
 8383:                     $ordered{$order} = $role;
 8384:                     if ($desc ne '') {
 8385:                         $description{$role} = $desc;
 8386:                     } else {
 8387:                         $description{$role}= $role;
 8388:                     }
 8389:                     $count++;
 8390:                 }
 8391:                 my @roles_by_num = ();
 8392:                 foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 8393:                     push(@roles_by_num,$ordered{$item});
 8394:                 }
 8395:                 %domusage = &domain_adhoc_access(\%changed,\%domcurrent,\@accesstypes,$usertypes,$othertitle);
 8396:                 $r->print(&mt('Helpdesk access settings have been changed as follows').'<br />');
 8397:                 $r->print('<ul>');
 8398:                 foreach my $role (@roles_by_num) {
 8399:                     next unless (ref($changed{$role}) eq 'HASH');
 8400:                     $r->print('<li>'.&mt('Ad hoc role').': <b>'.$description{$role}.'</b>'.
 8401:                               '<ul>');
 8402:                     if ($changed{$role}{'access'} || $changed{$role}{'status'} || $changed{$role}{'inc'} || $changed{$role}{'exc'}) {
 8403:                         $r->print('<li>');
 8404:                         if ($env{'form.'.$role.'_incrs'}) {
 8405:                             if ($newsettings{$role}{'access'} eq 'all') {
 8406:                                 $r->print(&mt('All helpdesk staff can access '.lc($crstype).' with this role.'));
 8407:                             } elsif ($newsettings{$role}{'access'} eq 'dh') {
 8408:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8409:                                               &Apache::lonnet::plaintext('dh')));
 8410:                             } elsif ($newsettings{$role}{'access'} eq 'da') {
 8411:                                 $r->print(&mt('Helpdesk staff can use this role if they have an active [_1] role',
 8412:                                               &Apache::lonnet::plaintext('da')));
 8413:                             } elsif ($newsettings{$role}{'access'} eq 'none') {
 8414:                                 $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8415:                             } elsif ($newsettings{$role}{'access'} eq 'status') {
 8416:                                 if ($newsettings{$role}{'status'}) {
 8417:                                     my ($access,$rest) = split(/=/,$storehash{'internal.adhoc.'.$role});
 8418:                                     if (split(/,/,$rest) > 1) {
 8419:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is one of: [_1].',
 8420:                                                       $newsettings{$role}{'status'}));
 8421:                                     } else {
 8422:                                         $r->print(&mt('Helpdesk staff can use this role if their institutional type is: [_1].',
 8423:                                                       $newsettings{$role}{'status'}));
 8424:                                     }
 8425:                                 } else {
 8426:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8427:                                 }
 8428:                             } elsif ($newsettings{$role}{'access'} eq 'exc') {
 8429:                                 if ($newsettings{$role}{'exc'}) {
 8430:                                     $r->print(&mt('Helpdesk staff who can use this role are as follows:').' '.$newsettings{$role}{'exc'}.'.');
 8431:                                 } else {
 8432:                                     $r->print(&mt('No helpdesk staff can access '.lc($crstype).' with this role.'));
 8433:                                 }
 8434:                             } elsif ($newsettings{$role}{'access'} eq 'inc') {
 8435:                                 if ($newsettings{$role}{'inc'}) {
 8436:                                     $r->print(&mt('All helpdesk staff may use this role except the following:').' '.$newsettings{$role}{'inc'}.'.');
 8437:                                 } else {
 8438:                                     $r->print(&mt('All helpdesk staff may use this role.'));
 8439:                                 }
 8440:                             }
 8441:                         } else {
 8442:                             $r->print(&mt('Default access set in the domain now applies.').'<br />'.
 8443:                                       '<span class="LC_cusr_emph">'.$domusage{$role}.'</span>');
 8444:                         }
 8445:                         $r->print('</li>');
 8446:                     }
 8447:                     unless ($newsettings{$role}{'access'} eq 'none') {
 8448:                         if ($changed{$role}{'off'}) {
 8449:                             if ($newsettings{$role}{'off'}) {
 8450:                                 $r->print('<li>'.&mt('Privileges which are available by default for this ad hoc role, but are disabled for this specific '.lc($crstype).':').
 8451:                                           '<ul><li>'.$newsettings{$role}{'off'}.'</li></ul></li>');
 8452:                             } else {
 8453:                                 $r->print('<li>'.&mt('All privileges available by default for this ad hoc role are enabled.').'</li>');
 8454:                             }
 8455:                         }
 8456:                         if ($changed{$role}{'on'}) {
 8457:                             if ($newsettings{$role}{'on'}) {
 8458:                                 $r->print('<li>'.&mt('Privileges which are not available by default for this ad hoc role, but are enabled for this specific '.lc($crstype).':').
 8459:                                           '<ul><li>'.$newsettings{$role}{'on'}.'</li></ul></li>');
 8460:                             } else {
 8461:                                 $r->print('<li>'.&mt('None of the privileges unavailable by default for this ad hoc role are enabled.').'</li>');
 8462:                             }
 8463:                         }
 8464:                     }
 8465:                     $r->print('</ul></li>');
 8466:                 }
 8467:                 $r->print('</ul>');
 8468:             }
 8469:         } else {
 8470:             $r->print(&mt('No changes made to helpdesk access settings.'));
 8471:         }
 8472:     }
 8473:     return;
 8474: }
 8475: 
 8476: #-------------------------------------------------- functions for &phase_two
 8477: sub user_search_result {
 8478:     my ($context,$srch) = @_;
 8479:     my %allhomes;
 8480:     my %inst_matches;
 8481:     my %srch_results;
 8482:     my ($response,$currstate,$forcenewuser,$dirsrchres);
 8483:     $srch->{'srchterm'} =~ s/\s+/ /g;
 8484:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
 8485:         $response = &mt('Invalid search.');
 8486:     }
 8487:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 8488:         $response = &mt('Invalid search.');
 8489:     }
 8490:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
 8491:         $response = &mt('Invalid search.');
 8492:     }
 8493:     if ($srch->{'srchterm'} eq '') {
 8494:         $response = &mt('You must enter a search term.');
 8495:     }
 8496:     if ($srch->{'srchterm'} =~ /^\s+$/) {
 8497:         $response = &mt('Your search term must contain more than just spaces.');
 8498:     }
 8499:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 8500:         if (($srch->{'srchdomain'} eq '') || 
 8501: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
 8502:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 8503:         }
 8504:     }
 8505:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 8506:         ($srch->{'srchin'} eq 'alc')) {
 8507:         if ($srch->{'srchby'} eq 'uname') {
 8508:             my $unamecheck = $srch->{'srchterm'};
 8509:             if ($srch->{'srchtype'} eq 'contains') {
 8510:                 if ($unamecheck !~ /^\w/) {
 8511:                     $unamecheck = 'a'.$unamecheck; 
 8512:                 }
 8513:             }
 8514:             if ($unamecheck !~ /^$match_username$/) {
 8515:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 8516:             }
 8517:         }
 8518:     }
 8519:     if ($response ne '') {
 8520:         $response = '<span class="LC_warning">'.$response.'</span><br />';
 8521:     }
 8522:     if ($srch->{'srchin'} eq 'instd') {
 8523:         my $instd_chk = &instdirectorysrch_check($srch);
 8524:         if ($instd_chk ne 'ok') {
 8525:             my $domd_chk = &domdirectorysrch_check($srch);
 8526:             $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
 8527:             if ($domd_chk eq 'ok') {
 8528:                 $response .= &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.');
 8529:             }
 8530:             $response .= '<br />';
 8531:         }
 8532:     } else {
 8533:         unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) {
 8534:             my $domd_chk = &domdirectorysrch_check($srch);
 8535:             if (($domd_chk ne 'ok') && ($env{'form.action'} ne 'accesslogs')) {
 8536:                 my $instd_chk = &instdirectorysrch_check($srch);
 8537:                 $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
 8538:                 if ($instd_chk eq 'ok') {
 8539:                     $response .= &mt('You may want to search in the institutional directory instead of in the LON-CAPA domain.');
 8540:                 }
 8541:                 $response .= '<br />';
 8542:             }
 8543:         }
 8544:     }
 8545:     if ($response ne '') {
 8546:         return ($currstate,$response);
 8547:     }
 8548:     if ($srch->{'srchby'} eq 'uname') {
 8549:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 8550:             if ($env{'form.forcenew'}) {
 8551:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 8552:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8553:                     if ($uhome eq 'no_host') {
 8554:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 8555:                         my $showdom = &display_domain_info($env{'request.role.domain'});
 8556:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
 8557:                     } else {
 8558:                         $currstate = 'modify';
 8559:                     }
 8560:                 } else {
 8561:                     $currstate = 'modify';
 8562:                 }
 8563:             } else {
 8564:                 if ($srch->{'srchin'} eq 'dom') {
 8565:                     if ($srch->{'srchtype'} eq 'exact') {
 8566:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 8567:                         if ($uhome eq 'no_host') {
 8568:                             ($currstate,$response,$forcenewuser) =
 8569:                                 &build_search_response($context,$srch,%srch_results);
 8570:                         } else {
 8571:                             $currstate = 'modify';
 8572:                             if ($env{'form.action'} eq 'accesslogs') {
 8573:                                 $currstate = 'activity';
 8574:                             }
 8575:                             my $uname = $srch->{'srchterm'};
 8576:                             my $udom = $srch->{'srchdomain'};
 8577:                             $srch_results{$uname.':'.$udom} =
 8578:                                 { &Apache::lonnet::get('environment',
 8579:                                                        ['firstname',
 8580:                                                         'lastname',
 8581:                                                         'permanentemail'],
 8582:                                                          $udom,$uname)
 8583:                                 };
 8584:                         }
 8585:                     } else {
 8586:                         %srch_results = &Apache::lonnet::usersearch($srch);
 8587:                         ($currstate,$response,$forcenewuser) =
 8588:                             &build_search_response($context,$srch,%srch_results);
 8589:                     }
 8590:                 } else {
 8591:                     my $courseusers = &get_courseusers();
 8592:                     if ($srch->{'srchtype'} eq 'exact') {
 8593:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 8594:                             $currstate = 'modify';
 8595:                         } else {
 8596:                             ($currstate,$response,$forcenewuser) =
 8597:                                 &build_search_response($context,$srch,%srch_results);
 8598:                         }
 8599:                     } else {
 8600:                         foreach my $user (keys(%$courseusers)) {
 8601:                             my ($cuname,$cudomain) = split(/:/,$user);
 8602:                             if ($cudomain eq $srch->{'srchdomain'}) {
 8603:                                 my $matched = 0;
 8604:                                 if ($srch->{'srchtype'} eq 'begins') {
 8605:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
 8606:                                         $matched = 1;
 8607:                                     }
 8608:                                 } else {
 8609:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
 8610:                                         $matched = 1;
 8611:                                     }
 8612:                                 }
 8613:                                 if ($matched) {
 8614:                                     $srch_results{$user} = 
 8615: 					{&Apache::lonnet::get('environment',
 8616: 							     ['firstname',
 8617: 							      'lastname',
 8618: 							      'permanentemail'],
 8619: 							      $cudomain,$cuname)};
 8620:                                 }
 8621:                             }
 8622:                         }
 8623:                         ($currstate,$response,$forcenewuser) =
 8624:                             &build_search_response($context,$srch,%srch_results);
 8625:                     }
 8626:                 }
 8627:             }
 8628:         } elsif ($srch->{'srchin'} eq 'alc') {
 8629:             $currstate = 'query';
 8630:         } elsif ($srch->{'srchin'} eq 'instd') {
 8631:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
 8632:             if ($dirsrchres eq 'ok') {
 8633:                 ($currstate,$response,$forcenewuser) = 
 8634:                     &build_search_response($context,$srch,%srch_results);
 8635:             } else {
 8636:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8637:                 $response = '<span class="LC_warning">'.
 8638:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8639:                     '</span><br />'.
 8640:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8641:                     '<br />'; 
 8642:             }
 8643:         }
 8644:     } else {
 8645:         if ($srch->{'srchin'} eq 'dom') {
 8646:             %srch_results = &Apache::lonnet::usersearch($srch);
 8647:             ($currstate,$response,$forcenewuser) = 
 8648:                 &build_search_response($context,$srch,%srch_results); 
 8649:         } elsif ($srch->{'srchin'} eq 'crs') {
 8650:             my $courseusers = &get_courseusers(); 
 8651:             foreach my $user (keys(%$courseusers)) {
 8652:                 my ($uname,$udom) = split(/:/,$user);
 8653:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 8654:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 8655:                 if ($srch->{'srchby'} eq 'lastname') {
 8656:                     if ((($srch->{'srchtype'} eq 'exact') && 
 8657:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 8658:                         (($srch->{'srchtype'} eq 'begins') &&
 8659:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
 8660:                         (($srch->{'srchtype'} eq 'contains') &&
 8661:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 8662:                         $srch_results{$user} = {firstname => $names{'firstname'},
 8663:                                             lastname => $names{'lastname'},
 8664:                                             permanentemail => $emails{'permanentemail'},
 8665:                                            };
 8666:                     }
 8667:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 8668:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 8669:                     $srchlast =~ s/\s+$//;
 8670:                     $srchfirst =~ s/^\s+//;
 8671:                     if ($srch->{'srchtype'} eq 'exact') {
 8672:                         if (($names{'lastname'} eq $srchlast) &&
 8673:                             ($names{'firstname'} eq $srchfirst)) {
 8674:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8675:                                                 lastname => $names{'lastname'},
 8676:                                                 permanentemail => $emails{'permanentemail'},
 8677: 
 8678:                                            };
 8679:                         }
 8680:                     } elsif ($srch->{'srchtype'} eq 'begins') {
 8681:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
 8682:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
 8683:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8684:                                                 lastname => $names{'lastname'},
 8685:                                                 permanentemail => $emails{'permanentemail'},
 8686:                                                };
 8687:                         }
 8688:                     } else {
 8689:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 8690:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 8691:                             $srch_results{$user} = {firstname => $names{'firstname'},
 8692:                                                 lastname => $names{'lastname'},
 8693:                                                 permanentemail => $emails{'permanentemail'},
 8694:                                                };
 8695:                         }
 8696:                     }
 8697:                 }
 8698:             }
 8699:             ($currstate,$response,$forcenewuser) = 
 8700:                 &build_search_response($context,$srch,%srch_results); 
 8701:         } elsif ($srch->{'srchin'} eq 'alc') {
 8702:             $currstate = 'query';
 8703:         } elsif ($srch->{'srchin'} eq 'instd') {
 8704:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
 8705:             if ($dirsrchres eq 'ok') {
 8706:                 ($currstate,$response,$forcenewuser) = 
 8707:                     &build_search_response($context,$srch,%srch_results);
 8708:             } else {
 8709:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
 8710:                 $response = '<span class="LC_warning">'.
 8711:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
 8712:                     '</span><br />'.
 8713:                     &mt('You may want to search in the LON-CAPA domain instead of in the institutional directory.').
 8714:                     '<br />';
 8715:             }
 8716:         }
 8717:     }
 8718:     return ($currstate,$response,$forcenewuser,\%srch_results);
 8719: }
 8720: 
 8721: sub domdirectorysrch_check {
 8722:     my ($srch) = @_;
 8723:     my $response;
 8724:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8725:                                              ['directorysrch'],$srch->{'srchdomain'});
 8726:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8727:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8728:         if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
 8729:             return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
 8730:         }
 8731:         if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
 8732:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8733:                 return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
 8734:             }
 8735:         }
 8736:     }
 8737:     return 'ok';
 8738: }
 8739: 
 8740: sub instdirectorysrch_check {
 8741:     my ($srch) = @_;
 8742:     my $can_search = 0;
 8743:     my $response;
 8744:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 8745:                                              ['directorysrch'],$srch->{'srchdomain'});
 8746:     my $showdom = &display_domain_info($srch->{'srchdomain'});
 8747:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 8748:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 8749:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
 8750:         }
 8751:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 8752:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 8753:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
 8754:             }
 8755:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 8756:             if (!@usertypes) {
 8757:                 push(@usertypes,'default');
 8758:             }
 8759:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 8760:                 foreach my $type (@usertypes) {
 8761:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 8762:                         $can_search = 1;
 8763:                         last;
 8764:                     }
 8765:                 }
 8766:             }
 8767:             if (!$can_search) {
 8768:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 8769:                 my @longtypes; 
 8770:                 foreach my $item (@usertypes) {
 8771:                     if (defined($insttypes->{$item})) { 
 8772:                         push (@longtypes,$insttypes->{$item});
 8773:                     } elsif ($item eq 'default') {
 8774:                         push (@longtypes,&mt('other')); 
 8775:                     }
 8776:                 }
 8777:                 my $insttype_str = join(', ',@longtypes); 
 8778:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
 8779:             }
 8780:         } else {
 8781:             $can_search = 1;
 8782:         }
 8783:     } else {
 8784:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
 8785:     }
 8786:     my %longtext = &Apache::lonlocal::texthash (
 8787:                        uname     => 'username',
 8788:                        lastfirst => 'last name, first name',
 8789:                        lastname  => 'last name',
 8790:                        contains  => 'contains',
 8791:                        exact     => 'as exact match to',
 8792:                        begins    => 'begins with',
 8793:                    );
 8794:     if ($can_search) {
 8795:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 8796:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 8797:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
 8798:             }
 8799:         } else {
 8800:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
 8801:         }
 8802:     }
 8803:     if ($can_search) {
 8804:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
 8805:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
 8806:                 return 'ok';
 8807:             } else {
 8808:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8809:             }
 8810:         } else {
 8811:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
 8812:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
 8813:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 8814:                 return 'ok';
 8815:             } else {
 8816:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
 8817:             }
 8818:         }
 8819:     }
 8820: }
 8821: 
 8822: sub get_courseusers {
 8823:     my %advhash;
 8824:     my $classlist = &Apache::loncoursedata::get_classlist();
 8825:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 8826:     foreach my $role (sort(keys(%coursepersonnel))) {
 8827:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 8828: 	    if (!exists($classlist->{$user})) {
 8829: 		$classlist->{$user} = [];
 8830: 	    }
 8831:         }
 8832:     }
 8833:     return $classlist;
 8834: }
 8835: 
 8836: sub build_search_response {
 8837:     my ($context,$srch,%srch_results) = @_;
 8838:     my ($currstate,$response,$forcenewuser);
 8839:     my %names = (
 8840:           'uname'     => 'username',
 8841:           'lastname'  => 'last name',
 8842:           'lastfirst' => 'last name, first name',
 8843:           'crs'       => 'this course',
 8844:           'dom'       => 'LON-CAPA domain',
 8845:           'instd'     => 'the institutional directory for domain',
 8846:     );
 8847: 
 8848:     my %single = (
 8849:                    begins   => 'A match',
 8850:                    contains => 'A match',
 8851:                    exact    => 'An exact match',
 8852:                  );
 8853:     my %nomatch = (
 8854:                    begins   => 'No match',
 8855:                    contains => 'No match',
 8856:                    exact    => 'No exact match',
 8857:                   );
 8858:     if (keys(%srch_results) > 1) {
 8859:         $currstate = 'select';
 8860:     } else {
 8861:         if (keys(%srch_results) == 1) {
 8862:             if ($env{'form.action'} eq 'accesslogs') {
 8863:                 $currstate = 'activity';
 8864:             } else {
 8865:                 $currstate = 'modify';
 8866:             }
 8867:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 8868:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8869:                 $response .= ': '.&display_domain_info($srch->{'srchdomain'});
 8870:             }
 8871:         } else { # Search has nothing found. Prepare message to user.
 8872:             $response = '<span class="LC_warning">';
 8873:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
 8874:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}: [_2]",
 8875:                                  '<b>'.$srch->{'srchterm'}.'</b>',
 8876:                                  &display_domain_info($srch->{'srchdomain'}));
 8877:             } else {
 8878:                 $response .= &mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} [_1] in $names{$srch->{'srchin'}}.",
 8879:                                  '<b>'.$srch->{'srchterm'}.'</b>');
 8880:             }
 8881:             $response .= '</span>';
 8882: 
 8883:             if ($srch->{'srchin'} ne 'alc') {
 8884:                 $forcenewuser = 1;
 8885:                 my $cansrchinst = 0; 
 8886:                 if (($srch->{'srchdomain'}) && ($env{'form.action'} ne 'accesslogs')) {
 8887:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 8888:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 8889:                         if ($domconfig{'directorysrch'}{'available'}) {
 8890:                             $cansrchinst = 1;
 8891:                         } 
 8892:                     }
 8893:                 }
 8894:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
 8895:                      ($srch->{'srchby'} eq 'lastname')) &&
 8896:                     ($srch->{'srchin'} eq 'dom')) {
 8897:                     if ($cansrchinst) {
 8898:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
 8899:                     }
 8900:                 }
 8901:                 if ($srch->{'srchin'} eq 'crs') {
 8902:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
 8903:                 }
 8904:             }
 8905:             my $createdom = $env{'request.role.domain'};
 8906:             if ($context eq 'requestcrs') {
 8907:                 if ($env{'form.coursedom'} ne '') {
 8908:                     $createdom = $env{'form.coursedom'};
 8909:                 }
 8910:             }
 8911:             unless (($env{'form.action'} eq 'accesslogs') || (($srch->{'srchby'} eq 'uname') && ($srch->{'srchin'} eq 'dom') &&
 8912:                     ($srch->{'srchtype'} eq 'exact') && ($srch->{'srchdomain'} eq $createdom))) {
 8913:                 my $cancreate =
 8914:                     &Apache::lonuserutils::can_create_user($createdom,$context);
 8915:                 my $targetdom = '<span class="LC_cusr_emph">'.$createdom.'</span>';
 8916:                 if ($cancreate) {
 8917:                     my $showdom = &display_domain_info($createdom); 
 8918:                     $response .= '<br /><br />'
 8919:                                 .'<b>'.&mt('To add a new user:').'</b>'
 8920:                                 .'<br />';
 8921:                     if ($context eq 'requestcrs') {
 8922:                         $response .= &mt("(You can only define new users in the new course's domain - [_1])",$targetdom);
 8923:                     } else {
 8924:                         $response .= &mt("(You can only create new users in your current role's domain - [_1])",$targetdom);
 8925:                     }
 8926:                     $response .='<ul><li>'
 8927:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
 8928:                                 .'</li><li>'
 8929:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
 8930:                                 .'</li><li>'
 8931:                                 .&mt('Provide the proposed username')
 8932:                                 .'</li><li>'
 8933:                                 .&mt("Click 'Search'")
 8934:                                 .'</li></ul><br />';
 8935:                 } else {
 8936:                     unless (($context eq 'domain') && ($env{'form.action'} eq 'singleuser')) {
 8937:                         my $helplink = ' href="javascript:helpMenu('."'display'".')"';
 8938:                         $response .= '<br /><br />';
 8939:                         if ($context eq 'requestcrs') {
 8940:                             $response .= &mt("You are not authorized to define new users in the new course's domain - [_1].",$targetdom);
 8941:                         } else {
 8942:                             $response .= &mt("You are not authorized to create new users in your current role's domain - [_1].",$targetdom);
 8943:                         }
 8944:                         $response .= '<br />'
 8945:                                      .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
 8946:                                         ,' <a'.$helplink.'>'
 8947:                                         ,'</a>')
 8948:                                      .'<br />';
 8949:                     }
 8950:                 }
 8951:             }
 8952:         }
 8953:     }
 8954:     return ($currstate,$response,$forcenewuser);
 8955: }
 8956: 
 8957: sub display_domain_info {
 8958:     my ($dom) = @_;
 8959:     my $output = $dom;
 8960:     if ($dom ne '') { 
 8961:         my $domdesc = &Apache::lonnet::domain($dom,'description');
 8962:         if ($domdesc ne '') {
 8963:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
 8964:         }
 8965:     }
 8966:     return $output;
 8967: }
 8968: 
 8969: sub crumb_utilities {
 8970:     my %elements = (
 8971:        crtuser => {
 8972:            srchterm => 'text',
 8973:            srchin => 'selectbox',
 8974:            srchby => 'selectbox',
 8975:            srchtype => 'selectbox',
 8976:            srchdomain => 'selectbox',
 8977:        },
 8978:        crtusername => {
 8979:            srchterm => 'text',
 8980:            srchdomain => 'selectbox',
 8981:        },
 8982:        docustom => {
 8983:            rolename => 'selectbox',
 8984:            newrolename => 'textbox',
 8985:        },
 8986:        studentform => {
 8987:            srchterm => 'text',
 8988:            srchin => 'selectbox',
 8989:            srchby => 'selectbox',
 8990:            srchtype => 'selectbox',
 8991:            srchdomain => 'selectbox',
 8992:        },
 8993:     );
 8994: 
 8995:     my $jsback .= qq|
 8996: function backPage(formname,prevphase,prevstate) {
 8997:     if (typeof prevphase == 'undefined') {
 8998:         formname.phase.value = '';
 8999:     }
 9000:     else {  
 9001:         formname.phase.value = prevphase;
 9002:     }
 9003:     if (typeof prevstate == 'undefined') {
 9004:         formname.currstate.value = '';
 9005:     }
 9006:     else {
 9007:         formname.currstate.value = prevstate;
 9008:     }
 9009:     formname.submit();
 9010: }
 9011: |;
 9012:     return ($jsback,\%elements);
 9013: }
 9014: 
 9015: sub course_level_table {
 9016:     my ($inccourses,$showcredits,$defaultcredits) = @_;
 9017:     return unless (ref($inccourses) eq 'HASH');
 9018:     my $table = '';
 9019: # Custom Roles?
 9020: 
 9021:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9022:     my %lt=&Apache::lonlocal::texthash(
 9023:             'exs'  => "Existing sections",
 9024:             'new'  => "Define new section",
 9025:             'ssd'  => "Set Start Date",
 9026:             'sed'  => "Set End Date",
 9027:             'crl'  => "Course Level",
 9028:             'act'  => "Activate",
 9029:             'rol'  => "Role",
 9030:             'ext'  => "Extent",
 9031:             'grs'  => "Section",
 9032:             'crd'  => "Credits",
 9033:             'sta'  => "Start",
 9034:             'end'  => "End"
 9035:     );
 9036: 
 9037:     foreach my $protectedcourse (sort(keys(%{$inccourses}))) {
 9038: 	my $thiscourse=$protectedcourse;
 9039: 	$thiscourse=~s:_:/:g;
 9040: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 9041:         my $isowner = &Apache::lonuserutils::is_courseowner($protectedcourse,$coursedata{'internal.courseowner'});
 9042: 	my $area=$coursedata{'description'};
 9043:         my $crstype=$coursedata{'type'};
 9044: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 9045: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 9046:         my %sections_count;
 9047:         if (defined($env{'request.course.id'})) {
 9048:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 9049:                 %sections_count = 
 9050: 		    &Apache::loncommon::get_sections($domain,$cnum);
 9051:             }
 9052:         }
 9053:         my @roles = &Apache::lonuserutils::roles_by_context('course','',$crstype);
 9054: 	foreach my $role (@roles) {
 9055:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
 9056: 	    if ((&Apache::lonnet::allowed('c'.$role,$thiscourse)) ||
 9057:                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
 9058:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9059:                                             $plrole,\%sections_count,\%lt,
 9060:                                             $showcredits,$defaultcredits,$crstype);
 9061:             } elsif ($env{'request.course.sec'} ne '') {
 9062:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
 9063:                                              $env{'request.course.sec'})) {
 9064:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9065:                                                 $plrole,\%sections_count,\%lt,
 9066:                                                 $showcredits,$defaultcredits,$crstype);
 9067:                 }
 9068:             }
 9069:         }
 9070:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 9071:             foreach my $cust (sort(keys(%customroles))) {
 9072:                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
 9073:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
 9074:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
 9075:                                             $cust,\%sections_count,\%lt,
 9076:                                             $showcredits,$defaultcredits,$crstype);
 9077:             }
 9078: 	}
 9079:     }
 9080:     return '' if ($table eq ''); # return nothing if there is nothing 
 9081:                                  # in the table
 9082:     my $result;
 9083:     if (!$env{'request.course.id'}) {
 9084:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
 9085:     }
 9086:     $result .= 
 9087: &Apache::loncommon::start_data_table().
 9088: &Apache::loncommon::start_data_table_header_row().
 9089: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9090: '<th>'.$lt{'ext'}.'</th><th>'."\n";
 9091:     if ($showcredits) {
 9092:         $result .= $lt{'crd'}.'</th>';
 9093:     }
 9094:     $result .=
 9095: '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 9096: '<th>'.$lt{'end'}.'</th>'.
 9097: &Apache::loncommon::end_data_table_header_row().
 9098: $table.
 9099: &Apache::loncommon::end_data_table();
 9100:     return $result;
 9101: }
 9102: 
 9103: sub course_level_row {
 9104:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
 9105:         $lt,$showcredits,$defaultcredits,$crstype) = @_;
 9106:     my $creditem;
 9107:     my $row = &Apache::loncommon::start_data_table_row().
 9108:               ' <td><input type="checkbox" name="act_'.
 9109:               $protectedcourse.'_'.$role.'" /></td>'."\n".
 9110:               ' <td>'.$plrole.'</td>'."\n".
 9111:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 9112:     if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
 9113:         $row .= 
 9114:             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
 9115:             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
 9116:     } else {
 9117:         $row .= '<td>&nbsp;</td>';
 9118:     }
 9119:     if (($role eq 'cc') || ($role eq 'co')) {
 9120:         $row .= '<td>&nbsp;</td>';
 9121:     } elsif ($env{'request.course.sec'} ne '') {
 9122:         $row .= ' <td><input type="hidden" value="'.
 9123:                 $env{'request.course.sec'}.'" '.
 9124:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
 9125:                 $env{'request.course.sec'}.'</td>';
 9126:     } else {
 9127:         if (ref($sections_count) eq 'HASH') {
 9128:             my $currsec = 
 9129:                 &Apache::lonuserutils::course_sections($sections_count,
 9130:                                                        $protectedcourse.'_'.$role);
 9131:             $row .= '<td><table class="LC_createuser">'."\n".
 9132:                     '<tr class="LC_section_row">'."\n".
 9133:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
 9134:                        $currsec.'</td>'."\n".
 9135:                      ' <td>&nbsp;&nbsp;</td>'."\n".
 9136:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
 9137:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
 9138:                      '" value="" />'.
 9139:                      '<input type="hidden" '.
 9140:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
 9141:                      '</tr></table></td>'."\n";
 9142:         } else {
 9143:             $row .= '<td><input type="text" size="10" '.
 9144:                     'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
 9145:         }
 9146:     }
 9147:     $row .= <<ENDTIMEENTRY;
 9148: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
 9149: <a href=
 9150: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
 9151: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
 9152: <a href=
 9153: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
 9154: ENDTIMEENTRY
 9155:     $row .= &Apache::loncommon::end_data_table_row();
 9156:     return $row;
 9157: }
 9158: 
 9159: sub course_level_dc {
 9160:     my ($dcdom,$showcredits) = @_;
 9161:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 9162:     my @roles = &Apache::lonuserutils::roles_by_context('course');
 9163:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 9164:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 9165:                       '<input type="hidden" name="dccourse" value="" />';
 9166:     my $courseform=&Apache::loncommon::selectcourse_link
 9167:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Select','crstype');
 9168:     my $credit_elem;
 9169:     if ($showcredits) {
 9170:         $credit_elem = 'credits';
 9171:     }
 9172:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu','role','Course/Community Browser',$credit_elem);
 9173:     my %lt=&Apache::lonlocal::texthash(
 9174:                     'rol'  => "Role",
 9175:                     'grs'  => "Section",
 9176:                     'exs'  => "Existing sections",
 9177:                     'new'  => "Define new section", 
 9178:                     'sta'  => "Start",
 9179:                     'end'  => "End",
 9180:                     'ssd'  => "Set Start Date",
 9181:                     'sed'  => "Set End Date",
 9182:                     'scc'  => "Course/Community",
 9183:                     'crd'  => "Credits",
 9184:                   );
 9185:     my $header = '<h4>'.&mt('Course/Community Level').'</h4>'.
 9186:                  &Apache::loncommon::start_data_table().
 9187:                  &Apache::loncommon::start_data_table_header_row().
 9188:                  '<th>'.$lt{'scc'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
 9189:                  '<th>'.$lt{'grs'}.'</th>'."\n";
 9190:     $header .=   '<th>'.$lt{'crd'}.'</th>'."\n" if ($showcredits);
 9191:     $header .=   '<th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'."\n".
 9192:                  &Apache::loncommon::end_data_table_header_row();
 9193:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 9194:                      '<td><br /><span class="LC_nobreak"><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc','','','','crstype'".')" />'.
 9195:                      $courseform.('&nbsp;' x4).'</span></td>'."\n".
 9196:                      '<td valign="top"><br /><select name="role">'."\n";
 9197:     foreach my $role (@roles) {
 9198:         my $plrole=&Apache::lonnet::plaintext($role);
 9199:         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
 9200:     }
 9201:     if ( keys(%customroles) > 0) {
 9202:         foreach my $cust (sort(keys(%customroles))) {
 9203:             my $custrole='cr_cr_'.$env{'user.domain'}.
 9204:                     '_'.$env{'user.name'}.'_'.$cust;
 9205:             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
 9206:         }
 9207:     }
 9208:     $otheritems .= '</select></td><td>'.
 9209:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 9210:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 9211:                      ' <option value="">&lt;--'.&mt('Pick course first').'</option></select></td>'.
 9212:                      '<td>&nbsp;&nbsp;</td>'.
 9213:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 9214:                      '<input type="text" name="newsec" value="" />'.
 9215:                      '<input type="hidden" name="section" value="" />'.
 9216:                      '<input type="hidden" name="groups" value="" />'.
 9217:                      '<input type="hidden" name="crstype" value="" /></td>'.
 9218:                      '</tr></table></td>'."\n";
 9219:     if ($showcredits) {
 9220:         $otheritems .= '<td><br />'."\n".
 9221:                        '<input type="text" size="3" name="credits" value="" /></td>'."\n";
 9222:     }
 9223:     $otheritems .= <<ENDTIMEENTRY;
 9224: <td><br /><input type="hidden" name="start" value='' />
 9225: <a href=
 9226: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 9227: <td><br /><input type="hidden" name="end" value='' />
 9228: <a href=
 9229: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 9230: ENDTIMEENTRY
 9231:     $otheritems .= &Apache::loncommon::end_data_table_row().
 9232:                    &Apache::loncommon::end_data_table()."\n";
 9233:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 9234: }
 9235: 
 9236: sub update_selfenroll_config {
 9237:     my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
 9238:     return unless (ref($currsettings) eq 'HASH');
 9239:     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
 9240:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9241:     my (%changes,%warning);
 9242:     my $curr_types;
 9243:     my %noedit;
 9244:     unless ($context eq 'domain') {
 9245:         %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
 9246:     }
 9247:     if (ref($row) eq 'ARRAY') {
 9248:         foreach my $item (@{$row}) {
 9249:             next if ($noedit{$item});
 9250:             if ($item eq 'enroll_dates') {
 9251:                 my (%currenrolldate,%newenrolldate);
 9252:                 foreach my $type ('start','end') {
 9253:                     $currenrolldate{$type} = $currsettings->{'selfenroll_'.$type.'_date'};
 9254:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
 9255:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
 9256:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
 9257:                     }
 9258:                 }
 9259:             } elsif ($item eq 'access_dates') {
 9260:                 my (%currdate,%newdate);
 9261:                 foreach my $type ('start','end') {
 9262:                     $currdate{$type} = $currsettings->{'selfenroll_'.$type.'_access'};
 9263:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
 9264:                     if ($newdate{$type} ne $currdate{$type}) {
 9265:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
 9266:                     }
 9267:                 }
 9268:             } elsif ($item eq 'types') {
 9269:                 $curr_types = $currsettings->{'selfenroll_'.$item};
 9270:                 if ($env{'form.selfenroll_all'}) {
 9271:                     if ($curr_types ne '*') {
 9272:                         $changes{'internal.selfenroll_types'} = '*';
 9273:                     } else {
 9274:                         next;
 9275:                     }
 9276:                 } else {
 9277:                     my %currdoms;
 9278:                     my @entries = split(/;/,$curr_types);
 9279:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
 9280:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
 9281:                     my $newnum = 0;
 9282:                     my @latesttypes;
 9283:                     foreach my $num (@activations) {
 9284:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
 9285:                         if (@types > 0) {
 9286:                             @types = sort(@types);
 9287:                             my $typestr = join(',',@types);
 9288:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
 9289:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9290:                             $currdoms{$typedom} = 1;
 9291:                             $newnum ++;
 9292:                         }
 9293:                     }
 9294:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {
 9295:                         if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
 9296:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
 9297:                             if (@types > 0) {
 9298:                                 @types = sort(@types);
 9299:                                 my $typestr = join(',',@types);
 9300:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
 9301:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
 9302:                                 $currdoms{$typedom} = 1;
 9303:                                 $newnum ++;
 9304:                             }
 9305:                         }
 9306:                     }
 9307:                     if ($env{'form.selfenroll_newdom'} ne '') {
 9308:                         my $typedom = $env{'form.selfenroll_newdom'};
 9309:                         if ((!defined($currdoms{$typedom})) && 
 9310:                             (&Apache::lonnet::domain($typedom) ne '')) {
 9311:                             my $typestr;
 9312:                             my ($othertitle,$usertypes,$types) = 
 9313:                                 &Apache::loncommon::sorted_inst_types($typedom);
 9314:                             my $othervalue = 'any';
 9315:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 9316:                                 if (@{$types} > 0) {
 9317:                                     my @esc_types = map { &escape($_); } @{$types};
 9318:                                     $othervalue = 'other';
 9319:                                     $typestr = join(',',(@esc_types,$othervalue));
 9320:                                 }
 9321:                                 $typestr = $othervalue;
 9322:                             } else {
 9323:                                 $typestr = $othervalue;
 9324:                             } 
 9325:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
 9326:                             $newnum ++ ;
 9327:                         }
 9328:                     }
 9329:                     my $selfenroll_types = join(';',@latesttypes);
 9330:                     if ($selfenroll_types ne $curr_types) {
 9331:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
 9332:                     }
 9333:                 }
 9334:             } elsif ($item eq 'limit') {
 9335:                 my $newlimit = $env{'form.selfenroll_limit'};
 9336:                 my $newcap = $env{'form.selfenroll_cap'};
 9337:                 $newcap =~s/\s+//g;
 9338:                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9339:                 $currlimit = 'none' if ($currlimit eq '');
 9340:                 my $currcap = $currsettings->{'selfenroll_cap'};
 9341:                 if ($newlimit ne $currlimit) {
 9342:                     if ($newlimit ne 'none') {
 9343:                         if ($newcap =~ /^\d+$/) {
 9344:                             if ($newcap ne $currcap) {
 9345:                                 $changes{'internal.selfenroll_cap'} = $newcap;
 9346:                             }
 9347:                             $changes{'internal.selfenroll_limit'} = $newlimit;
 9348:                         } else {
 9349:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9350:                                 &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
 9351:                         }
 9352:                     } elsif ($currcap ne '') {
 9353:                         $changes{'internal.selfenroll_cap'} = '';
 9354:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
 9355:                     }
 9356:                 } elsif ($currlimit ne 'none') {
 9357:                     if ($newcap =~ /^\d+$/) {
 9358:                         if ($newcap ne $currcap) {
 9359:                             $changes{'internal.selfenroll_cap'} = $newcap;
 9360:                         }
 9361:                     } else {
 9362:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.
 9363:                             &mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
 9364:                     }
 9365:                 }
 9366:             } elsif ($item eq 'approval') {
 9367:                 my (@currnotified,@newnotified);
 9368:                 my $currapproval = $currsettings->{'selfenroll_approval'};
 9369:                 my $currnotifylist = $currsettings->{'selfenroll_notifylist'};
 9370:                 if ($currnotifylist ne '') {
 9371:                     @currnotified = split(/,/,$currnotifylist);
 9372:                     @currnotified = sort(@currnotified);
 9373:                 }
 9374:                 my $newapproval = $env{'form.selfenroll_approval'};
 9375:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
 9376:                 @newnotified = sort(@newnotified);
 9377:                 if ($newapproval ne $currapproval) {
 9378:                     $changes{'internal.selfenroll_approval'} = $newapproval;
 9379:                     if (!$newapproval) {
 9380:                         if ($currnotifylist ne '') {
 9381:                             $changes{'internal.selfenroll_notifylist'} = '';
 9382:                         }
 9383:                     } else {
 9384:                         my @differences =  
 9385:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9386:                         if (@differences > 0) {
 9387:                             if (@newnotified > 0) {
 9388:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9389:                             } else {
 9390:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9391:                             }
 9392:                         }
 9393:                     }
 9394:                 } else {
 9395:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
 9396:                     if (@differences > 0) {
 9397:                         if (@newnotified > 0) {
 9398:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
 9399:                         } else {
 9400:                             $changes{'internal.selfenroll_notifylist'} = '';
 9401:                         }
 9402:                     }
 9403:                 }
 9404:             } else {
 9405:                 my $curr_val = $currsettings->{'selfenroll_'.$item};
 9406:                 my $newval = $env{'form.selfenroll_'.$item};
 9407:                 if ($item eq 'section') {
 9408:                     $newval = $env{'form.sections'};
 9409:                     if (defined($curr_groups{$newval})) {
 9410:                         $newval = $curr_val;
 9411:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.
 9412:                                           &mt('Group names and section names must be distinct');
 9413:                     } elsif ($newval eq 'all') {
 9414:                         $newval = $curr_val;
 9415:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
 9416:                     }
 9417:                     if ($newval eq '') {
 9418:                         $newval = 'none';
 9419:                     }
 9420:                 }
 9421:                 if ($newval ne $curr_val) {
 9422:                     $changes{'internal.selfenroll_'.$item} = $newval;
 9423:                 }
 9424:             }
 9425:         }
 9426:         if (keys(%warning) > 0) {
 9427:             foreach my $item (@{$row}) {
 9428:                 if (exists($warning{$item})) {
 9429:                     $r->print($warning{$item}.'<br />');
 9430:                 }
 9431:             } 
 9432:         }
 9433:         if (keys(%changes) > 0) {
 9434:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
 9435:             if ($putresult eq 'ok') {
 9436:                 if ((exists($changes{'internal.selfenroll_types'})) ||
 9437:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
 9438:                     (exists($changes{'internal.selfenroll_end_date'}))) {
 9439:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
 9440:                                                                 $cnum,undef,undef,'Course');
 9441:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 9442:                     if (ref($crsinfo{$cid}) eq 'HASH') {
 9443:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
 9444:                             if (exists($changes{'internal.'.$item})) {
 9445:                                 $crsinfo{$cid}{$item} = $changes{'internal.'.$item};
 9446:                             }
 9447:                         }
 9448:                         my $crsputresult =
 9449:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
 9450:                                                          $chome,'notime');
 9451:                     }
 9452:                 }
 9453:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
 9454:                 foreach my $item (@{$row}) {
 9455:                     my $title = $item;
 9456:                     if (ref($lt) eq 'HASH') {
 9457:                         $title = $lt->{$item};
 9458:                     }
 9459:                     if ($item eq 'enroll_dates') {
 9460:                         foreach my $type ('start','end') {
 9461:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
 9462:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
 9463:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9464:                                           $title,$type,$newdate).'</li>');
 9465:                             }
 9466:                         }
 9467:                     } elsif ($item eq 'access_dates') {
 9468:                         foreach my $type ('start','end') {
 9469:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
 9470:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
 9471:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
 9472:                                           $title,$type,$newdate).'</li>');
 9473:                             }
 9474:                         }
 9475:                     } elsif ($item eq 'limit') {
 9476:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
 9477:                             (exists($changes{'internal.selfenroll_cap'}))) {
 9478:                             my ($newval,$newcap);
 9479:                             if ($changes{'internal.selfenroll_cap'} ne '') {
 9480:                                 $newcap = $changes{'internal.selfenroll_cap'}
 9481:                             } else {
 9482:                                 $newcap = $currsettings->{'selfenroll_cap'};
 9483:                             }
 9484:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
 9485:                                 $newval = &mt('No limit');
 9486:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
 9487:                                      'allstudents') {
 9488:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9489:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9490:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9491:                             } else {
 9492:                                 my $currlimit =  $currsettings->{'selfenroll_limit'};
 9493:                                 if ($currlimit eq 'allstudents') {
 9494:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
 9495:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
 9496:                                     $newval =  &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
 9497:                                 }
 9498:                             }
 9499:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9500:                         }
 9501:                     } elsif ($item eq 'approval') {
 9502:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
 9503:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
 9504:                             my %selfdescs = &Apache::lonuserutils::selfenroll_default_descs();
 9505:                             my ($newval,$newnotify);
 9506:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
 9507:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
 9508:                             } else {   
 9509:                                 $newnotify = $currsettings->{'selfenroll_notifylist'};
 9510:                             }
 9511:                             if (exists($changes{'internal.selfenroll_approval'})) {
 9512:                                 if ($changes{'internal.selfenroll_approval'} !~ /^[012]$/) {
 9513:                                     $changes{'internal.selfenroll_approval'} = '0';
 9514:                                 }
 9515:                                 $newval = $selfdescs{'approval'}{$changes{'internal.selfenroll_approval'}};
 9516:                             } else {
 9517:                                 my $currapproval = $currsettings->{'selfenroll_approval'}; 
 9518:                                 if ($currapproval !~ /^[012]$/) {
 9519:                                     $currapproval = 0;
 9520:                                 }
 9521:                                 $newval = $selfdescs{'approval'}{$currapproval};
 9522:                             }
 9523:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
 9524:                             if ($newnotify) {
 9525:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
 9526:                             } else {
 9527:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
 9528:                             }
 9529:                             $r->print('</li>'."\n");
 9530:                         }
 9531:                     } else {
 9532:                         if (exists($changes{'internal.selfenroll_'.$item})) {
 9533:                             my $newval = $changes{'internal.selfenroll_'.$item};
 9534:                             if ($item eq 'types') {
 9535:                                 if ($newval eq '') {
 9536:                                     $newval = &mt('None');
 9537:                                 } elsif ($newval eq '*') {
 9538:                                     $newval = &mt('Any user in any domain');
 9539:                                 }
 9540:                             } elsif ($item eq 'registered') {
 9541:                                 if ($newval eq '1') {
 9542:                                     $newval = &mt('Yes');
 9543:                                 } elsif ($newval eq '0') {
 9544:                                     $newval = &mt('No');
 9545:                                 }
 9546:                             }
 9547:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
 9548:                         }
 9549:                     }
 9550:                 }
 9551:                 $r->print('</ul>');
 9552:                 if ($env{'course.'.$cid.'.description'} ne '') {
 9553:                     my %newenvhash;
 9554:                     foreach my $key (keys(%changes)) {
 9555:                         $newenvhash{'course.'.$cid.'.'.$key} = $changes{$key};
 9556:                     }
 9557:                     &Apache::lonnet::appenv(\%newenvhash);
 9558:                 }
 9559:             } else {
 9560:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.
 9561:                           &mt('The error was: [_1].',$putresult));
 9562:             }
 9563:         } else {
 9564:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9565:         }
 9566:     } else {
 9567:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
 9568:     }
 9569:     my $visactions = &cat_visibility();
 9570:     my ($cathash,%cattype);
 9571:     my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
 9572:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 9573:         $cathash = $domconfig{'coursecategories'}{'cats'};
 9574:         $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
 9575:         $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
 9576:     } else {
 9577:         $cathash = {};
 9578:         $cattype{'auth'} = 'std';
 9579:         $cattype{'unauth'} = 'std';
 9580:     }
 9581:     if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
 9582:         $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9583:                   '<br />'.
 9584:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9585:                   '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
 9586:                   '</ul>');
 9587:     } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
 9588:         if ($currsettings->{'uniquecode'}) {
 9589:             $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
 9590:         } else {
 9591:             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9592:                   '<br />'.
 9593:                   '<br />'.$visactions->{'take'}.'<ul>'.
 9594:                   '<li>'.$visactions->{'dc_setcode'}.'</li>'.
 9595:                   '</ul><br />');
 9596:         }
 9597:     } else {
 9598:         my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
 9599:         if (ref($visactions) eq 'HASH') {
 9600:             if (!$visible) {
 9601:                 $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
 9602:                           '<br />');
 9603:                 if (ref($vismsgs) eq 'ARRAY') {
 9604:                     $r->print('<br />'.$visactions->{'take'}.'<ul>');
 9605:                     foreach my $item (@{$vismsgs}) {
 9606:                         $r->print('<li>'.$visactions->{$item}.'</li>');
 9607:                     }
 9608:                     $r->print('</ul>');
 9609:                 }
 9610:                 $r->print($cansetvis);
 9611:             }
 9612:         }
 9613:     } 
 9614:     return;
 9615: }
 9616: 
 9617: #---------------------------------------------- end functions for &phase_two
 9618: 
 9619: #--------------------------------- functions for &phase_two and &phase_three
 9620: 
 9621: #--------------------------end of functions for &phase_two and &phase_three
 9622: 
 9623: 1;
 9624: __END__
 9625: 
 9626: 

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